Decompiled source of CrownsAndTiaras v1.0.1

CrownsAndTiaras.dll

Decompiled a day ago
using System;
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 Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("CrownsAndTiaras")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.0.0")]
[assembly: AssemblyInformationalVersion("0.2.0")]
[assembly: AssemblyProduct("CrownsAndTiaras")]
[assembly: AssemblyTitle("CrownsAndTiaras")]
[assembly: AssemblyVersion("0.2.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[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 CrownsAndTiaras
{
	internal sealed class CrownDef
	{
		public string Id { get; set; } = "";

		public string Name { get; set; } = "";

		public string Description { get; set; } = "";

		public float Armor { get; set; } = 1f;

		public float ArmorPerLevel { get; set; } = 2f;

		public int MaxQuality { get; set; } = 1;

		public string CraftingStation { get; set; } = CraftingStations.Workbench;

		public List<(string Item, int Amount, int AmountPerLevel)> Recipe { get; set; } = new List<(string, int, int)>();

		public string NameToken => "item_" + Id.ToLowerInvariant();

		public string DescriptionToken => NameToken + "_description";
	}
	internal static class CrownDefs
	{
		private sealed class Tier
		{
			public float Armor;

			public string Station = "";

			public string Metal = "";

			public int MetalAmount;

			public int Coins;
		}

		private static readonly Tier BronzeAge = new Tier
		{
			Armor = 8f,
			Station = CraftingStations.Forge,
			Metal = "Bronze",
			MetalAmount = 5,
			Coins = 100
		};

		private static readonly Tier IronAge = new Tier
		{
			Armor = 14f,
			Station = CraftingStations.Forge,
			Metal = "Iron",
			MetalAmount = 10,
			Coins = 200
		};

		private static readonly Tier SilverAge = new Tier
		{
			Armor = 20f,
			Station = CraftingStations.Forge,
			Metal = "Silver",
			MetalAmount = 10,
			Coins = 300
		};

		private static readonly Tier BlackMetalAge = new Tier
		{
			Armor = 26f,
			Station = CraftingStations.Forge,
			Metal = "BlackMetal",
			MetalAmount = 10,
			Coins = 400
		};

		private static readonly Tier FlametalAge = new Tier
		{
			Armor = 32f,
			Station = CraftingStations.BlackForge,
			Metal = "FlametalNew",
			MetalAmount = 10,
			Coins = 500
		};

		public static readonly CrownDef[] All = new CrownDef[15]
		{
			Crown("SkaRoseCrown", "Rose Crown", "A romantic crown covered in small roses, with jewels nestled throughout.", BronzeAge, ("Ruby", 1), ("Thistle", 5)),
			Crown("SkaThornedCrown", "Thorned Crown", "A dramatic crown with vine-like points and numerous gems.", BronzeAge, ("Ruby", 2)),
			Crown("SkaLotusCrown", "Lotus Crown", "A graceful crown of layered petal points, adorned with multiple gems.", BronzeAge, ("Ruby", 1), ("Dandelion", 5)),
			Crown("SkaCrystalCrown", "Crystal Crown", "A radiant crown of multiple crystal points and glittering jewels.", IronAge, ("Crystal", 8), ("AmberPearl", 2)),
			Crown("SkaCrescentCrown", "Crescent Crown", "A mystical crown with a crescent motif, several points, and dangling jewels.", IronAge, ("Crystal", 4), ("AmberPearl", 2)),
			Crown("SkaStarfallCrown", "Starfall Crown", "A celestial crown with star-like points and gleaming jewels.", IronAge, ("Crystal", 4), ("AmberPearl", 2)),
			Crown("SkaRadiantDiadem", "Radiant Diadem", "An elegant, multi-point tiara set with an array of gemstones.", SilverAge, ("Ruby", 3)),
			Crown("SkaRoyalFiligreeTiara", "Royal Filigree Tiara", "A delicate yet regal tiara with intricate filigree, multiple points, and jewels.", SilverAge, ("Ruby", 3)),
			Crown("SkaDrapedCrown", "Draped Crown", "A jeweled crown with multiple points and elegant, cascading chains.", SilverAge, ("Ruby", 3), ("Chain", 2)),
			Crown("SkaObsidianSpireCrown", "Obsidian Spire Crown", "A bold crown of many sharp points, set with deep, luminous gems.", BlackMetalAge, ("Obsidian", 12), ("Crystal", 4)),
			Crown("SkaArcaneCrown", "Arcane Crown", "A majestic crown with curved points and multiple arcane jewels.", BlackMetalAge, ("Obsidian", 8), ("Crystal", 4)),
			Crown("SkaHighSpireCrown", "High Spire Crown", "A regal crown with many towering points and radiant jewels.", BlackMetalAge, ("Obsidian", 8), ("Crystal", 4)),
			Crown("SkaHaloCrown", "Halo Crown", "A resplendent crown with a halo of points and radiant jewels.", FlametalAge, ("GemstoneBlue", 1)),
			Crown("SkaSovereignCrown", "Sovereign Crown", "A grand, multi-tiered crown with numerous points and rich gemstones.", FlametalAge, ("GemstoneRed", 1)),
			Crown("SkaImperialCrown", "Imperial Crown", "A majestic, multi-spired crown richly set with countless jewels.", FlametalAge, ("GemstoneGreen", 1))
		};

		private static CrownDef Crown(string id, string name, string description, Tier tier, params (string Item, int Amount)[] jewels)
		{
			CrownDef crownDef = new CrownDef
			{
				Id = id,
				Name = name,
				Description = description,
				Armor = tier.Armor,
				CraftingStation = tier.Station
			};
			crownDef.Recipe.Add((tier.Metal, tier.MetalAmount, 0));
			crownDef.Recipe.Add(("Coins", tier.Coins, 0));
			for (int i = 0; i < jewels.Length; i++)
			{
				var (item, item2) = jewels[i];
				crownDef.Recipe.Add((item, item2, 0));
			}
			return crownDef;
		}
	}
	internal sealed class CrownDiagnostics : MonoBehaviour
	{
		private const float SettleSeconds = 3f;

		private const float CheckSeconds = 0.5f;

		private const float WornReportDelay = 1f;

		private static readonly FieldInfo? HelmetInstanceField = PrivateField("m_helmetItemInstance");

		private static readonly FieldInfo? HairInstanceField = PrivateField("m_hairItemInstance");

		private static readonly FieldInfo? BeardInstanceField = PrivateField("m_beardItemInstance");

		private Player? _player;

		private float _readyAt;

		private float _nextCheck;

		private bool _introDone;

		private string _inventoryState = "";

		private string _craftingState = "";

		private string _wornKey = "";

		private float _wornReportAt = float.MaxValue;

		public bool LogState { get; set; }

		public bool GiveItems { get; set; }

		private static FieldInfo? PrivateField(string name)
		{
			return typeof(VisEquipment).GetField(name, BindingFlags.Instance | BindingFlags.NonPublic);
		}

		private void Update()
		{
			if (!LogState && !GiveItems)
			{
				return;
			}
			float unscaledTime = Time.unscaledTime;
			if (unscaledTime < _nextCheck)
			{
				return;
			}
			_nextCheck = unscaledTime + 0.5f;
			Player localPlayer = Player.m_localPlayer;
			if (!Object.op_Implicit((Object)(object)localPlayer))
			{
				_player = null;
				return;
			}
			if ((Object)(object)localPlayer != (Object)(object)_player)
			{
				_player = localPlayer;
				_readyAt = unscaledTime + 3f;
				_introDone = false;
				_inventoryState = (_craftingState = (_wornKey = ""));
				_wornReportAt = float.MaxValue;
			}
			if (unscaledTime < _readyAt || !Object.op_Implicit((Object)(object)ObjectDB.instance))
			{
				return;
			}
			try
			{
				if (!_introDone)
				{
					_introDone = true;
					if (LogState)
					{
						ReportRegistration(localPlayer);
					}
					if (GiveItems)
					{
						Give(localPlayer);
					}
					if (LogState)
					{
						try
						{
							ExportHead(localPlayer);
						}
						catch (Exception ex)
						{
							CrownsPlugin.Log.LogWarning((object)("The head reference could not be saved: " + ex.Message));
						}
					}
				}
				if (LogState)
				{
					ReportInventory(localPlayer);
					ReportCraftingMenu(localPlayer);
					ReportHelmet(localPlayer, unscaledTime);
				}
			}
			catch (Exception arg)
			{
				CrownsPlugin.Log.LogWarning((object)$"Diagnostics stopped after an error: {arg}");
				LogState = false;
				GiveItems = false;
			}
		}

		private static void ReportRegistration(Player player)
		{
			CrownDef[] all = CrownDefs.All;
			foreach (CrownDef crownDef in all)
			{
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(crownDef.Id);
				Recipe val = FindRecipe(crownDef.Id);
				string text = "no recipe";
				if ((Object)(object)val != (Object)null)
				{
					string text2 = string.Join(", ", val.m_resources.Select((Requirement r) => string.Format("{0} {1}", r.m_amount, Object.op_Implicit((Object)(object)r.m_resItem) ? ((Object)r.m_resItem).name : "?")));
					text = "recipe at " + StationName(val) + " for " + text2;
				}
				bool flag = Object.op_Implicit((Object)(object)itemPrefab) && player.IsRecipeKnown(SharedName(itemPrefab));
				Say(crownDef.Id + ": " + (Object.op_Implicit((Object)(object)itemPrefab) ? "in the item database" : "NOT in the item database") + ", " + text + ", " + (flag ? "known" : "not known") + " to this character. " + $"Free inventory slots: {((Humanoid)player).GetInventory().GetEmptySlots()}");
			}
		}

		private static void Give(Player player)
		{
			Inventory inventory = ((Humanoid)player).GetInventory();
			List<string> list = new List<string>();
			List<string> list2 = new List<string>();
			CrownDef[] all = CrownDefs.All;
			foreach (CrownDef crownDef in all)
			{
				if (Owned(inventory, crownDef.Id).Any())
				{
					continue;
				}
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(crownDef.Id);
				if (Object.op_Implicit((Object)(object)itemPrefab))
				{
					if (!inventory.CanAddItem(itemPrefab, 1))
					{
						Say("GiveItemsOnSpawn: no room in the inventory for " + crownDef.Id);
						list2.Add(crownDef.Name);
					}
					else
					{
						inventory.AddItem(itemPrefab, 1);
						Say("GiveItemsOnSpawn: added " + crownDef.Id + " to the inventory");
						list.Add(crownDef.Name);
					}
				}
			}
			List<string> list3 = new List<string>();
			if (list.Count > 0)
			{
				list3.Add("Test items added to your inventory: " + string.Join(", ", list));
			}
			if (list2.Count > 0)
			{
				list3.Add("No room in the inventory for: " + string.Join(", ", list2));
			}
			if (list3.Count > 0)
			{
				((Character)player).Message((MessageType)2, string.Join("\n", list3), 0, (Sprite)null, false);
			}
		}

		private void ReportInventory(Player player)
		{
			Inventory inventory = ((Humanoid)player).GetInventory();
			List<string> list = new List<string>();
			CrownDef[] all = CrownDefs.All;
			foreach (CrownDef crownDef in all)
			{
				foreach (ItemData item in Owned(inventory, crownDef.Id))
				{
					list.Add(string.Format("{0} in slot ({1}, {2}){3}", crownDef.Id, item.m_gridPos.x, item.m_gridPos.y, item.m_equipped ? ", equipped" : ""));
				}
			}
			string text = ((list.Count == 0) ? "none of this mod's items" : string.Join("; ", list));
			if (!(text == _inventoryState))
			{
				_inventoryState = text;
				Say("Inventory: " + text);
			}
		}

		private void ReportCraftingMenu(Player player)
		{
			CraftingStation currentCraftingStation = player.GetCurrentCraftingStation();
			string text = ((!InventoryGui.IsVisible()) ? "" : (Object.op_Implicit((Object)(object)currentCraftingStation) ? currentCraftingStation.m_name : "none"));
			if (text == _craftingState)
			{
				return;
			}
			_craftingState = text;
			if (text == "")
			{
				return;
			}
			string text2 = (Object.op_Implicit((Object)(object)currentCraftingStation) ? Localization.instance.Localize(currentCraftingStation.m_name) : "no crafting station");
			CrownDef[] all = CrownDefs.All;
			foreach (CrownDef crownDef in all)
			{
				Recipe val = FindRecipe(crownDef.Id);
				if (!((Object)(object)val == (Object)null) && Object.op_Implicit((Object)(object)val.m_item))
				{
					string text3 = ((!player.IsRecipeKnown(val.m_item.m_itemData.m_shared.m_name)) ? "not listed: this character has not learned the recipe" : ((!player.RequiredCraftingStation(val, 1, false)) ? ("not listed: it is crafted at " + StationName(val)) : ((!player.HaveRequirements(val, false, 1, 1)) ? "listed, but the ingredients are missing" : (((Humanoid)player).GetInventory().CanAddItem(((Component)val.m_item).gameObject, 1) ? "listed and can be crafted" : "listed, but the inventory is full"))));
					Say("Crafting menu opened at " + text2 + ": " + crownDef.Id + " is " + text3);
				}
			}
		}

		private void ReportHelmet(Player player, float now)
		{
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0416: Unknown result type (might be due to invalid IL or missing references)
			//IL_0424: Unknown result type (might be due to invalid IL or missing references)
			//IL_042b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0432: Unknown result type (might be due to invalid IL or missing references)
			//IL_0439: Unknown result type (might be due to invalid IL or missing references)
			//IL_031a: Unknown result type (might be due to invalid IL or missing references)
			ItemData val = ((IEnumerable<ItemData>)((Humanoid)player).GetInventory().GetEquippedItems()).FirstOrDefault((Func<ItemData, bool>)((ItemData item) => (int)item.m_shared.m_itemType == 6));
			VisEquipment component = ((Component)player).GetComponent<VisEquipment>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return;
			}
			object? obj = HelmetInstanceField?.GetValue(component);
			GameObject val2 = (GameObject)((obj is GameObject) ? obj : null);
			string text = ((val == null) ? "" : $"{PrefabName(val)}/{(Object.op_Implicit((Object)(object)val2) ? ((Object)val2).GetInstanceID() : 0)}");
			if (text != _wornKey)
			{
				_wornKey = text;
				_wornReportAt = ((val == null) ? float.MaxValue : (now + 1f));
				if (val == null)
				{
					Say("Helmet slot: empty");
				}
			}
			if (val == null || now < _wornReportAt)
			{
				return;
			}
			_wornReportAt = float.MaxValue;
			StringBuilder stringBuilder = new StringBuilder("Helmet slot: " + PrefabName(val) + ". ");
			if (!Object.op_Implicit((Object)(object)val2))
			{
				stringBuilder.Append("The game has put nothing on the helmet joint.");
				Say(stringBuilder.ToString());
				return;
			}
			Transform transform = val2.transform;
			stringBuilder.Append("Attached '" + ((Object)val2).name + "' to '" + (Object.op_Implicit((Object)(object)transform.parent) ? ((Object)transform.parent).name : "nothing") + "', " + $"active {val2.activeInHierarchy}, world scale {Vec(transform.lossyScale)}.");
			Renderer[] componentsInChildren = val2.GetComponentsInChildren<Renderer>(true);
			if (componentsInChildren.Length == 0)
			{
				stringBuilder.Append(" It has no renderers.");
			}
			Renderer[] array = componentsInChildren;
			foreach (Renderer val3 in array)
			{
				MeshFilter component2 = ((Component)val3).GetComponent<MeshFilter>();
				Mesh val4 = (Object.op_Implicit((Object)(object)component2) ? component2.sharedMesh : null);
				Material sharedMaterial = val3.sharedMaterial;
				stringBuilder.AppendLine();
				stringBuilder.Append($"  renderer '{((Object)val3).name}': enabled {val3.enabled}, on screen {val3.isVisible}, " + "layer " + LayerMask.LayerToName(((Component)val3).gameObject.layer) + ", " + (Object.op_Implicit((Object)(object)val4) ? (val4.vertexCount + " vertices") : "no mesh") + ", ");
				if (Object.op_Implicit((Object)(object)sharedMaterial))
				{
					Texture val5 = (sharedMaterial.HasProperty("_MainTex") ? sharedMaterial.mainTexture : null);
					stringBuilder.Append($"material '{((Object)sharedMaterial).name}', shader '{((Object)sharedMaterial.shader).name}' (supported {sharedMaterial.shader.isSupported}), " + $"queue {sharedMaterial.renderQueue}");
					if (sharedMaterial.HasProperty("_Color"))
					{
						stringBuilder.Append($", colour {sharedMaterial.color}");
					}
					if (sharedMaterial.HasProperty("_Metallic"))
					{
						stringBuilder.Append(", metallic " + Num(sharedMaterial.GetFloat("_Metallic")));
					}
					if (sharedMaterial.HasProperty("_Glossiness"))
					{
						stringBuilder.Append(", smoothness " + Num(sharedMaterial.GetFloat("_Glossiness")));
					}
					stringBuilder.Append(", texture " + (Object.op_Implicit((Object)(object)val5) ? $"'{((Object)val5).name}' {val5.width}x{val5.height}" : "none"));
				}
				else
				{
					stringBuilder.Append("no material");
				}
				Transform helmet = component.m_helmet;
				if (Object.op_Implicit((Object)(object)val4) && Object.op_Implicit((Object)(object)helmet))
				{
					stringBuilder.AppendLine();
					stringBuilder.Append("    from the helmet joint, in metres: " + Box(val4.bounds, ((Component)val3).transform, helmet.position, helmet.right, helmet.up, helmet.forward, "left to right", "down to up", "back to front"));
				}
			}
			Say(stringBuilder.ToString());
		}

		private static void ExportHead(Player player)
		{
			VisEquipment component = ((Component)player).GetComponent<VisEquipment>();
			if (!Object.op_Implicit((Object)(object)component) || !Object.op_Implicit((Object)(object)component.m_bodyModel) || !Object.op_Implicit((Object)(object)component.m_bodyModel.sharedMesh) || !Object.op_Implicit((Object)(object)component.m_helmet))
			{
				return;
			}
			SkinnedMeshRenderer bodyModel = component.m_bodyModel;
			Transform joint = component.m_helmet;
			List<string> lines = new List<string>
			{
				"# The player's head in the space of the helmet joint, written by CrownsAndTiaras ([Debug] Diagnostics).",
				"# Body mesh '" + ((Object)bodyModel.sharedMesh).name + "'. Units are metres; the origin is the helmet joint; +Z is towards the face.",
				"# A fitting guide for modelling headwear around. Taken from the game: do not publish or ship it."
			};
			List<string> written = new List<string>();
			int offset = 0;
			AddPart("head", (Renderer)(object)bodyModel, headOnly: true);
			(string, FieldInfo)[] array = new(string, FieldInfo)[2]
			{
				("hair", HairInstanceField),
				("beard", BeardInstanceField)
			};
			for (int i = 0; i < array.Length; i++)
			{
				(string, FieldInfo) tuple = array[i];
				string item = tuple.Item1;
				object? obj = tuple.Item2?.GetValue(component);
				GameObject val = (GameObject)((obj is GameObject) ? obj : null);
				if (val != null && Object.op_Implicit((Object)(object)val))
				{
					int num = 0;
					Renderer[] componentsInChildren = val.GetComponentsInChildren<Renderer>();
					foreach (Renderer renderer in componentsInChildren)
					{
						AddPart((num++ == 0) ? item : $"{item}{num}", renderer, headOnly: false);
					}
				}
			}
			string text = Path.Combine(Paths.BepInExRootPath, "CrownsAndTiaras");
			Directory.CreateDirectory(text);
			string text2 = Path.Combine(text, "head_reference_" + ((Object)bodyModel.sharedMesh).name + ".obj");
			File.WriteAllLines(text2, lines);
			Say("Head reference: " + string.Join(", ", written) + "; saved to " + text2);
			void AddPart(string name, Renderer val4, bool headOnly)
			{
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Expected O, but got Unknown
				//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_00cd: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
				//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
				//IL_0116: Unknown result type (might be due to invalid IL or missing references)
				Mesh val2 = null;
				bool flag = false;
				SkinnedMeshRenderer val3 = (SkinnedMeshRenderer)(object)((val4 is SkinnedMeshRenderer) ? val4 : null);
				if (val3 != null && Object.op_Implicit((Object)(object)val3.sharedMesh))
				{
					val2 = new Mesh();
					flag = true;
					val3.BakeMesh(val2, true);
				}
				else
				{
					MeshFilter component2 = ((Component)val4).GetComponent<MeshFilter>();
					if (component2 != null && Object.op_Implicit((Object)(object)component2) && Object.op_Implicit((Object)(object)component2.sharedMesh))
					{
						if (!component2.sharedMesh.isReadable)
						{
							written.Add(name + " skipped (the game does not allow reading its mesh)");
							return;
						}
						val2 = component2.sharedMesh;
					}
				}
				if (Object.op_Implicit((Object)(object)val2))
				{
					Vector3[] vertices = val2.vertices;
					int[] triangles = val2.triangles;
					if (flag)
					{
						Object.Destroy((Object)(object)val2);
					}
					int[] array2 = new int[vertices.Length];
					List<Vector3> list = new List<Vector3>();
					for (int k = 0; k < vertices.Length; k++)
					{
						Vector3 val5 = joint.InverseTransformPoint(((Component)val4).transform.TransformPoint(vertices[k]));
						bool flag2 = !headOnly || (val5.y > -0.2f && ((Vector3)(ref val5)).sqrMagnitude < 0.122499995f);
						array2[k] = (flag2 ? (list.Count + 1) : 0);
						if (flag2)
						{
							list.Add(val5);
						}
					}
					List<string> list2 = new List<string>();
					for (int l = 0; l + 2 < triangles.Length; l += 3)
					{
						int num2 = array2[triangles[l]];
						int num3 = array2[triangles[l + 1]];
						int num4 = array2[triangles[l + 2]];
						if (num2 > 0 && num3 > 0 && num4 > 0)
						{
							list2.Add($"f {offset + num2} {offset + num4} {offset + num3}");
						}
					}
					if (list2.Count != 0)
					{
						lines.Add("o " + name);
						lines.AddRange(list.Select((Vector3 p) => "v " + Num5(0f - p.x) + " " + Num5(p.y) + " " + Num5(p.z)));
						lines.AddRange(list2);
						offset += list.Count;
						written.Add($"{name} {list.Count} vertices");
					}
				}
			}
		}

		private static string Box(Bounds bounds, Transform owner, Vector3 origin, Vector3 right, Vector3 up, Vector3 forward, string rightName, string upName, string forwardName)
		{
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: 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_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: 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_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: 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_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(float.MaxValue, float.MaxValue, float.MaxValue);
			Vector3 val2 = default(Vector3);
			((Vector3)(ref val2))..ctor(float.MinValue, float.MinValue, float.MinValue);
			Vector3 val3 = default(Vector3);
			Vector3 val5 = default(Vector3);
			for (int i = 0; i < 8; i++)
			{
				((Vector3)(ref val3))..ctor(((i & 1) == 0) ? (0f - ((Bounds)(ref bounds)).extents.x) : ((Bounds)(ref bounds)).extents.x, ((i & 2) == 0) ? (0f - ((Bounds)(ref bounds)).extents.y) : ((Bounds)(ref bounds)).extents.y, ((i & 4) == 0) ? (0f - ((Bounds)(ref bounds)).extents.z) : ((Bounds)(ref bounds)).extents.z);
				Vector3 val4 = owner.TransformPoint(((Bounds)(ref bounds)).center + val3) - origin;
				((Vector3)(ref val5))..ctor(Vector3.Dot(val4, right), Vector3.Dot(val4, up), Vector3.Dot(val4, forward));
				val = Vector3.Min(val, val5);
				val2 = Vector3.Max(val2, val5);
			}
			return rightName + " " + Num(val.x) + " to " + Num(val2.x) + ", " + upName + " " + Num(val.y) + " to " + Num(val2.y) + ", " + forwardName + " " + Num(val.z) + " to " + Num(val2.z);
		}

		private static IEnumerable<ItemData> Owned(Inventory inventory, string id)
		{
			return from item in inventory.GetAllItems()
				where PrefabName(item) == id
				select item;
		}

		private static Recipe? FindRecipe(string id)
		{
			return ((IEnumerable<Recipe>)ObjectDB.instance.m_recipes).FirstOrDefault((Func<Recipe, bool>)((Recipe recipe) => Object.op_Implicit((Object)(object)recipe) && Object.op_Implicit((Object)(object)recipe.m_item) && ((Object)((Component)recipe.m_item).gameObject).name == id));
		}

		private static string StationName(Recipe recipe)
		{
			if (!Object.op_Implicit((Object)(object)recipe.m_craftingStation))
			{
				return "no crafting station";
			}
			return Localization.instance.Localize(recipe.m_craftingStation.m_name);
		}

		private static string SharedName(GameObject prefab)
		{
			return prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_name;
		}

		private static string PrefabName(ItemData item)
		{
			if (!Object.op_Implicit((Object)(object)item.m_dropPrefab))
			{
				return item.m_shared.m_name;
			}
			return ((Object)item.m_dropPrefab).name;
		}

		private static string Num(float value)
		{
			return value.ToString("0.000", CultureInfo.InvariantCulture);
		}

		private static string Num5(float value)
		{
			return value.ToString("0.#####", CultureInfo.InvariantCulture);
		}

		private static string Vec(Vector3 v)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			return "(" + Num(v.x) + ", " + Num(v.y) + ", " + Num(v.z) + ")";
		}

		private static void Say(string message)
		{
			CrownsPlugin.Log.LogInfo((object)("[test] " + message));
		}
	}
	internal static class CrownFactory
	{
		private const string BasePrefab = "HelmetRootCrown";

		private const string ModelSuffix = "_model";

		private static readonly Quaternion IconRotation = Quaternion.Euler(20f, 0f, 0f) * Quaternion.Euler(0f, 25f, 0f);

		public static void Add(AssetBundle bundle, CrownDef def, bool useGameShader, bool saveIcon)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: 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_0075: Expected O, but got Unknown
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Expected O, but got Unknown
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0171: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_02aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cc: Unknown result type (might be due to invalid IL or missing references)
			string text = def.Id + "_model";
			GameObject val = bundle.LoadAsset<GameObject>(text);
			if (!Object.op_Implicit((Object)(object)val))
			{
				throw new InvalidOperationException("The bundle has no prefab named " + text + ".");
			}
			ItemConfig val2 = new ItemConfig
			{
				Name = "$" + def.NameToken,
				Description = "$" + def.DescriptionToken,
				CraftingStation = def.CraftingStation
			};
			foreach (var (text2, num, num2) in def.Recipe)
			{
				val2.AddRequirement(text2, num, num2);
			}
			CustomItem val3 = new CustomItem(def.Id, "HelmetRootCrown", val2);
			if (!Object.op_Implicit((Object)(object)val3.ItemPrefab))
			{
				throw new InvalidOperationException("Could not clone HelmetRootCrown.");
			}
			Transform obj = val3.ItemPrefab.transform.Find("attach");
			if (!Object.op_Implicit((Object)(object)obj))
			{
				throw new InvalidOperationException("HelmetRootCrown has no 'attach' child.");
			}
			Renderer componentInChildren = ((Component)obj).GetComponentInChildren<Renderer>(true);
			Shader val4 = ((Object.op_Implicit((Object)(object)componentInChildren) && Object.op_Implicit((Object)(object)componentInChildren.sharedMaterial)) ? componentInChildren.sharedMaterial.shader : null);
			GameObject visual = ReplaceVisual(obj, val, val3.ItemPrefab.layer);
			int num3 = PrepareMaterials(visual, useGameShader ? val4 : null);
			Bounds val5 = AddCollider(visual);
			SharedData shared = val3.ItemDrop.m_itemData.m_shared;
			shared.m_helmetHideHair = (HelmetHairType)0;
			shared.m_helmetHideBeard = (HelmetHairType)0;
			shared.m_armor = def.Armor;
			shared.m_armorPerLevel = def.ArmorPerLevel;
			shared.m_maxQuality = def.MaxQuality;
			Sprite val6 = RenderIcon(obj, def.Id);
			if (Object.op_Implicit((Object)(object)val6))
			{
				shared.m_icons = (Sprite[])(object)new Sprite[1] { val6 };
			}
			else
			{
				CrownsPlugin.Log.LogWarning((object)(def.Id + ": the icon could not be rendered; it keeps the HelmetRootCrown icon."));
			}
			if (Object.op_Implicit((Object)(object)val6) && saveIcon)
			{
				SaveIcon(val6, def.Id);
			}
			if (!ItemManager.Instance.AddItem(val3))
			{
				throw new InvalidOperationException("Jotunn refused to add " + def.Id + ".");
			}
			CrownsPlugin.Log.LogInfo((object)(string.Format("Added {0}: cloned from {1}, {2} material(s) ", def.Id, "HelmetRootCrown", num3) + "(" + ((useGameShader && Object.op_Implicit((Object)(object)val4)) ? ("game shader " + ((Object)val4).name) : "bundle shader") + "), " + $"model size {((Bounds)(ref val5)).size.x:0.###} x {((Bounds)(ref val5)).size.y:0.###} x {((Bounds)(ref val5)).size.z:0.###} m, " + "icon " + (Object.op_Implicit((Object)(object)val6) ? "rendered" : "vanilla")));
		}

		private static GameObject ReplaceVisual(Transform attach, GameObject model, int layer)
		{
			//IL_0025: 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_003b: Unknown result type (might be due to invalid IL or missing references)
			for (int num = attach.childCount - 1; num >= 0; num--)
			{
				Object.DestroyImmediate((Object)(object)((Component)attach.GetChild(num)).gameObject);
			}
			attach.localPosition = Vector3.zero;
			attach.localRotation = Quaternion.identity;
			attach.localScale = Vector3.one;
			GameObject val = Object.Instantiate<GameObject>(model, attach, false);
			((Object)val).name = "visual";
			Transform[] componentsInChildren = val.GetComponentsInChildren<Transform>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				((Component)componentsInChildren[i]).gameObject.layer = layer;
			}
			return val;
		}

		private static int PrepareMaterials(GameObject visual, Shader? gameShader)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			int num = 0;
			Renderer[] componentsInChildren = visual.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				Material[] sharedMaterials = val.sharedMaterials;
				for (int j = 0; j < sharedMaterials.Length; j++)
				{
					if (!Object.op_Implicit((Object)(object)sharedMaterials[j]))
					{
						continue;
					}
					Material val2 = new Material(sharedMaterials[j]);
					if (Object.op_Implicit((Object)(object)gameShader))
					{
						if (((Object)gameShader).name == ((Object)val2.shader).name)
						{
							val2.shader = gameShader;
						}
						else
						{
							CrownsPlugin.Log.LogWarning((object)("Material " + ((Object)val2).name + " uses shader '" + ((Object)val2.shader).name + "', not '" + ((Object)gameShader).name + "'; left on the bundle's shader."));
						}
					}
					sharedMaterials[j] = val2;
					num++;
				}
				val.sharedMaterials = sharedMaterials;
			}
			return num;
		}

		private static Bounds AddCollider(GameObject visual)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0134: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: 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_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: 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_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: 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_00e9: Unknown result type (might be due to invalid IL or missing references)
			bool flag = false;
			Bounds result = default(Bounds);
			MeshFilter[] componentsInChildren = visual.GetComponentsInChildren<MeshFilter>(true);
			Vector3 val3 = default(Vector3);
			foreach (MeshFilter val in componentsInChildren)
			{
				if (!Object.op_Implicit((Object)(object)val.sharedMesh))
				{
					continue;
				}
				Matrix4x4 val2 = visual.transform.worldToLocalMatrix * ((Component)val).transform.localToWorldMatrix;
				Bounds bounds = val.sharedMesh.bounds;
				for (int j = 0; j < 8; j++)
				{
					((Vector3)(ref val3))..ctor(((j & 1) == 0) ? (0f - ((Bounds)(ref bounds)).extents.x) : ((Bounds)(ref bounds)).extents.x, ((j & 2) == 0) ? (0f - ((Bounds)(ref bounds)).extents.y) : ((Bounds)(ref bounds)).extents.y, ((j & 4) == 0) ? (0f - ((Bounds)(ref bounds)).extents.z) : ((Bounds)(ref bounds)).extents.z);
					Vector3 val4 = ((Matrix4x4)(ref val2)).MultiplyPoint3x4(((Bounds)(ref bounds)).center + val3);
					if (flag)
					{
						((Bounds)(ref result)).Encapsulate(val4);
					}
					else
					{
						((Bounds)(ref result))..ctor(val4, Vector3.zero);
					}
					flag = true;
				}
			}
			if (!flag)
			{
				throw new InvalidOperationException("The model has no mesh.");
			}
			BoxCollider obj = visual.AddComponent<BoxCollider>();
			obj.center = ((Bounds)(ref result)).center;
			obj.size = ((Bounds)(ref result)).size;
			return result;
		}

		private static Sprite? RenderIcon(Transform attach, string name)
		{
			//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_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Expected O, but got Unknown
			GameObject val = Object.Instantiate<GameObject>(((Component)attach).gameObject);
			try
			{
				((Object)val).name = name;
				RenderRequest val2 = new RenderRequest(val)
				{
					Rotation = IconRotation,
					DistanceMultiplier = 0.8f
				};
				return RenderManager.Instance.Render(val2);
			}
			catch (Exception ex)
			{
				CrownsPlugin.Log.LogWarning((object)("Icon render for " + name + " failed: " + ex.Message));
				return null;
			}
			finally
			{
				Object.DestroyImmediate((Object)(object)val);
			}
		}

		private static void SaveIcon(Sprite icon, string id)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: 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)
			try
			{
				Texture2D texture = icon.texture;
				Color32[] pixels = texture.GetPixels32();
				int num = 0;
				long num2 = 0L;
				Color32[] array = pixels;
				foreach (Color32 val in array)
				{
					if (val.a != 0)
					{
						num++;
						num2 += (val.r + val.g + val.b) / 3;
					}
				}
				string text = Path.Combine(Paths.BepInExRootPath, "CrownsAndTiaras");
				Directory.CreateDirectory(text);
				string text2 = Path.Combine(text, id + "_icon.png");
				File.WriteAllBytes(text2, ImageConversion.EncodeToPNG(texture));
				CrownsPlugin.Log.LogInfo((object)($"[test] {id} icon: {((Texture)texture).width}x{((Texture)texture).height}, {100f * (float)num / (float)pixels.Length:0}% of it drawn, " + $"average brightness {((num == 0) ? 0 : (num2 / num))} of 255, saved to {text2}"));
			}
			catch (Exception ex)
			{
				CrownsPlugin.Log.LogWarning((object)("The icon for " + id + " could not be saved: " + ex.Message));
			}
		}
	}
	[BepInPlugin("com.skaket.valheim.crownsandtiaras", "CrownsAndTiaras", "0.2.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class CrownsPlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.skaket.valheim.crownsandtiaras";

		public const string PluginName = "CrownsAndTiaras";

		public const string PluginVersion = "0.2.0";

		private const string BundleName = "crownsandtiaras";

		internal static ManualLogSource Log;

		private AssetBundle? _bundle;

		private ConfigEntry<bool> _useGameShader;

		private ConfigEntry<bool> _diagnostics;

		private ConfigEntry<bool> _giveItems;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			_useGameShader = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "UseGameShader", true, "Render the models with the game's own copy of their shader. Turn off to use the shader compiled into the mod's asset bundle instead. Only for comparing the two while testing. Takes effect on the next launch.");
			_diagnostics = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "Diagnostics", false, "Write test lines to the log: whether the items and recipes exist, whether the crafting menu lists them, and what is on the character's head and where. Also saves, in BepInEx\\CrownsAndTiaras, each rendered icon as a PNG and the character's head as an OBJ file for fitting new models. Takes effect on the next launch.");
			_giveItems = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "GiveItemsOnSpawn", false, "On entering a world, put one of each item this mod adds into the inventory if the character has none. For testing how an item looks without crafting it. Takes effect on the next launch.");
			CrownDiagnostics crownDiagnostics = ((Component)this).gameObject.AddComponent<CrownDiagnostics>();
			crownDiagnostics.LogState = _diagnostics.Value;
			crownDiagnostics.GiveItems = _giveItems.Value;
			_bundle = AssetUtils.LoadAssetBundleFromResources("crownsandtiaras");
			if (!Object.op_Implicit((Object)(object)_bundle))
			{
				Log.LogError((object)"The asset bundle could not be loaded, so no items were added. If the log just above mentions the Unity version, the bundle was built with an editor the game cannot read.");
				return;
			}
			Log.LogInfo((object)("Asset bundle loaded: " + string.Join(", ", _bundle.GetAllAssetNames())));
			AddTranslations();
			PrefabManager.OnVanillaPrefabsAvailable += AddItems;
		}

		private static void AddTranslations()
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			CrownDef[] all = CrownDefs.All;
			foreach (CrownDef crownDef in all)
			{
				dictionary[crownDef.NameToken] = crownDef.Name;
				dictionary[crownDef.DescriptionToken] = crownDef.Description;
			}
			CustomLocalization localization = LocalizationManager.Instance.GetLocalization();
			string text = "English";
			localization.AddTranslation(ref text, dictionary);
		}

		private void AddItems()
		{
			PrefabManager.OnVanillaPrefabsAvailable -= AddItems;
			CrownDef[] all = CrownDefs.All;
			foreach (CrownDef crownDef in all)
			{
				try
				{
					CrownFactory.Add(_bundle, crownDef, _useGameShader.Value, _diagnostics.Value);
				}
				catch (Exception arg)
				{
					Log.LogError((object)$"{crownDef.Id} was not added: {arg}");
				}
			}
		}
	}
}