Decompiled source of Hat Loader v1.2.0

HatLoader.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Alexandria.ItemAPI;
using Alexandria.SoundAPI;
using Alexandria.cAPI;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using SGUI;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("HatLoader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("N/A")]
[assembly: AssemblyProduct("HatLoader")]
[assembly: AssemblyCopyright("Copyright © N/A 2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("13bd8a8a-8724-4ced-af43-687ebc23ca8f")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace HatLoader
{
	[HarmonyPatch]
	public static class AutoHatManager
	{
		public static readonly HashSet<string> RandomHatList = new HashSet<string>();

		public const string RandomHatListFileName = "RandomHatList.txt";

		public static string RandomHatListFilePath;

		public const string RandomHatCommandGroup = "randomhats";

		public static void Init()
		{
			RandomHatListFilePath = Path.Combine(Paths.ConfigPath, "RandomHatList.txt");
			LoadRandomHatList();
			ETGModConsole.Commands.AddGroup("randomhats");
			ConsoleCommandGroup group = ETGModConsole.Commands.GetGroup("randomhats");
			group.AddUnit("addcurrent", (Action<string[]>)delegate
			{
				//IL_0036: 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_00e8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
				if (GameManager.HasInstance)
				{
					if ((Object)(object)GameManager.Instance.PrimaryPlayer == (Object)null)
					{
						((SElement)ETGModConsole.Log((object)"No active player.", false)).Foreground = Color.red;
					}
					else
					{
						HatController component3 = ((Component)GameManager.Instance.PrimaryPlayer).GetComponent<HatController>();
						if (component3 != null)
						{
							Hat currentHat3 = component3.CurrentHat;
							if (currentHat3 != null && !((Object)(object)currentHat3 == (Object)null))
							{
								string hatName3 = currentHat3.hatName;
								string databaseFriendlyHatName3 = HatUtility.GetDatabaseFriendlyHatName(hatName3);
								if (!RandomHatList.Add(databaseFriendlyHatName3))
								{
									((SElement)ETGModConsole.Log((object)("Current hat \"" + databaseFriendlyHatName3 + "\" is already in the random hat list."), false)).Foreground = Color.yellow;
								}
								else
								{
									((SElement)ETGModConsole.Log((object)("Current hat \"" + databaseFriendlyHatName3 + "\" successfully added to the random hat list."), false)).Foreground = Color.green;
									WriteRandomHatList();
								}
								return;
							}
						}
						((SElement)ETGModConsole.Log((object)"The active player isn't wearing a hat.", false)).Foreground = Color.red;
					}
				}
			});
			group.AddUnit("setcurrent", (Action<string[]>)delegate
			{
				//IL_0036: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
				//IL_007f: Unknown result type (might be due to invalid IL or missing references)
				if (GameManager.HasInstance)
				{
					if ((Object)(object)GameManager.Instance.PrimaryPlayer == (Object)null)
					{
						((SElement)ETGModConsole.Log((object)"No active player.", false)).Foreground = Color.red;
					}
					else
					{
						HatController component2 = ((Component)GameManager.Instance.PrimaryPlayer).GetComponent<HatController>();
						if (component2 != null)
						{
							Hat currentHat2 = component2.CurrentHat;
							if (currentHat2 != null && !((Object)(object)currentHat2 == (Object)null))
							{
								string hatName2 = currentHat2.hatName;
								string databaseFriendlyHatName2 = HatUtility.GetDatabaseFriendlyHatName(hatName2);
								RandomHatList.Clear();
								RandomHatList.Add(databaseFriendlyHatName2);
								((SElement)ETGModConsole.Log((object)("Random hat list set to current hat \"" + databaseFriendlyHatName2 + "\""), false)).Foreground = Color.green;
								WriteRandomHatList();
								return;
							}
						}
						((SElement)ETGModConsole.Log((object)"The active player isn't wearing a hat.", false)).Foreground = Color.red;
					}
				}
			});
			group.AddUnit("removecurrent", (Action<string[]>)delegate
			{
				//IL_0036: 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_00e8: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
				if (GameManager.HasInstance)
				{
					if ((Object)(object)GameManager.Instance.PrimaryPlayer == (Object)null)
					{
						((SElement)ETGModConsole.Log((object)"No active player.", false)).Foreground = Color.red;
					}
					else
					{
						HatController component = ((Component)GameManager.Instance.PrimaryPlayer).GetComponent<HatController>();
						if (component != null)
						{
							Hat currentHat = component.CurrentHat;
							if (currentHat != null && !((Object)(object)currentHat == (Object)null))
							{
								string hatName = currentHat.hatName;
								string databaseFriendlyHatName = HatUtility.GetDatabaseFriendlyHatName(hatName);
								if (!RandomHatList.Remove(databaseFriendlyHatName))
								{
									((SElement)ETGModConsole.Log((object)("Current hat \"" + databaseFriendlyHatName + "\" is not in the random hat list."), false)).Foreground = Color.yellow;
								}
								else
								{
									((SElement)ETGModConsole.Log((object)("Current hat \"" + databaseFriendlyHatName + "\" successfully removed from the random hat list."), false)).Foreground = Color.green;
									WriteRandomHatList();
								}
								return;
							}
						}
						((SElement)ETGModConsole.Log((object)"The active player isn't wearing a hat.", false)).Foreground = Color.red;
					}
				}
			});
			group.AddUnit("clear", (Action<string[]>)delegate
			{
				//IL_0044: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				if (RandomHatList.Count <= 0)
				{
					((SElement)ETGModConsole.Log((object)"Random hat list is already empty.", false)).Foreground = Color.yellow;
				}
				else
				{
					RandomHatList.Clear();
					((SElement)ETGModConsole.Log((object)"Successfully cleared the random hat list.", false)).Foreground = Color.green;
					WriteRandomHatList();
				}
			});
			group.AddUnit("log", (Action<string[]>)delegate
			{
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				if (RandomHatList.Count <= 0)
				{
					((SElement)ETGModConsole.Log((object)"Random hat list is empty.", false)).Foreground = Color.yellow;
					return;
				}
				ETGModConsole.Log((object)"Current random hat list:", false);
				foreach (string randomHat in RandomHatList)
				{
					string text = randomHat;
					if (!Hatabase.Hats.ContainsKey(HatUtility.GetDatabaseFriendlyHatName(text)))
					{
						text += "<color=$FF0000>(not currently loaded)</color>";
					}
					ETGModConsole.Log((object)randomHat, false);
				}
			});
			ETGModConsole.CommandDescriptions["randomhats addcurrent"] = "Adds the player's current hat to the random hats list.";
			ETGModConsole.CommandDescriptions["randomhats setcurrent"] = "Sets the random hats list to only contain the player's current hat.";
			ETGModConsole.CommandDescriptions["randomhats removecurrent"] = "Removes the player's current hat from the random hats list.";
			ETGModConsole.CommandDescriptions["randomhats clear"] = "Removes all hats from the random hats list.";
			ETGModConsole.CommandDescriptions["randomhats log"] = "Logs the current hats list to the console.";
		}

		public static void LoadRandomHatList()
		{
			RandomHatList.Clear();
			if (File.Exists(RandomHatListFilePath))
			{
				string[] array = File.ReadAllLines(RandomHatListFilePath);
				foreach (string item in array)
				{
					RandomHatList.Add(item);
				}
			}
		}

		public static void WriteRandomHatList()
		{
			string directoryName = Path.GetDirectoryName(RandomHatListFilePath);
			if (!Directory.Exists(directoryName))
			{
				Directory.CreateDirectory(directoryName);
			}
			string randomHatListFilePath = RandomHatListFilePath;
			HashSet<string> randomHatList = RandomHatList;
			int num = 0;
			string[] array = new string[randomHatList.Count];
			foreach (string item in randomHatList)
			{
				array[num] = item;
				num++;
			}
			File.WriteAllLines(randomHatListFilePath, array);
		}

		[HarmonyPatch(typeof(PlayerController), "Start")]
		[HarmonyPostfix]
		public static void EquipRandomHat_Postfix(PlayerController __instance)
		{
			if ((Object)(object)__instance == (Object)null || RandomHatList.Count <= 0)
			{
				return;
			}
			List<string> list = new List<string>(RandomHatList);
			if (list.Count > 0)
			{
				int index = Random.Range(0, list.Count);
				string databaseFriendlyHatName = HatUtility.GetDatabaseFriendlyHatName(list[index]);
				list.RemoveAt(index);
				if (Hatabase.Hats.ContainsKey(databaseFriendlyHatName))
				{
					Hatabase.StoredHats[((Object)__instance).name] = databaseFriendlyHatName;
					GameObjectExtensions.GetOrAddComponent<HatController>(((Component)__instance).gameObject);
				}
			}
		}
	}
	public static class Loader
	{
		public static tk2dSpriteCollectionData HatLoaderCollection;

		public static void LoadHats()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Expected O, but got Unknown
			//IL_043b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0442: Expected O, but got Unknown
			//IL_0779: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_053d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0867: Unknown result type (might be due to invalid IL or missing references)
			//IL_086c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0872: Unknown result type (might be due to invalid IL or missing references)
			//IL_0874: Unknown result type (might be due to invalid IL or missing references)
			HatLoaderCollection = SpriteBuilder.ConstructCollection(new GameObject(), "HatLoaderHatCollection", false);
			string[] files = Directory.GetFiles(Paths.PluginPath, "*-hat.spapi", SearchOption.AllDirectories);
			foreach (string path in files)
			{
				string[] lines = File.ReadAllLines(path);
				string file = Path.GetFileName(path);
				string directoryName = Path.GetDirectoryName(path);
				string name = "";
				int xOffs = 0;
				int yOffs = 0;
				int fps = 4;
				bool attachedToHead = true;
				bool inFrontWhenFacingBack = true;
				bool inFrontWhenFacingFront = true;
				bool flipOnRoll = true;
				bool vanishOnRoll = false;
				string flipStartSound = "";
				string flipEndSound = "";
				float flipSpeed = 1f;
				float flipHeight = 1f;
				bool? flipHorizontalWithPlayer = null;
				Dictionary<string, List<string>> hatSpritePaths = new Dictionary<string, List<string>>();
				List<tk2dSpriteDefinition> list = new List<tk2dSpriteDefinition>();
				string hatRoomSprite = "";
				string shaderName = "";
				Dictionary<string, float> materialPropertiesFloat = new Dictionary<string, float>();
				Dictionary<string, int> dictionary = new Dictionary<string, int>();
				Dictionary<string, Color> materialPropertiesColor = new Dictionary<string, Color>();
				Dictionary<string, Vector4> materialPropertiesVector = new Dictionary<string, Vector4>();
				Dictionary<string, string> materialPropertiesTexture = new Dictionary<string, string>();
				SpapiDataReader.HandleLines(lines, new Dictionary<string, Func<List<string>, bool>>
				{
					{
						"name",
						delegate(List<string> x)
						{
							name = x.LastOrDefault();
							return true;
						}
					},
					{
						"northsprites",
						delegate(List<string> x)
						{
							hatSpritePaths["north"] = x;
							return true;
						}
					},
					{
						"southsprites",
						delegate(List<string> x)
						{
							hatSpritePaths["south"] = x;
							return true;
						}
					},
					{
						"westsprites",
						delegate(List<string> x)
						{
							hatSpritePaths["west"] = x;
							return true;
						}
					},
					{
						"eastsprites",
						delegate(List<string> x)
						{
							hatSpritePaths["east"] = x;
							return true;
						}
					},
					{
						"northwestsprites",
						delegate(List<string> x)
						{
							hatSpritePaths["northwest"] = x;
							return true;
						}
					},
					{
						"northeastsprites",
						delegate(List<string> x)
						{
							hatSpritePaths["northeast"] = x;
							return true;
						}
					},
					{
						"hatroomsprite",
						delegate(List<string> x)
						{
							hatRoomSprite = x.LastOrDefault();
							return true;
						}
					},
					{
						"shadername",
						delegate(List<string> x)
						{
							shaderName = x.LastOrDefault();
							return true;
						}
					},
					{
						"shaderfloatproperties",
						delegate(List<string> x)
						{
							if (x.Count % 2 != 0)
							{
								return false;
							}
							for (int num3 = 0; num3 < x.Count; num3 += 2)
							{
								string text7 = x[num3];
								if (string.IsNullOrEmpty(text7))
								{
									return false;
								}
								string s2 = x[num3 + 1];
								if (!float.TryParse(s2, out var result7))
								{
									return false;
								}
								materialPropertiesFloat[text7] = result7;
							}
							return true;
						}
					},
					{
						"shaderintproperties",
						delegate(List<string> x)
						{
							if (x.Count % 2 != 0)
							{
								return false;
							}
							for (int num2 = 0; num2 < x.Count; num2 += 2)
							{
								string text6 = x[num2];
								if (string.IsNullOrEmpty(text6))
								{
									return false;
								}
								string s = x[num2 + 1];
								if (!int.TryParse(s, out var result6))
								{
									return false;
								}
								materialPropertiesFloat[text6] = result6;
							}
							return true;
						}
					},
					{
						"shadercolorproperties",
						delegate(List<string> x)
						{
							//IL_005c: Unknown result type (might be due to invalid IL or missing references)
							if (x.Count % 2 != 0)
							{
								return false;
							}
							Color value3 = default(Color);
							for (int n = 0; n < x.Count; n += 2)
							{
								string text4 = x[n];
								if (string.IsNullOrEmpty(text4))
								{
									return false;
								}
								string text5 = x[n + 1];
								if (!ColorUtility.TryParseHtmlString(text5, ref value3))
								{
									return false;
								}
								materialPropertiesColor[text4] = value3;
							}
							return true;
						}
					},
					{
						"shadervectorproperties",
						delegate(List<string> x)
						{
							//IL_0129: Unknown result type (might be due to invalid IL or missing references)
							if (x.Count % 2 != 0)
							{
								return false;
							}
							for (int m = 0; m < x.Count; m += 2)
							{
								string text2 = x[m];
								if (string.IsNullOrEmpty(text2))
								{
									return false;
								}
								string text3 = x[m + 1];
								string[] array3 = text3.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
								if (array3.Length == 0 || array3.Length > 4)
								{
									return false;
								}
								float result2 = 0f;
								float result3 = 0f;
								float result4 = 0f;
								float result5 = 0f;
								if (!float.TryParse(array3[0], out result2))
								{
									return false;
								}
								if (array3.Length > 1 && !float.TryParse(array3[1], out result3))
								{
									return false;
								}
								if (array3.Length > 2 && !float.TryParse(array3[2], out result4))
								{
									return false;
								}
								if (array3.Length > 3 && !float.TryParse(array3[3], out result5))
								{
									return false;
								}
								materialPropertiesVector[text2] = new Vector4(result2, result3, result4, result5);
							}
							return true;
						}
					},
					{
						"shadertextureproperties",
						delegate(List<string> x)
						{
							if (x.Count % 2 != 0)
							{
								return false;
							}
							for (int l = 0; l < x.Count; l += 2)
							{
								string text = x[l];
								if (string.IsNullOrEmpty(text))
								{
									return false;
								}
								string value2 = x[l + 1];
								if (string.IsNullOrEmpty(value2))
								{
									return false;
								}
								materialPropertiesTexture[text] = value2;
							}
							return true;
						}
					},
					{
						"xoffset",
						delegate(List<string> x)
						{
							if (int.TryParse(x.LastOrDefault(), out xOffs))
							{
								return true;
							}
							Debug.LogError((object)("Error reading hat file " + file + ": XOffset should be an integer."));
							return false;
						}
					},
					{
						"yoffset",
						delegate(List<string> x)
						{
							if (int.TryParse(x.LastOrDefault(), out yOffs))
							{
								return true;
							}
							Debug.LogError((object)("Error reading hat file " + file + ": YOffset should be an integer."));
							return false;
						}
					},
					{
						"fps",
						delegate(List<string> x)
						{
							if (int.TryParse(x.LastOrDefault(), out fps))
							{
								return true;
							}
							Debug.LogError((object)("Error reading hat file " + file + ": FPS should be an integer."));
							return false;
						}
					},
					{
						"attachedtohead",
						delegate(List<string> x)
						{
							if (bool.TryParse(x.LastOrDefault(), out attachedToHead))
							{
								return true;
							}
							Debug.LogError((object)("Error reading hat file " + file + ": AttachedToHead should be True or False."));
							return false;
						}
					},
					{
						"infrontwhenfacingback",
						delegate(List<string> x)
						{
							if (bool.TryParse(x.LastOrDefault(), out inFrontWhenFacingBack))
							{
								return true;
							}
							Debug.LogError((object)("Error reading hat file " + file + ": InFrontWhenFacingBack should be True or False."));
							return false;
						}
					},
					{
						"infrontwhenfacingfront",
						delegate(List<string> x)
						{
							if (bool.TryParse(x.LastOrDefault(), out inFrontWhenFacingFront))
							{
								return true;
							}
							Debug.LogError((object)("Error reading hat file " + file + ": InFrontWhenFacingFront should be True or False."));
							return false;
						}
					},
					{
						"fliponroll",
						delegate(List<string> x)
						{
							if (bool.TryParse(x.LastOrDefault(), out flipOnRoll))
							{
								return true;
							}
							Debug.LogError((object)("Error reading hat file " + file + ": FlipOnRoll should be True or False."));
							return false;
						}
					},
					{
						"vanishonroll",
						delegate(List<string> x)
						{
							if (bool.TryParse(x.LastOrDefault(), out vanishOnRoll))
							{
								return true;
							}
							Debug.LogError((object)("Error reading hat file " + file + ": VanishOnRoll should be True or False."));
							return false;
						}
					},
					{
						"flipstartsound",
						delegate(List<string> x)
						{
							flipStartSound = x.LastOrDefault();
							return true;
						}
					},
					{
						"flipendsound",
						delegate(List<string> x)
						{
							flipEndSound = x.LastOrDefault();
							return true;
						}
					},
					{
						"flipspeed",
						delegate(List<string> x)
						{
							if (float.TryParse(x.LastOrDefault(), out flipSpeed))
							{
								return true;
							}
							Debug.LogError((object)("Error reading hat file " + file + ": FlipSpeed should be a number."));
							return false;
						}
					},
					{
						"flipheight",
						delegate(List<string> x)
						{
							if (float.TryParse(x.LastOrDefault(), out flipHeight))
							{
								return true;
							}
							Debug.LogError((object)("Error reading hat file " + file + ": FlipHeight should be a number."));
							return false;
						}
					},
					{
						"fliphorizontalwithplayer",
						delegate(List<string> x)
						{
							bool result;
							bool flag = bool.TryParse(x.LastOrDefault(), out result);
							flipHorizontalWithPlayer = result;
							if (flag)
							{
								return true;
							}
							Debug.LogError((object)("Error reading hat file " + file + ": FlipHorizontalWithPlayer should be True or False."));
							return false;
						}
					}
				}, delegate(string x)
				{
					Debug.LogError((object)("Error reading hat file " + file + ": " + x));
				});
				if (string.IsNullOrEmpty(name))
				{
					Debug.LogError((object)("Error loading hat " + file + ": hat name not given."));
					continue;
				}
				Material val = null;
				if (!string.IsNullOrEmpty(shaderName))
				{
					Shader val2 = ShaderCache.Acquire(shaderName);
					if ((Object)(object)val2 != (Object)null)
					{
						val = new Material(val2);
						foreach (KeyValuePair<string, float> item in materialPropertiesFloat)
						{
							val.SetFloat(item.Key, item.Value);
						}
						foreach (KeyValuePair<string, int> item2 in dictionary)
						{
							val.SetInt(item2.Key, item2.Value);
						}
						foreach (KeyValuePair<string, Color> item3 in materialPropertiesColor)
						{
							val.SetColor(item3.Key, item3.Value);
						}
						foreach (KeyValuePair<string, Vector4> item4 in materialPropertiesVector)
						{
							val.SetVector(item4.Key, item4.Value);
						}
						foreach (KeyValuePair<string, string> item5 in materialPropertiesTexture)
						{
							Texture2D val3 = LoadHatTexture(directoryName, item5.Value, ETGMod.ToID(name) + "_" + item5.Key, file);
							if (!((Object)(object)val3 == (Object)null))
							{
								val.SetTexture(item5.Key, (Texture)(object)val3);
							}
						}
					}
					else
					{
						Debug.LogError((object)("Error loading hat " + file + ": \"" + shaderName + "\" isn't a valid shader."));
					}
				}
				foreach (KeyValuePair<string, List<string>> item6 in hatSpritePaths)
				{
					string key = item6.Key;
					List<string> value = item6.Value;
					for (int j = 0; j < value.Count; j++)
					{
						int spriteId;
						tk2dSpriteDefinition val4 = LoadHatSpriteDefinition(directoryName, value[j], $"{ETGMod.ToID(name)}_{key}_{j + 1:D3}", file, val, out spriteId);
						if (val4 != null)
						{
							list.Add(val4);
						}
					}
				}
				int spriteId2 = -1;
				tk2dSpriteDefinition val5 = null;
				if (!string.IsNullOrEmpty(hatRoomSprite))
				{
					val5 = LoadHatSpriteDefinition(directoryName, hatRoomSprite, ETGMod.ToID(name) + "_default_001", file, val, out spriteId2);
				}
				if (list.Count <= 0)
				{
					Debug.LogError((object)("Error loading hat " + file + ": hat doesn't have any sprites."));
					continue;
				}
				try
				{
					Hat val6 = HatUtility.SetupHat(name, (List<string>)null, (IntVector2?)new IntVector2(xOffs, yOffs), fps, (HatAttachLevel)((!attachedToHead) ? 1 : 0), (HatDepthType)((!inFrontWhenFacingBack) ? ((!inFrontWhenFacingFront) ? 1 : 2) : ((!inFrontWhenFacingFront) ? 3 : 0)), (HatRollReaction)(vanishOnRoll ? 1 : ((!flipOnRoll) ? 2 : 0)), string.IsNullOrEmpty(flipStartSound) ? null : flipStartSound, string.IsNullOrEmpty(flipEndSound) ? null : flipEndSound, flipSpeed, flipHeight, flipHorizontalWithPlayer, false, (List<GungeonFlags>)null, (List<DungeonPrerequisite>)null, (string)null, false);
					HatUtility.SetupHatSprites(val6, (List<string>)null, list, fps, (Assembly)null);
					if (val5 != null)
					{
						tk2dSpriteDefinition val7 = val5;
						Vector3[] colliderVertices = ((BraveBehaviour)val6).sprite.CurrentSprite.colliderVertices;
						int num = 0;
						Vector3[] array = (Vector3[])(object)new Vector3[colliderVertices.Length];
						Vector3[] array2 = colliderVertices;
						foreach (Vector3 val8 in array2)
						{
							array[num] = val8;
							num++;
						}
						val7.colliderVertices = array;
					}
					if (spriteId2 >= 0)
					{
						((BraveBehaviour)val6).sprite.SetSprite(HatLoaderCollection, spriteId2);
					}
				}
				catch (Exception ex)
				{
					Debug.LogError((object)("Error loading hat " + file + ": " + ex.Message));
				}
			}
		}

		public static void LoadHatSoundbanks()
		{
			string[] files = Directory.GetFiles(Paths.PluginPath, "*-hatsb.bnk", SearchOption.AllDirectories);
			foreach (string path in files)
			{
				byte[] array = File.ReadAllBytes(path);
				string fileName = Path.GetFileName(path);
				try
				{
					SoundManager.LoadSoundbankFromBytes(array, fileName);
				}
				catch (Exception ex)
				{
					Debug.LogError((object)("Error loading hat soundbank " + fileName + ": " + ex.Message));
				}
			}
		}

		public static tk2dSpriteDefinition LoadHatSpriteDefinition(string hatDirectory, string spriteName, string definitionName, string hatFile, Material overrideMaterial, out int spriteId)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Expected O, but got Unknown
			spriteId = -1;
			Texture2D val = LoadHatTexture(hatDirectory, spriteName, definitionName, hatFile);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			spriteId = SpriteBuilder.AddSpriteToCollection(val, HatLoaderCollection, "");
			tk2dSpriteDefinition val2 = HatLoaderCollection.spriteDefinitions[spriteId];
			if ((Object)(object)overrideMaterial != (Object)null)
			{
				if ((Object)(object)val2.material != (Object)null)
				{
					val2.material = new Material(overrideMaterial)
					{
						mainTexture = val2.material.mainTexture
					};
				}
				if ((Object)(object)val2.materialInst != (Object)null)
				{
					val2.materialInst = new Material(overrideMaterial)
					{
						mainTexture = val2.material.mainTexture
					};
				}
			}
			return val2;
		}

		public static Texture2D LoadHatTexture(string hatDirectory, string spriteName, string textureName, string hatFile)
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Expected O, but got Unknown
			string text = spriteName.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar);
			if (!text.EndsWith(".png"))
			{
				text += ".png";
			}
			string path = Path.Combine(hatDirectory, text);
			if (!File.Exists(path))
			{
				Debug.LogError((object)("Error loading sprites for hat " + hatFile + ": file " + spriteName + " doesn't exist."));
				return null;
			}
			byte[] array = File.ReadAllBytes(path);
			Texture2D val = new Texture2D(1, 1, (TextureFormat)4, false)
			{
				filterMode = (FilterMode)0,
				name = textureName
			};
			try
			{
				if (!ImageConversion.LoadImage(val, array))
				{
					Debug.LogError((object)("Error loading sprites for hat " + hatFile + ": file " + text + " is not a valid texture."));
					return null;
				}
			}
			catch
			{
				Debug.LogError((object)("Error loading sprites for hat " + hatFile + ": file " + text + " is not a valid texture."));
				return null;
			}
			return val;
		}
	}
	[BepInPlugin("spapi.etg.hatloader", "Hat Loader", "1.2.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string GUID = "spapi.etg.hatloader";

		public const string NAME = "Hat Loader";

		public const string VERSION = "1.2.0";

		public void Awake()
		{
			ETGModMainBehaviour.WaitForGameManagerStart((Action<GameManager>)GMStart);
		}

		public void GMStart(GameManager gm)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			Loader.LoadHats();
			Loader.LoadHatSoundbanks();
			AutoHatManager.Init();
			Harmony val = new Harmony("spapi.etg.hatloader");
			val.PatchAll();
		}
	}
	public static class SpapiDataReader
	{
		public static bool HandleLines(string[] lines, Dictionary<string, Func<List<string>, bool>> propertyHandler, Action<string> errorHandler)
		{
			for (int i = 0; i < lines.Length; i++)
			{
				string text = lines[i];
				if (Utility.IsNullOrWhiteSpace(text))
				{
					continue;
				}
				string text2 = text.Trim();
				if (text2.StartsWith("#") && text2.Length > 1)
				{
					string text3 = text2.Substring(1).Trim().ToLowerInvariant();
					if (!Utility.IsNullOrWhiteSpace(text3))
					{
						List<string> property;
						bool flag = TryReadDataProperty(lines, ref i, out property);
						if (!propertyHandler.TryGetValue(text3.ToLowerInvariant(), out var value))
						{
							errorHandler?.Invoke("unknown property " + text3 + ".");
							return false;
						}
						if (flag && value != null && !value(property))
						{
							return false;
						}
					}
					continue;
				}
				errorHandler?.Invoke($"unexpected data at line {i + 1}.");
				return false;
			}
			return true;
		}

		private static bool TryReadDataProperty(string[] lines, ref int index, out List<string> property)
		{
			property = new List<string>();
			index++;
			while (index < lines.Length)
			{
				string text = lines[index];
				if (!Utility.IsNullOrWhiteSpace(text))
				{
					string text2 = text.Trim();
					if (text2.StartsWith("#") && text2.Length > 1)
					{
						index--;
						break;
					}
					property.Add(text2);
				}
				index++;
			}
			return property.Count > 0;
		}
	}
}