Decompiled source of Guilds v1.5.1

Guilds.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Splatform;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.TextCore;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace Guilds;

internal static class Banner
{
	public const string PrefabName = "Guilds_Banner";

	public const string ZdoKey = "Guilds_BannerGuild";

	public static Sprite Icon;

	public static void Register()
	{
		PrefabManager.OnVanillaPrefabsAvailable += Create;
	}

	private static void Create()
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Expected O, but got Unknown
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Expected O, but got Unknown
		PrefabManager.OnVanillaPrefabsAvailable -= Create;
		try
		{
			PieceConfig val = new PieceConfig();
			val.Name = Loc.T("banner_name");
			val.Description = Loc.T("banner_desc");
			val.PieceTable = "Hammer";
			val.Category = "Guild";
			string[] array = Plugin.BannerRecipe.Value.Split(',');
			foreach (string text in array)
			{
				string[] array2 = text.Split(':');
				if (array2.Length == 2 && int.TryParse(array2[1].Trim(), out var result) && result > 0)
				{
					val.AddRequirement(array2[0].Trim(), result, true);
				}
			}
			CustomPiece val2 = new CustomPiece("Guilds_Banner", "piece_banner01", val);
			GameObject piecePrefab = val2.PiecePrefab;
			if ((Object)(object)piecePrefab == (Object)null)
			{
				Plugin.Log.LogError((object)"Could not clone piece_banner01 — the guild banner is not available.");
				return;
			}
			if (!BannerModel.Apply(piecePrefab))
			{
				Plugin.Log.LogWarning((object)"Guild banner model could not be loaded — using the vanilla banner look.");
				Cloth[] componentsInChildren = piecePrefab.GetComponentsInChildren<Cloth>(true);
				foreach (Cloth val3 in componentsInChildren)
				{
					Object.DestroyImmediate((Object)(object)val3);
				}
			}
			piecePrefab.AddComponent<GuildBanner>();
			if ((Object)(object)BannerModel.Icon != (Object)null && (Object)(object)val2.Piece != (Object)null)
			{
				val2.Piece.m_icon = BannerModel.Icon;
			}
			PieceManager.Instance.AddPiece(val2);
			Icon = (((Object)(object)val2.Piece != (Object)null) ? val2.Piece.m_icon : null);
			Territory.SetEffectIcons(Icon);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("Guild banner registration failed: " + ex));
		}
	}

	public static void RPC_Rejected(long sender, ZPackage pkg)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_006f: Unknown result type (might be due to invalid IL or missing references)
		ZDOID val = pkg.ReadZDOID();
		string text = pkg.ReadString();
		if ((Object)(object)Player.m_localPlayer != (Object)null)
		{
			((Character)Player.m_localPlayer).Message((MessageType)2, Loc.T("banner_rejected", Loc.T("s_raw", text)), 0, (Sprite)null, false);
		}
		GameObject val2 = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.FindInstance(val) : null);
		if ((Object)(object)val2 == (Object)null)
		{
			return;
		}
		ZNetView component = val2.GetComponent<ZNetView>();
		if (!((Object)(object)component == (Object)null) && component.IsValid() && component.IsOwner())
		{
			Piece component2 = val2.GetComponent<Piece>();
			if ((Object)(object)component2 != (Object)null)
			{
				component2.DropResources((HitData)null);
			}
			ZNetScene.instance.Destroy(val2);
		}
	}
}
public class GuildBanner : MonoBehaviour, Hoverable, Interactable
{
	private ZNetView _nv;

	private Piece _piece;

	private Renderer _renderer;

	private MaterialPropertyBlock _block;

	private string _applied;

	public long GuildId
	{
		get
		{
			if (!((Object)(object)_nv != (Object)null) || !_nv.IsValid())
			{
				return 0L;
			}
			return _nv.GetZDO().GetLong("Guilds_BannerGuild", 0L);
		}
	}

	private void Awake()
	{
		_nv = ((Component)this).GetComponent<ZNetView>();
		_piece = ((Component)this).GetComponent<Piece>();
	}

	private void Start()
	{
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)_nv == (Object)null || !_nv.IsValid())
		{
			return;
		}
		if (_nv.IsOwner() && GuildId == 0 && (Object)(object)_piece != (Object)null && _piece.IsCreator())
		{
			MemberInfo memberInfo = GuildClient.Member(GuildClient.LocalPid);
			if (memberInfo != null)
			{
				_nv.GetZDO().Set("Guilds_BannerGuild", memberInfo.GuildId);
				GuildClient.RegisterBanner(_nv.GetZDO().m_uid, ((Component)this).transform.position);
			}
		}
		((MonoBehaviour)this).InvokeRepeating("Refresh", 0.3f, 2f);
	}

	internal bool IsActive(GuildInfo g)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		if (g != null && g.HasBanner)
		{
			Vector3 val = g.BannerPos - ((Component)this).transform.position;
			return ((Vector3)(ref val)).sqrMagnitude < 4f;
		}
		return false;
	}

	private void Refresh()
	{
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		if (GuildId == 0 && (Object)(object)_nv != (Object)null && _nv.IsValid() && _nv.IsOwner() && (Object)(object)_piece != (Object)null)
		{
			MemberInfo memberInfo = GuildClient.Member(_piece.GetCreator());
			if (memberInfo != null && _piece.IsCreator())
			{
				_nv.GetZDO().Set("Guilds_BannerGuild", memberInfo.GuildId);
				GuildClient.RegisterBanner(_nv.GetZDO().m_uid, ((Component)this).transform.position);
			}
		}
		GuildInfo guildInfo = GuildClient.Guild(GuildId);
		string text = ((guildInfo != null) ? (guildInfo.ColorHex + "|" + guildInfo.Emblem) : "-");
		if (text == _applied)
		{
			return;
		}
		_applied = text;
		try
		{
			ApplyLook(guildInfo);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Banner look: " + ex.Message));
		}
	}

	private void ApplyLook(GuildInfo g)
	{
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Expected O, but got Unknown
		if ((Object)(object)_renderer == (Object)null)
		{
			Transform val = ((Component)this).transform.Find("GuildBannerModel");
			if ((Object)(object)val != (Object)null)
			{
				_renderer = (Renderer)(object)((Component)val).GetComponent<MeshRenderer>();
			}
		}
		if ((Object)(object)_renderer == (Object)null)
		{
			return;
		}
		Texture2D val2 = BannerModel.TextureFor(g);
		if (!((Object)(object)val2 == (Object)null))
		{
			if (_block == null)
			{
				_block = new MaterialPropertyBlock();
			}
			_renderer.GetPropertyBlock(_block, 0);
			_block.SetTexture("_MainTex", (Texture)(object)val2);
			_block.SetVector("_MainTex_ST", new Vector4(1f, 1f, 0f, 0f));
			_renderer.SetPropertyBlock(_block, 0);
			Plugin.Log.LogInfo((object)string.Concat("Guild banner at ", Vector3Int.RoundToInt(((Component)this).transform.position), ": ", (g != null) ? ("[" + g.Tag + "] colour " + g.ColorHex + ", emblem " + g.Emblem) : ("no guild (guild id " + GuildId + ")")));
		}
	}

	public float GetHoverOffset()
	{
		return 0f;
	}

	public string GetHoverName()
	{
		return Loc.T("banner_name");
	}

	public string GetHoverText()
	{
		GuildInfo guildInfo = GuildClient.Guild(GuildId);
		string text;
		if (guildInfo == null)
		{
			text = Loc.T("banner_name") + "\n<color=#9A9A9A>" + Loc.T("banner_abandoned") + "</color>";
		}
		else
		{
			text = "<color=#" + guildInfo.ColorHex + ">[" + guildInfo.Tag + "] " + guildInfo.Name + "</color>\n" + Loc.T("banner_hover_level", guildInfo.Level, Mathf.RoundToInt(guildInfo.Half * 2f));
			if (!IsActive(guildInfo))
			{
				text = text + "\n<color=#FF7766>" + Loc.T("banner_inactive") + "</color>";
			}
			MemberInfo memberInfo = GuildClient.Member(GuildClient.LocalPid);
			if (memberInfo != null && memberInfo.GuildId == guildInfo.Id)
			{
				text = text + "\n[<color=yellow><b>$KEY_Use</b></color>] " + Loc.T("banner_open");
				if (guildInfo.Tier("respawn") > 0)
				{
					text = text + "\n[<color=yellow><b>$KEY_AltPlace + $KEY_Use</b></color>] " + Loc.T(Territory.WantsBannerSpawn(guildInfo.Id) ? "banner_spawn_off" : "banner_spawn_on");
				}
			}
		}
		return Localization.instance.Localize(text);
	}

	public bool Interact(Humanoid user, bool hold, bool alt)
	{
		if (hold)
		{
			return false;
		}
		GuildInfo guildInfo = GuildClient.Guild(GuildId);
		MemberInfo memberInfo = GuildClient.Member(GuildClient.LocalPid);
		if (guildInfo == null || memberInfo == null || memberInfo.GuildId != guildInfo.Id)
		{
			((Character)user).Message((MessageType)2, (guildInfo != null) ? Loc.T("banner_foreign", "[" + guildInfo.Tag + "] " + guildInfo.Name) : Loc.T("banner_abandoned"), 0, (Sprite)null, false);
			return false;
		}
		if (alt)
		{
			if (guildInfo.Tier("respawn") == 0)
			{
				((Character)user).Message((MessageType)2, Loc.T("banner_spawn_locked"), 0, (Sprite)null, false);
				return true;
			}
			bool flag = !Territory.WantsBannerSpawn(guildInfo.Id);
			Territory.SetBannerSpawn(guildInfo.Id, flag);
			((Character)user).Message((MessageType)2, Loc.T(flag ? "banner_spawn_set" : "banner_spawn_cleared"), 0, (Sprite)null, false);
			return true;
		}
		GuildUI.OpenBanner();
		return true;
	}

	public bool UseItem(Humanoid user, ItemData item)
	{
		return false;
	}
}
internal static class BannerModel
{
	private const int EmblemPx = 330;

	private const float EmblemU = 0.498f;

	private const float EmblemVTop = 0.2915f;

	public static Mesh Mesh;

	public static Material ClothMaterial;

	public static Material PartsMaterial;

	public static Sprite Icon;

	private static Color32[] _base;

	private static int _size;

	private static readonly Dictionary<string, Texture2D> Cache = new Dictionary<string, Texture2D>();

	internal static byte[] Resource(string name)
	{
		Assembly assembly = typeof(BannerModel).Assembly;
		using Stream stream = assembly.GetManifestResourceStream("Guilds." + name);
		if (stream == null)
		{
			return null;
		}
		byte[] array = new byte[stream.Length];
		for (int i = 0; i < array.Length; i += stream.Read(array, i, array.Length - i))
		{
		}
		return array;
	}

	public static bool Load(Material template)
	{
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0059: Expected O, but got Unknown
		//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_014c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0153: Expected O, but got Unknown
		//IL_0179: 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)
		if ((Object)(object)Mesh != (Object)null)
		{
			return true;
		}
		byte[] array = Resource("banner.mesh");
		byte[] array2 = Resource("banner_cloth.png");
		byte[] array3 = Resource("banner_icon.png");
		if (array == null || array2 == null || (Object)(object)template == (Object)null)
		{
			return false;
		}
		Mesh = ReadMesh(array, out var palette);
		Texture2D val = new Texture2D(2, 2, (TextureFormat)4, true);
		ImageConversion.LoadImage(val, array2, false);
		_size = ((Texture)val).width;
		_base = val.GetPixels32();
		Color32[] array4 = (Color32[])(object)new Color32[_base.Length];
		for (int i = 0; i < array4.Length; i++)
		{
			ref Color32 reference = ref array4[i];
			reference = _base[i];
			array4[i].a = byte.MaxValue;
		}
		val.SetPixels32(array4);
		val.Apply(true);
		((Object)val).name = "GuildBannerCloth";
		((Texture)val).wrapMode = (TextureWrapMode)1;
		((Texture)val).anisoLevel = 4;
		Texture2D tex = PartsTexture(palette);
		ClothMaterial = MakeMaterial(template, val, "GuildBanner_Cloth");
		Texture2D val2 = TextureFor(null);
		if ((Object)(object)val2 != (Object)null)
		{
			ClothMaterial.mainTexture = (Texture)(object)val2;
		}
		PartsMaterial = MakeMaterial(template, tex, "GuildBanner_Parts");
		if (array3 != null)
		{
			Texture2D val3 = new Texture2D(2, 2, (TextureFormat)4, false);
			ImageConversion.LoadImage(val3, array3, false);
			Icon = Sprite.Create(val3, new Rect(0f, 0f, (float)((Texture)val3).width, (float)((Texture)val3).height), new Vector2(0.5f, 0.5f), 100f);
			((Object)Icon).name = "GuildBannerIcon";
		}
		return true;
	}

	private static Texture2D PartsTexture(Color[] palette)
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Expected O, but got Unknown
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0244: Unknown result type (might be due to invalid IL or missing references)
		//IL_0249: Unknown result type (might be due to invalid IL or missing references)
		int num = palette.Length * 8;
		Texture2D val = new Texture2D(num, 128, (TextureFormat)4, true);
		Random random = new Random(7);
		Color[] array = (Color[])(object)new Color[num * 128];
		for (int i = 0; i < palette.Length; i++)
		{
			Color val2 = palette[i];
			float num2 = Mathf.Max(val2.r, Mathf.Max(val2.g, val2.b)) - Mathf.Min(val2.r, Mathf.Min(val2.g, val2.b));
			bool flag = num2 > 0.12f && val2.r > val2.b * 1.4f;
			float num3 = (flag ? 0.22f : 0.12f);
			double num4 = random.NextDouble() * 6.28;
			double num5 = random.NextDouble() * 6.28;
			for (int j = 0; j < 128; j++)
			{
				float num6 = (float)j / 128f;
				float num7 = (flag ? ((float)(Math.Sin((double)num6 * 6.283 * 9.0 + num4) * 0.5 + Math.Sin((double)num6 * 6.283 * 23.0 + num5) * 0.3 + Math.Sin((double)num6 * 6.283 * 61.0) * 0.2)) : ((float)(Math.Sin((double)num6 * 6.283 * 4.0 + num4) * 0.6 + Math.Sin((double)num6 * 6.283 * 13.0 + num5) * 0.4)));
				for (int k = 0; k < 8; k++)
				{
					float num8 = (float)(random.NextDouble() - 0.5) * (flag ? 0.16f : 0.1f);
					float num9 = 1f + num7 * num3 + num8;
					ref Color reference = ref array[j * num + i * 8 + k];
					reference = new Color(Mathf.Clamp01(val2.r * num9), Mathf.Clamp01(val2.g * num9), Mathf.Clamp01(val2.b * num9), 1f);
				}
			}
		}
		val.SetPixels(array);
		val.Apply(true);
		((Texture)val).wrapModeU = (TextureWrapMode)1;
		((Texture)val).wrapModeV = (TextureWrapMode)0;
		((Texture)val).filterMode = (FilterMode)1;
		((Object)val).name = "GuildBannerParts";
		return val;
	}

	private static Material MakeMaterial(Material template, Texture2D tex, string name)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		Material val = new Material(template);
		((Object)val).name = name;
		val.mainTexture = (Texture)(object)tex;
		ResetTiling(val);
		if (val.HasProperty("_MainTex"))
		{
			val.SetTexture("_MainTex", (Texture)(object)tex);
		}
		if (val.HasProperty("_Color"))
		{
			val.color = Color.white;
		}
		string[] array = new string[4] { "_BumpMap", "_MetallicGlossMap", "_EmissionMap", "_OcclusionMap" };
		foreach (string text in array)
		{
			if (val.HasProperty(text))
			{
				val.SetTexture(text, (Texture)null);
			}
		}
		if (val.HasProperty("_Cutoff"))
		{
			val.SetFloat("_Cutoff", 0f);
		}
		return val;
	}

	private static void ResetTiling(Material m)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Invalid comparison between Unknown and I4
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		m.mainTextureScale = Vector2.one;
		m.mainTextureOffset = Vector2.zero;
		Shader shader = m.shader;
		if ((Object)(object)shader == (Object)null)
		{
			return;
		}
		StringBuilder stringBuilder = new StringBuilder();
		for (int i = 0; i < shader.GetPropertyCount(); i++)
		{
			if ((int)shader.GetPropertyType(i) == 4)
			{
				string propertyName = shader.GetPropertyName(i);
				stringBuilder.Append(propertyName).Append(" scale ").Append(m.GetTextureScale(propertyName))
					.Append("; ");
				m.SetTextureScale(propertyName, Vector2.one);
				m.SetTextureOffset(propertyName, Vector2.zero);
			}
		}
		if (((Object)m).name == "GuildBanner_Cloth")
		{
			Plugin.Log.LogInfo((object)("Guild banner shader: " + ((Object)shader).name + " | textures: " + stringBuilder));
		}
	}

	private static Mesh ReadMesh(byte[] data, out Color[] palette)
	{
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_012d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0132: Unknown result type (might be due to invalid IL or missing references)
		//IL_0145: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Expected O, but got Unknown
		//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
		using BinaryReader binaryReader = new BinaryReader(new MemoryStream(data));
		binaryReader.ReadInt32();
		int num = binaryReader.ReadInt32();
		Vector3[] array = (Vector3[])(object)new Vector3[num];
		Vector2[] array2 = (Vector2[])(object)new Vector2[num];
		for (int i = 0; i < num; i++)
		{
			ref Vector3 reference = ref array[i];
			reference = new Vector3(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle());
		}
		for (int j = 0; j < num; j++)
		{
			ref Vector2 reference2 = ref array2[j];
			reference2 = new Vector2(binaryReader.ReadSingle(), binaryReader.ReadSingle());
		}
		int[] array3 = new int[binaryReader.ReadInt32()];
		for (int k = 0; k < array3.Length; k++)
		{
			array3[k] = binaryReader.ReadInt32();
		}
		int[] array4 = new int[binaryReader.ReadInt32()];
		for (int l = 0; l < array4.Length; l++)
		{
			array4[l] = binaryReader.ReadInt32();
		}
		palette = (Color[])(object)new Color[binaryReader.ReadInt32()];
		for (int m = 0; m < palette.Length; m++)
		{
			float num2 = binaryReader.ReadSingle();
			float num3 = binaryReader.ReadSingle();
			float num4 = binaryReader.ReadSingle();
			ref Color reference3 = ref palette[m];
			reference3 = new Color(Mathf.LinearToGammaSpace(num2), Mathf.LinearToGammaSpace(num3), Mathf.LinearToGammaSpace(num4), 1f);
		}
		Mesh val = new Mesh();
		((Object)val).name = "GuildBanner";
		if (num > 65000)
		{
			val.indexFormat = (IndexFormat)1;
		}
		val.vertices = array;
		val.uv = array2;
		Color32[] array5 = (Color32[])(object)new Color32[num];
		for (int n = 0; n < num; n++)
		{
			ref Color32 reference4 = ref array5[n];
			reference4 = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue);
		}
		val.colors32 = array5;
		val.subMeshCount = 2;
		val.SetTriangles(array3, 0);
		val.SetTriangles(array4, 1);
		val.RecalculateNormals();
		val.RecalculateTangents();
		val.RecalculateBounds();
		return val;
	}

	public static Texture2D TextureFor(GuildInfo g)
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0026: Expected O, but got Unknown
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: 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_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0227: Unknown result type (might be due to invalid IL or missing references)
		//IL_022c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0263: Unknown result type (might be due to invalid IL or missing references)
		//IL_0269: Expected O, but got Unknown
		if (_base == null)
		{
			if (!((Object)(object)ClothMaterial != (Object)null))
			{
				return null;
			}
			return (Texture2D)ClothMaterial.mainTexture;
		}
		string key = ((g != null) ? (g.ColorHex + "|" + g.Emblem) : "-");
		if (Cache.TryGetValue(key, out var value) && (Object)(object)value != (Object)null)
		{
			return value;
		}
		Color val = (Color)(((??)g?.Color) ?? new Color(0.62f, 0.12f, 0.1f));
		float num = val.r * 0.299f + val.g * 0.587f + val.b * 0.114f;
		if (num < 0.25f)
		{
			val = Color.Lerp(val, Color.white, 0.35f);
		}
		Color32[] array = (Color32[])(object)new Color32[_base.Length];
		for (int i = 0; i < array.Length; i++)
		{
			Color32 val2 = _base[i];
			float num2 = (float)(val2.r + val2.g + val2.b) / 765f;
			float num3 = Mathf.Clamp01((num2 - 0.2f) / 0.6f);
			float num4 = 0.028f + 0.085f * num3 * num3 * (3f - 2f * num3);
			float num5 = Mathf.Clamp01(((float)(int)val2.a / 255f - 0.18f) / 0.82f);
			float num6 = 0.8f + 0.35f * Mathf.Clamp01((float)(int)val2.r / 220f);
			float num7 = Mathf.Lerp(num4, val.r * num6, num5);
			float num8 = Mathf.Lerp(num4 * 0.97f, val.g * num6, num5);
			float num9 = Mathf.Lerp(num4 * 0.95f, val.b * num6, num5);
			ref Color32 reference = ref array[i];
			reference = new Color32((byte)Mathf.Clamp(num7 * 255f, 0f, 255f), (byte)Mathf.Clamp(num8 * 255f, 0f, 255f), (byte)Mathf.Clamp(num9 * 255f, 0f, 255f), byte.MaxValue);
		}
		if (g != null)
		{
			PaintEmblem(array, Visuals.EmblemSprite(g.Emblem));
		}
		value = new Texture2D(_size, _size, (TextureFormat)4, true);
		value.SetPixels32(array);
		value.Apply(true, true);
		((Texture)value).wrapMode = (TextureWrapMode)1;
		((Texture)value).anisoLevel = 4;
		((Object)value).name = "GuildBannerCloth_" + ((g != null) ? g.Tag : "none");
		Cache[key] = value;
		return value;
	}

	private static void PaintEmblem(Color32[] px, Sprite s)
	{
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_0175: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01df: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0209: Unknown result type (might be due to invalid IL or missing references)
		//IL_020e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0247: Unknown result type (might be due to invalid IL or missing references)
		//IL_024c: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)s == (Object)null || (Object)(object)s.texture == (Object)null)
		{
			return;
		}
		Color[] array = ReadSprite(s, 330);
		if (array == null)
		{
			return;
		}
		int num = 330;
		float[] array2 = new float[num * num];
		for (int i = 0; i < array2.Length; i++)
		{
			array2[i] = array[i].a;
		}
		int num2 = Mathf.RoundToInt(0.498f * (float)_size);
		int num3 = Mathf.RoundToInt(0.7085f * (float)_size);
		int num4 = num2 - num / 2;
		int num5 = num3 - num / 2;
		Color val2 = default(Color);
		for (int j = 0; j < num; j++)
		{
			for (int k = 0; k < num; k++)
			{
				int num6 = num4 + k;
				int num7 = num5 + j;
				if (num6 < 0 || num7 < 0 || num6 >= _size || num7 >= _size)
				{
					continue;
				}
				int num8 = num7 * _size + num6;
				float num9 = array2[j * num + k];
				float num10 = 0f;
				for (int l = -2; l <= 2; l++)
				{
					if (!(num10 < 1f))
					{
						break;
					}
					for (int m = -2; m <= 2; m++)
					{
						if (m * m + l * l <= 5)
						{
							int num11 = k + m;
							int num12 = j + l;
							if (num11 >= 0 && num12 >= 0 && num11 < num && num12 < num)
							{
								num10 = Mathf.Max(num10, array2[num12 * num + num11]);
							}
						}
					}
				}
				if (!(num10 <= 0.02f))
				{
					Color32 val = px[num8];
					((Color)(ref val2))..ctor((float)(int)val.r / 255f, (float)(int)val.g / 255f, (float)(int)val.b / 255f);
					Color val3 = Color.Lerp(val2, new Color(0.93f, 0.92f, 0.88f), Mathf.Clamp01(num10 * 1.4f));
					Color val4 = array[j * num + k];
					Color val5 = Color.Lerp(val3, new Color(val4.r, val4.g, val4.b), Mathf.Clamp01(num9));
					ref Color32 reference = ref px[num8];
					reference = new Color32((byte)(val5.r * 255f), (byte)(val5.g * 255f), (byte)(val5.b * 255f), byte.MaxValue);
				}
			}
		}
	}

	internal static Color[] ReadSprite(Sprite s, int size)
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Expected O, but got Unknown
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		RenderTexture active = RenderTexture.active;
		RenderTexture temporary = RenderTexture.GetTemporary(size, size, 0, (RenderTextureFormat)0);
		try
		{
			Texture texture = (Texture)(object)s.texture;
			Rect textureRect = s.textureRect;
			RenderTexture.active = temporary;
			GL.Clear(true, true, new Color(0f, 0f, 0f, 0f));
			Graphics.Blit(texture, temporary, new Vector2(((Rect)(ref textureRect)).width / (float)texture.width, ((Rect)(ref textureRect)).height / (float)texture.height), new Vector2(((Rect)(ref textureRect)).x / (float)texture.width, ((Rect)(ref textureRect)).y / (float)texture.height));
			Texture2D val = new Texture2D(size, size, (TextureFormat)4, false);
			RenderTexture.active = temporary;
			val.ReadPixels(new Rect(0f, 0f, (float)size, (float)size), 0, 0);
			val.Apply(false);
			Color[] pixels = val.GetPixels();
			Object.Destroy((Object)(object)val);
			return pixels;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Could not read emblem for the banner: " + ex.Message));
			return null;
		}
		finally
		{
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
		}
	}

	public static bool Apply(GameObject prefab)
	{
		//IL_019a: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a1: Expected O, but got Unknown
		//IL_0212: Unknown result type (might be due to invalid IL or missing references)
		//IL_0226: Unknown result type (might be due to invalid IL or missing references)
		//IL_0241: Unknown result type (might be due to invalid IL or missing references)
		//IL_0255: Unknown result type (might be due to invalid IL or missing references)
		//IL_0270: Unknown result type (might be due to invalid IL or missing references)
		//IL_0284: Unknown result type (might be due to invalid IL or missing references)
		//IL_029f: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_0388: Unknown result type (might be due to invalid IL or missing references)
		//IL_038f: Expected O, but got Unknown
		//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
		Material val = null;
		int layer = prefab.layer;
		Renderer[] componentsInChildren = prefab.GetComponentsInChildren<Renderer>(true);
		foreach (Renderer val2 in componentsInChildren)
		{
			if ((Object)(object)val == (Object)null && val2 is MeshRenderer && (Object)(object)val2.sharedMaterial != (Object)null)
			{
				val = val2.sharedMaterial;
			}
		}
		Renderer[] componentsInChildren2 = prefab.GetComponentsInChildren<Renderer>(true);
		foreach (Renderer val3 in componentsInChildren2)
		{
			if ((Object)(object)val == (Object)null && (Object)(object)val3.sharedMaterial != (Object)null)
			{
				val = val3.sharedMaterial;
			}
		}
		Collider[] componentsInChildren3 = prefab.GetComponentsInChildren<Collider>(true);
		int num = 0;
		if (num < componentsInChildren3.Length)
		{
			Collider val4 = componentsInChildren3[num];
			layer = ((Component)val4).gameObject.layer;
		}
		if (!Load(val))
		{
			return false;
		}
		Cloth[] componentsInChildren4 = prefab.GetComponentsInChildren<Cloth>(true);
		foreach (Cloth val5 in componentsInChildren4)
		{
			Object.DestroyImmediate((Object)(object)val5);
		}
		Renderer[] componentsInChildren5 = prefab.GetComponentsInChildren<Renderer>(true);
		foreach (Renderer val6 in componentsInChildren5)
		{
			Object.DestroyImmediate((Object)(object)val6);
		}
		MeshFilter[] componentsInChildren6 = prefab.GetComponentsInChildren<MeshFilter>(true);
		foreach (MeshFilter val7 in componentsInChildren6)
		{
			Object.DestroyImmediate((Object)(object)val7);
		}
		Collider[] componentsInChildren7 = prefab.GetComponentsInChildren<Collider>(true);
		foreach (Collider val8 in componentsInChildren7)
		{
			Object.DestroyImmediate((Object)(object)val8);
		}
		GameObject val9 = new GameObject("GuildBannerModel", new Type[2]
		{
			typeof(MeshFilter),
			typeof(MeshRenderer)
		});
		val9.layer = layer;
		val9.transform.SetParent(prefab.transform, false);
		val9.GetComponent<MeshFilter>().sharedMesh = Mesh;
		MeshRenderer component = val9.GetComponent<MeshRenderer>();
		((Renderer)component).sharedMaterials = (Material[])(object)new Material[2] { ClothMaterial, PartsMaterial };
		((Renderer)component).shadowCastingMode = (ShadowCastingMode)1;
		AddBox(val9, new Vector3(0f, 2.1f, -0.1f), new Vector3(0.22f, 4.2f, 0.22f));
		AddBox(val9, new Vector3(0f, 1.95f, 0.12f), new Vector3(1.95f, 1.95f, 0.22f));
		AddBox(val9, new Vector3(0f, 3.06f, 0f), new Vector3(3.1f, 0.16f, 0.16f));
		AddBox(val9, new Vector3(0f, 0.05f, -0.1f), new Vector3(1.12f, 0.1f, 1.12f));
		Piece component2 = prefab.GetComponent<Piece>();
		if ((Object)(object)component2 != (Object)null)
		{
			component2.m_notOnFloor = false;
			component2.m_inCeilingOnly = false;
			component2.m_groundPiece = false;
			component2.m_groundOnly = false;
			component2.m_cultivatedGroundOnly = false;
			component2.m_waterPiece = false;
			component2.m_noInWater = true;
			component2.m_notOnWood = false;
			component2.m_notOnTiltingSurface = false;
			component2.m_clipGround = true;
			component2.m_clipEverything = false;
			component2.m_noClipping = false;
			component2.m_onlyInTeleportArea = false;
		}
		Transform[] componentsInChildren8 = prefab.GetComponentsInChildren<Transform>(true);
		foreach (Transform val10 in componentsInChildren8)
		{
			if ((Object)(object)val10 != (Object)(object)prefab.transform && ((Component)val10).CompareTag("snappoint"))
			{
				Object.DestroyImmediate((Object)(object)((Component)val10).gameObject);
			}
		}
		GameObject val11 = new GameObject("_snappoint");
		val11.tag = "snappoint";
		val11.layer = layer;
		val11.transform.SetParent(prefab.transform, false);
		val11.transform.localPosition = Vector3.zero;
		val11.SetActive(false);
		return true;
	}

	private static void AddBox(GameObject go, Vector3 center, Vector3 size)
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		BoxCollider val = go.AddComponent<BoxCollider>();
		val.center = center;
		val.size = size;
	}
}
internal static class Barrier
{
	private static Vector3 _lastOutside;

	private static bool _hasOutside;

	private static long _inside;

	private static float _msgAt = -10f;

	private static float _curtainTimer;

	private static readonly Dictionary<long, GameObject> Curtains = new Dictionary<long, GameObject>();

	private static readonly Dictionary<long, string> CurtainKeys = new Dictionary<long, string>();

	private static Material _mat;

	public static bool MayEnter(GuildInfo owner)
	{
		if (!GuildClient.BarrierEnabled || owner == null)
		{
			return true;
		}
		MemberInfo memberInfo = GuildClient.Member(GuildClient.LocalPid);
		if (memberInfo == null)
		{
			return false;
		}
		if (memberInfo.GuildId == owner.Id)
		{
			return true;
		}
		return owner.RelationWith(memberInfo.GuildId) switch
		{
			Relation.Ally => GuildClient.AlliesCanEnter, 
			Relation.War => true, 
			_ => false, 
		};
	}

	private static string Name(GuildInfo g)
	{
		return "<color=#" + g.ColorHex + ">[" + g.Tag + "] " + g.Name + "</color>";
	}

	public static void Update()
	{
		//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_0096: 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_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Unknown result type (might be due to invalid IL or missing references)
		//IL_011f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f0: 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_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_012b: Unknown result type (might be due to invalid IL or missing references)
		//IL_012e: 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_0126: Unknown result type (might be due to invalid IL or missing references)
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null)
		{
			_hasOutside = false;
			_inside = 0L;
			return;
		}
		try
		{
			_curtainTimer -= Time.deltaTime;
			if (_curtainTimer <= 0f)
			{
				_curtainTimer = 0.5f;
				UpdateCurtains(localPlayer);
			}
			if (((Character)localPlayer).IsDead() || ((Character)localPlayer).IsTeleporting())
			{
				_hasOutside = false;
				return;
			}
			Vector3 position = ((Component)localPlayer).transform.position;
			GuildInfo here = null;
			GuildInfo guildInfo = null;
			foreach (GuildInfo guild in GuildClient.GuildList)
			{
				if (guild.HasBanner && guild.Contains(position, 0f))
				{
					if (!MayEnter(guild))
					{
						guildInfo = guild;
						break;
					}
					here = guild;
				}
			}
			if (guildInfo == null)
			{
				_lastOutside = position;
				_hasOutside = true;
				Announce(here);
				return;
			}
			Vector3 val2;
			if (_hasOutside)
			{
				Vector3 val = position - _lastOutside;
				if (((Vector3)(ref val)).sqrMagnitude < 100f && !guildInfo.Contains(_lastOutside, 0f))
				{
					val2 = _lastOutside;
					goto IL_012b;
				}
			}
			val2 = EdgeOutside(guildInfo, position);
			goto IL_012b;
			IL_012b:
			Vector3 target = val2;
			Move(localPlayer, target);
			if (Time.time - _msgAt > 3f && (Object)(object)MessageHud.instance != (Object)null)
			{
				_msgAt = Time.time;
				MessageHud.instance.ShowMessage((MessageType)2, Loc.T("terr_barrier", Name(guildInfo)), 0, (Sprite)null, false, true);
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Territory barrier: " + ex.Message));
		}
	}

	private static void Announce(GuildInfo here)
	{
		long num = here?.Id ?? 0;
		if (num == _inside || (Object)(object)MessageHud.instance == (Object)null)
		{
			_inside = num;
			return;
		}
		GuildInfo guildInfo = ((_inside != 0) ? GuildClient.Guild(_inside) : null);
		_inside = num;
		if (here != null)
		{
			MemberInfo memberInfo = GuildClient.Member(GuildClient.LocalPid);
			bool flag = memberInfo != null && memberInfo.GuildId != here.Id && here.RelationWith(memberInfo.GuildId) == Relation.War;
			MessageHud.instance.ShowMessage((MessageType)2, Loc.T(flag ? "terr_enter_enemy" : "terr_enter", Name(here)), 0, (Sprite)null, false, true);
		}
		else if (guildInfo != null)
		{
			MessageHud.instance.ShowMessage((MessageType)1, Loc.T("terr_leave", Name(guildInfo)), 0, (Sprite)null, false, true);
		}
	}

	private static Vector3 EdgeOutside(GuildInfo g, Vector3 pos)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: 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_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: 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)
		Vector3 val = pos - g.BannerPos;
		float num = g.Half + 1.5f;
		Vector3 result = pos;
		if (num - Mathf.Abs(val.x) < num - Mathf.Abs(val.z))
		{
			result.x = g.BannerPos.x + ((val.x >= 0f) ? num : (0f - num));
		}
		else
		{
			result.z = g.BannerPos.z + ((val.z >= 0f) ? num : (0f - num));
		}
		float num2 = default(float);
		if ((Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.GetGroundHeight(new Vector3(result.x, 0f, result.z), ref num2))
		{
			result.y = num2 + 0.1f;
		}
		return result;
	}

	private static void Move(Player p, Vector3 target)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Unknown result type (might be due to invalid IL or missing references)
		((Component)p).transform.position = target;
		Rigidbody component = ((Component)p).GetComponent<Rigidbody>();
		if ((Object)(object)component != (Object)null)
		{
			component.position = target;
			component.linearVelocity = Vector3.zero;
		}
	}

	private static void UpdateCurtains(Player p)
	{
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		HashSet<long> hashSet = new HashSet<long>();
		if (GuildClient.BarrierEnabled)
		{
			foreach (GuildInfo guild in GuildClient.GuildList)
			{
				if (guild.HasBanner && !MayEnter(guild))
				{
					Vector3 val = ((Component)p).transform.position - guild.BannerPos;
					float num = Mathf.Max(Mathf.Abs(val.x), Mathf.Abs(val.z)) - guild.Half;
					if (!(num > 40f))
					{
						hashSet.Add(guild.Id);
						Draw(guild);
					}
				}
			}
		}
		List<long> list = new List<long>();
		foreach (long key in Curtains.Keys)
		{
			if (!hashSet.Contains(key))
			{
				list.Add(key);
			}
		}
		foreach (long item in list)
		{
			if ((Object)(object)Curtains[item] != (Object)null)
			{
				Object.Destroy((Object)(object)Curtains[item]);
			}
			Curtains.Remove(item);
			CurtainKeys.Remove(item);
		}
	}

	private static void Draw(GuildInfo g)
	{
		//IL_00e0: 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_0117: Unknown result type (might be due to invalid IL or missing references)
		//IL_011c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_016d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0172: Unknown result type (might be due to invalid IL or missing references)
		//IL_0198: Unknown result type (might be due to invalid IL or missing references)
		//IL_019d: 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_00d4: Expected O, but got Unknown
		//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0223: Unknown result type (might be due to invalid IL or missing references)
		//IL_0243: Unknown result type (might be due to invalid IL or missing references)
		//IL_0248: Unknown result type (might be due to invalid IL or missing references)
		//IL_024b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0250: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c9: Expected O, but got Unknown
		//IL_0408: Unknown result type (might be due to invalid IL or missing references)
		//IL_040e: Expected O, but got Unknown
		//IL_0288: Unknown result type (might be due to invalid IL or missing references)
		//IL_029b: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a5: 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)
		//IL_02da: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f4: Unknown result type (might be due to invalid IL or missing references)
		//IL_030a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0314: Unknown result type (might be due to invalid IL or missing references)
		//IL_0324: Unknown result type (might be due to invalid IL or missing references)
		//IL_033a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0344: Unknown result type (might be due to invalid IL or missing references)
		//IL_0350: Unknown result type (might be due to invalid IL or missing references)
		//IL_0359: Unknown result type (might be due to invalid IL or missing references)
		string text = ((Vector3)(ref g.BannerPos)).ToString("F1") + "|" + g.Half.ToString("F1") + "|" + g.ColorHex;
		if (CurtainKeys.TryGetValue(g.Id, out var value) && value == text && Curtains.ContainsKey(g.Id))
		{
			return;
		}
		if (Curtains.TryGetValue(g.Id, out var value2) && (Object)(object)value2 != (Object)null)
		{
			Object.Destroy((Object)(object)value2);
		}
		if ((Object)(object)_mat == (Object)null)
		{
			Shader val = Shader.Find("Sprites/Default");
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			_mat = new Material(val);
		}
		bool flag = false;
		float half = g.Half;
		Vector3 bannerPos = g.BannerPos;
		List<Vector3> list = new List<Vector3>();
		Vector3[] array = (Vector3[])(object)new Vector3[4]
		{
			new Vector3(bannerPos.x - half, 0f, bannerPos.z - half),
			new Vector3(bannerPos.x + half, 0f, bannerPos.z - half),
			new Vector3(bannerPos.x + half, 0f, bannerPos.z + half),
			new Vector3(bannerPos.x - half, 0f, bannerPos.z + half)
		};
		for (int i = 0; i < 4; i++)
		{
			Vector3 val2 = array[i];
			Vector3 val3 = array[(i + 1) % 4];
			int num = Mathf.Max(1, Mathf.CeilToInt(Vector3.Distance(val2, val3) / 2f));
			for (int j = 0; j < num; j++)
			{
				list.Add(Vector3.Lerp(val2, val3, (float)j / (float)num));
			}
		}
		list.Add(list[0]);
		List<Vector3> list2 = new List<Vector3>();
		List<Color> list3 = new List<Color>();
		List<int> list4 = new List<int>();
		Color color = g.Color;
		Color color2 = g.Color;
		color.a = 0.38f;
		color2.a = 0f;
		float num2 = default(float);
		for (int k = 0; k < list.Count; k++)
		{
			if ((Object)(object)ZoneSystem.instance == (Object)null || !ZoneSystem.instance.GetGroundHeight(new Vector3(list[k].x, 0f, list[k].z), ref num2))
			{
				num2 = ((WorldGenerator.instance != null) ? WorldGenerator.instance.GetHeight(list[k].x, list[k].z) : bannerPos.y);
				flag = true;
			}
			list2.Add(new Vector3(list[k].x, num2 - 0.5f, list[k].z));
			list2.Add(new Vector3(list[k].x, num2 + 4.5f, list[k].z));
			list3.Add(color);
			list3.Add(color2);
			if (k != 0)
			{
				int num3 = (k - 1) * 2;
				int num4 = k * 2;
				list4.Add(num3);
				list4.Add(num3 + 1);
				list4.Add(num4);
				list4.Add(num4);
				list4.Add(num3 + 1);
				list4.Add(num4 + 1);
			}
		}
		Mesh val4 = new Mesh();
		((Object)val4).name = "Guilds_Barrier";
		val4.SetVertices(list2);
		val4.SetColors(list3);
		val4.SetTriangles(list4, 0);
		val4.RecalculateBounds();
		value2 = new GameObject("Guilds_Barrier_" + g.Tag);
		value2.AddComponent<MeshFilter>().sharedMesh = val4;
		MeshRenderer val5 = value2.AddComponent<MeshRenderer>();
		((Renderer)val5).sharedMaterial = _mat;
		((Renderer)val5).shadowCastingMode = (ShadowCastingMode)0;
		((Renderer)val5).receiveShadows = false;
		Curtains[g.Id] = value2;
		CurtainKeys[g.Id] = (flag ? (text + "|retry") : text);
	}

	public static void Reset()
	{
		foreach (GameObject value in Curtains.Values)
		{
			if ((Object)(object)value != (Object)null)
			{
				Object.Destroy((Object)(object)value);
			}
		}
		Curtains.Clear();
		CurtainKeys.Clear();
		_hasOutside = false;
		_inside = 0L;
	}
}
public class GuildBuilding : MonoBehaviour
{
	private const string PlacedKey = "Guilds_PlacedT";

	private const string AckKey = "Guilds_Ack";

	private const string FurnishedKey = "Guilds_Furnished";

	private const string BKey = "Guilds_BKey";

	private const string LayoutKey = "Guilds_Layout";

	private const int LayoutVersion = 2;

	public string Kind = "";

	internal static readonly List<GuildBuilding> Instances = new List<GuildBuilding>();

	private ZNetView _nv;

	private Piece _piece;

	private bool _removing;

	public long GuildId
	{
		get
		{
			if (!((Object)(object)_nv != (Object)null) || !_nv.IsValid())
			{
				return 0L;
			}
			return _nv.GetZDO().GetLong("Guilds_Building", 0L);
		}
	}

	internal BuildingDef Def => Buildings.Find(Kind);

	private void Awake()
	{
		_nv = ((Component)this).GetComponent<ZNetView>();
		_piece = ((Component)this).GetComponent<Piece>();
	}

	private void OnEnable()
	{
		Instances.Add(this);
	}

	private void OnDisable()
	{
		Instances.Remove(this);
	}

	private void Start()
	{
		if ((Object)(object)_nv == (Object)null || !_nv.IsValid())
		{
			return;
		}
		Transform val = ((Component)this).transform.Find("Model");
		if ((Object)(object)val != (Object)null)
		{
			Transform val2 = val.Find("FurniturePreview");
			if ((Object)(object)val2 != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)val2).gameObject);
			}
		}
		Tick();
		((MonoBehaviour)this).InvokeRepeating("Tick", 2f, 3f);
	}

	private void Tick()
	{
		Adopt();
		TryFurnish();
	}

	private void Adopt()
	{
		//IL_00c6: 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)
		if (!((Object)(object)_nv == (Object)null) && _nv.IsValid() && _nv.IsOwner() && GuildId == 0 && !((Object)(object)_piece == (Object)null) && _piece.IsCreator())
		{
			MemberInfo memberInfo = GuildClient.Member(GuildClient.LocalPid);
			if (memberInfo != null)
			{
				ZDO zDO = _nv.GetZDO();
				zDO.Set("Guilds_Building", memberInfo.GuildId);
				zDO.Set("Guilds_PlacedT", DateTime.UtcNow.Ticks);
				zDO.Set("Guilds_BKey", (long)Random.Range(1, int.MaxValue) * 7919L + DateTime.UtcNow.Ticks % 100000);
				GuildClient.RegisterBuilding(zDO.m_uid, Kind, ((Component)this).transform.position);
			}
		}
	}

	internal void Acknowledge()
	{
		if (!((Object)(object)_nv == (Object)null) && _nv.IsValid())
		{
			if (!_nv.IsOwner())
			{
				_nv.ClaimOwnership();
			}
			_nv.GetZDO().Set("Guilds_Ack", true);
			TryFurnish();
		}
	}

	private long FurnitureKeyOfThis()
	{
		ZDO zDO = _nv.GetZDO();
		long num = zDO.GetLong("Guilds_BKey", 0L);
		if (num == 0)
		{
			num = (long)Random.Range(1, int.MaxValue) * 7919L + DateTime.UtcNow.Ticks % 100000;
			zDO.Set("Guilds_BKey", num);
		}
		return num;
	}

	private void TryFurnish()
	{
		//IL_0174: Unknown result type (might be due to invalid IL or missing references)
		//IL_0179: Unknown result type (might be due to invalid IL or missing references)
		//IL_017e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0186: Unknown result type (might be due to invalid IL or missing references)
		//IL_019c: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)_nv == (Object)null || !_nv.IsValid() || !_nv.IsOwner() || (Object)(object)ZNetScene.instance == (Object)null)
		{
			return;
		}
		ZDO zDO = _nv.GetZDO();
		if (zDO.GetLong("Guilds_Building", 0L) == 0)
		{
			return;
		}
		if (zDO.GetBool("Guilds_Furnished", false))
		{
			if (zDO.GetInt("Guilds_Layout", 1) >= 2)
			{
				return;
			}
			RemoveFurniture();
			_removing = false;
			zDO.Set("Guilds_Furnished", false);
		}
		long num = zDO.GetLong("Guilds_PlacedT", 0L);
		if (num != 0 && !zDO.GetBool("Guilds_Ack", false) && DateTime.UtcNow.Ticks - num < TimeSpan.FromMinutes(2.0).Ticks)
		{
			return;
		}
		BuildingDef def = Def;
		if (def == null)
		{
			return;
		}
		zDO.Set("Guilds_Furnished", true);
		zDO.Set("Guilds_Layout", 2);
		long num2 = FurnitureKeyOfThis();
		long num3 = zDO.GetLong("Guilds_Building", 0L);
		long num4 = (((Object)(object)_piece != (Object)null) ? _piece.GetCreator() : 0);
		int num5 = 0;
		foreach (FurnitureSpot item in def.Furniture)
		{
			GameObject prefab = ZNetScene.instance.GetPrefab(item.Prefab);
			if ((Object)(object)prefab == (Object)null)
			{
				continue;
			}
			Vector3 val = ((Component)this).transform.TransformPoint(item.Pos);
			Quaternion val2 = ((Component)this).transform.rotation * Quaternion.Euler(0f, item.Yaw, 0f);
			GameObject val3 = Object.Instantiate<GameObject>(prefab, val, val2);
			Piece component = val3.GetComponent<Piece>();
			if ((Object)(object)component != (Object)null && num4 != 0)
			{
				component.SetCreator(num4, UserInfo.GetLocalUser().UserId);
			}
			ZNetView component2 = val3.GetComponent<ZNetView>();
			if ((Object)(object)component2 != (Object)null && component2.IsValid())
			{
				component2.GetZDO().Set("Guilds_Furniture", true);
				component2.GetZDO().Set("Guilds_FurnOf", num2);
				component2.GetZDO().Set("Guilds_PartGid", num3);
				if (Kind == "gate" && (Object)(object)val3.GetComponent<Door>() != (Object)null)
				{
					component2.GetZDO().Set("Guilds_GateDoor", true);
				}
			}
			num5++;
		}
		Plugin.Log.LogInfo((object)("Guild building " + Kind + " built from " + num5 + " pieces."));
	}

	internal void RemoveFurniture()
	{
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		if (_removing || (Object)(object)_nv == (Object)null || !_nv.IsValid())
		{
			return;
		}
		_removing = true;
		long num = _nv.GetZDO().GetLong("Guilds_BKey", 0L);
		if (num == 0)
		{
			return;
		}
		List<Piece> list = new List<Piece>();
		Piece.GetAllPiecesInRadius(((Component)this).transform.position, 25f, list);
		foreach (Piece item in list)
		{
			if ((Object)(object)item == (Object)null || (Object)(object)((Component)item).gameObject == (Object)(object)((Component)this).gameObject)
			{
				continue;
			}
			ZNetView component = ((Component)item).GetComponent<ZNetView>();
			if (!((Object)(object)component == (Object)null) && component.IsValid() && component.GetZDO().GetLong("Guilds_FurnOf", 0L) == num)
			{
				WearNTear component2 = ((Component)item).GetComponent<WearNTear>();
				if ((Object)(object)component2 != (Object)null)
				{
					component2.Remove(false);
					continue;
				}
				component.ClaimOwnership();
				ZNetScene.instance.Destroy(((Component)item).gameObject);
			}
		}
	}

	private bool Mine(out GuildInfo g)
	{
		g = GuildClient.Guild(GuildId);
		MemberInfo memberInfo = GuildClient.Member(GuildClient.LocalPid);
		if (g != null && memberInfo != null)
		{
			return memberInfo.GuildId == g.Id;
		}
		return false;
	}

	internal string HoverText()
	{
		//IL_01db: Unknown result type (might be due to invalid IL or missing references)
		GuildInfo guildInfo = GuildClient.Guild(GuildId);
		string text = Loc.T("b_" + Kind);
		if (guildInfo == null)
		{
			return Localization.instance.Localize(text + "\n<color=#9A9A9A>" + Loc.T("building_unowned") + "</color>");
		}
		text = "<color=#" + guildInfo.ColorHex + ">[" + guildInfo.Tag + "] " + guildInfo.Name + "</color>\n" + text;
		GuildInfo g;
		bool flag = Mine(out g);
		string text2 = "\n[<color=yellow><b>$KEY_Use</b></color>] ";
		switch (Kind)
		{
		case "armory":
			if (flag)
			{
				text = text + text2 + Loc.T("bu_armory");
			}
			break;
		case "warehouse":
			if (flag)
			{
				text = text + text2 + Loc.T("bu_warehouse");
			}
			break;
		case "longhouse":
			text = text + "\n" + Loc.T("bh_longhouse");
			if (flag)
			{
				text = text + text2 + Loc.T("bu_longhouse");
			}
			break;
		case "barracks":
			if (flag)
			{
				text = text + text2 + Loc.T(Territory.BarracksSpawnAt(guildInfo.Id, ((Component)this).transform.position) ? "bu_barracks_off" : "bu_barracks_on");
			}
			break;
		case "gate":
			text = text + "\n" + Loc.T("bh_gate_members");
			if (flag)
			{
				text = text + text2 + Loc.T("bu_guild");
			}
			break;
		case "signpost":
			if (!string.IsNullOrEmpty(guildInfo.Description))
			{
				text = text + "\n<color=#C9C2B0>" + guildInfo.Description + "</color>";
			}
			text = text + "\n" + Loc.T("bh_signpost", guildInfo.LeaderName, guildInfo.MemberCount, guildInfo.Level);
			break;
		default:
			if (flag)
			{
				text = text + text2 + Loc.T("bu_guild");
			}
			break;
		}
		return Localization.instance.Localize(text);
	}

	internal bool Use(Humanoid user)
	{
		//IL_00d7: 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)
		if (!Mine(out var g))
		{
			GuildInfo guildInfo = GuildClient.Guild(GuildId);
			if (Kind != "signpost")
			{
				((Character)user).Message((MessageType)2, (guildInfo != null) ? Loc.T("building_foreign", "[" + guildInfo.Tag + "] " + guildInfo.Name) : Loc.T("building_unowned"), 0, (Sprite)null, false);
			}
			return false;
		}
		switch (Kind)
		{
		case "armory":
			GuildUI.OpenVault(gear: true);
			return true;
		case "warehouse":
			GuildUI.OpenVault(gear: false);
			return true;
		case "barracks":
		{
			bool flag = !Territory.BarracksSpawnAt(g.Id, ((Component)this).transform.position);
			Territory.SetBarracksSpawn(g.Id, flag ? new Vector3?(((Component)this).transform.position) : ((Vector3?)null));
			((Character)user).Message((MessageType)2, Loc.T(flag ? "barracks_spawn_set" : "banner_spawn_cleared"), 0, (Sprite)null, false);
			return true;
		}
		case "signpost":
			return false;
		default:
			GuildUI.OpenOverview();
			return true;
		}
	}

	internal static GuildBuilding Nearest(long gid, string kind, Vector3 pos, float radius)
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		GuildBuilding result = null;
		float num = radius * radius;
		foreach (GuildBuilding instance in Instances)
		{
			if (!((Object)(object)instance == (Object)null) && !(instance.Kind != kind) && instance.GuildId == gid)
			{
				Vector3 val = ((Component)instance).transform.position - pos;
				float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
				if (sqrMagnitude <= num)
				{
					num = sqrMagnitude;
					result = instance;
				}
			}
		}
		return result;
	}

	public static void RPC_Ack(long sender, ZPackage pkg)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		ZDOID val = pkg.ReadZDOID();
		GameObject val2 = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.FindInstance(val) : null);
		GuildBuilding guildBuilding = (((Object)(object)val2 != (Object)null) ? val2.GetComponent<GuildBuilding>() : null);
		if ((Object)(object)guildBuilding != (Object)null)
		{
			guildBuilding.Acknowledge();
		}
	}
}
public class GuildBuildingPoint : MonoBehaviour, Hoverable, Interactable
{
	private GuildBuilding _b;

	private GuildBuilding B
	{
		get
		{
			if ((Object)(object)_b == (Object)null)
			{
				_b = ((Component)this).GetComponentInParent<GuildBuilding>();
			}
			return _b;
		}
	}

	public string GetHoverText()
	{
		if (!((Object)(object)B != (Object)null))
		{
			return "";
		}
		return B.HoverText();
	}

	public string GetHoverName()
	{
		if (!((Object)(object)B != (Object)null))
		{
			return "";
		}
		return Loc.T("b_" + B.Kind);
	}

	public float GetHoverOffset()
	{
		return 0f;
	}

	public bool Interact(Humanoid user, bool hold, bool alt)
	{
		if (!hold && (Object)(object)B != (Object)null)
		{
			return B.Use(user);
		}
		return false;
	}

	public bool UseItem(Humanoid user, ItemData item)
	{
		return false;
	}
}
internal static class BuildingPatches
{
	private static MethodInfo _matProps;

	private static FieldInfo _support;

	[HarmonyPatch(typeof(Piece), "DropResources")]
	[HarmonyPrefix]
	private static bool DropResources(Piece __instance)
	{
		try
		{
			return !Buildings.IsFurniture(((Component)__instance).GetComponent<ZNetView>());
		}
		catch
		{
			return true;
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(WearNTear), "UpdateSupport")]
	private static bool UpdateSupport(WearNTear __instance)
	{
		try
		{
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if (!Buildings.IsFurniture(component) && (Object)(object)((Component)__instance).GetComponent<GuildBuilding>() == (Object)null)
			{
				return true;
			}
			if (_matProps == null)
			{
				_matProps = AccessTools.Method(typeof(WearNTear), "GetMaterialProperties", (Type[])null, (Type[])null);
			}
			if (_support == null)
			{
				_support = AccessTools.Field(typeof(WearNTear), "m_support");
			}
			object[] array = new object[4] { 0f, 0f, 0f, 0f };
			_matProps.Invoke(__instance, array);
			_support.SetValue(__instance, (float)array[0]);
			return false;
		}
		catch
		{
			return true;
		}
	}

	[HarmonyPatch(typeof(Door), "Interact")]
	[HarmonyPrefix]
	private static bool DoorInteract(Door __instance, Humanoid __0, ref bool __result)
	{
		try
		{
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid() || !component.GetZDO().GetBool("Guilds_GateDoor", false))
			{
				return true;
			}
			long num = component.GetZDO().GetLong("Guilds_PartGid", 0L);
			MemberInfo memberInfo = GuildClient.Member(GuildClient.LocalPid);
			if (num == 0 || (memberInfo != null && memberInfo.GuildId == num))
			{
				return true;
			}
			GuildInfo guildInfo = GuildClient.Guild(num);
			if ((Object)(object)__0 != (Object)null)
			{
				((Character)__0).Message((MessageType)2, Loc.T("gate_members_only", (guildInfo != null) ? ("[" + guildInfo.Tag + "] " + guildInfo.Name) : "?"), 0, (Sprite)null, false);
			}
			__result = false;
			return false;
		}
		catch
		{
			return true;
		}
	}

	[HarmonyPrefix]
	[HarmonyPatch(typeof(WearNTear), "Remove")]
	private static void Remove(WearNTear __instance)
	{
		try
		{
			GuildBuilding component = ((Component)__instance).GetComponent<GuildBuilding>();
			if ((Object)(object)component != (Object)null)
			{
				component.RemoveFurniture();
			}
		}
		catch
		{
		}
	}

	[HarmonyPatch(typeof(WearNTear), "Destroy")]
	[HarmonyPrefix]
	private static void Destroy(WearNTear __instance)
	{
		try
		{
			GuildBuilding component = ((Component)__instance).GetComponent<GuildBuilding>();
			if ((Object)(object)component != (Object)null)
			{
				component.RemoveFurniture();
			}
		}
		catch
		{
		}
	}
}
internal class FurnitureSpot
{
	public string Prefab;

	public Vector3 Pos;

	public float Yaw;
}
internal class BuildingDef
{
	public string Id;

	public string BasePrefab;

	public float Health;

	public ConfigEntry<string> Limit;

	public ConfigEntry<string> CostOverride;

	public Action<KitBuilder> Layout;

	public readonly List<FurnitureSpot> Furniture = new List<FurnitureSpot>();

	public string CostText = "";

	public string PrefabName => "Guilds_B_" + Id;

	public int LimitAt(int level)
	{
		string text = ((Limit != null) ? Limit.Value : "1").Replace(" ", "");
		int result = 1;
		int result2 = 0;
		int result3 = 0;
		string[] array = text.Split('+');
		int.TryParse(array[0], out result);
		if (array.Length > 1)
		{
			string[] array2 = array[1].Split('/');
			int.TryParse(array2[0], out result2);
			if (array2.Length > 1)
			{
				int.TryParse(array2[1], out result3);
			}
		}
		return Math.Max(0, result + ((result3 > 0) ? (level / result3 * result2) : 0));
	}
}
internal static class VaultCat
{
	private static readonly HashSet<string> GearTypes = new HashSet<string>
	{
		"OneHandedWeapon", "TwoHandedWeapon", "TwoHandedWeaponLeft", "Bow", "Shield", "Helmet", "Chest", "Legs", "Shoulder", "Utility",
		"Tool", "Torch", "Ammo", "Trinket", "Hands", "Customization"
	};

	public static bool IsGear(string prefab)
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		ItemDrop val = ItemRecord.PrefabDrop(prefab);
		if ((Object)(object)val != (Object)null)
		{
			return GearTypes.Contains(((object)val.m_itemData.m_shared.m_itemType).ToString());
		}
		return false;
	}
}
internal static class Buildings
{
	public const string ZdoKey = "Guilds_Building";

	public const string PartGidKey = "Guilds_PartGid";

	public const string GateDoorKey = "Guilds_GateDoor";

	public const string FurnitureKey = "Guilds_Furniture";

	public const string FurnitureOfKey = "Guilds_FurnOf";

	public static readonly List<BuildingDef> Defs = new List<BuildingDef>();

	public static BuildingDef Find(string id)
	{
		foreach (BuildingDef def in Defs)
		{
			if (def.Id == id)
			{
				return def;
			}
		}
		return null;
	}

	public static void Bind(ConfigFile cfg)
	{
		Add(cfg, "longhouse", "woodwall", 3500f, "1", Layouts.Longhouse);
		Add(cfg, "armory", "woodwall", 2500f, "1", Layouts.Armory);
		Add(cfg, "warehouse", "woodwall", 2500f, "1", Layouts.Warehouse);
		Add(cfg, "barracks", "woodwall", 2500f, "1+1/5", Layouts.Barracks);
		Add(cfg, "smithy", "woodwall", 2500f, "1", Layouts.Smithy);
		Add(cfg, "kitchen", "woodwall", 2000f, "1", Layouts.Kitchen);
		Add(cfg, "tavern", "woodwall", 2000f, "1", Layouts.Tavern);
		Add(cfg, "workshop", "woodwall", 2000f, "1", Layouts.Workshop);
		Add(cfg, "bathhouse", "woodwall", 2000f, "1", Layouts.Bathhouse);
		Add(cfg, "trophy_hall", "stone_wall_4x2", 3000f, "1", Layouts.TrophyHall);
		Add(cfg, "guardhouse", "woodwall", 1500f, "2+1/4", Layouts.Guardhouse);
		Add(cfg, "training_ground", "woodwall", 1200f, "1", Layouts.TrainingGround);
		Add(cfg, "market_stall", "woodwall", 1000f, "2+1/5", Layouts.MarketStall);
		Add(cfg, "wall_stone", "stone_wall_4x2", 2500f, "16+4/1", Layouts.StoneWall);
		Add(cfg, "palisade", "woodwall", 1200f, "16+4/1", Layouts.Palisade);
		Add(cfg, "rampart_stairs", "stone_wall_4x2", 1500f, "4+1/3", Layouts.RampartStairs);
		Add(cfg, "tower_stone", "stone_wall_4x2", 4000f, "2+1/4", Layouts.StoneTower);
		Add(cfg, "watchtower", "woodwall", 1500f, "2+1/4", Layouts.Watchtower);
		Add(cfg, "gate", "stone_wall_4x2", 3000f, "2+1/5", Layouts.Gate);
		Add(cfg, "lamppost", "woodwall", 400f, "8+2/2", Layouts.Lamppost);
		Add(cfg, "well", "stone_wall_4x2", 1500f, "2", Layouts.Well);
		Add(cfg, "signpost", "woodwall", 300f, "2", Layouts.Signpost);
	}

	private static void Add(ConfigFile cfg, string id, string basePrefab, float hp, string limit, Action<KitBuilder> layout)
	{
		BuildingDef buildingDef = new BuildingDef();
		buildingDef.Id = id;
		buildingDef.BasePrefab = basePrefab;
		buildingDef.Health = hp;
		buildingDef.Layout = layout;
		buildingDef.Limit = cfg.Bind<string>("8 - Buildings", id + ".Limit", limit, "How many of this building a guild may have: \"B\" or \"B+A/S\" = B, plus A for every S guild levels.");
		buildingDef.CostOverride = cfg.Bind<string>("8 - Buildings", id + ".CostOverride", "", "Empty = the cost is the sum of the vanilla pieces the building is made of (furniture included). Or your own cost: Prefab:amount, comma separated. Restart needed.");
		Defs.Add(buildingDef);
	}

	public static void Register()
	{
		PrefabManager.OnVanillaPrefabsAvailable += Create;
	}

	private static void Create()
	{
		PrefabManager.OnVanillaPrefabsAvailable -= Create;
		foreach (BuildingDef def in Defs)
		{
			try
			{
				CreateOne(def);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Guild building " + def.Id + " failed: " + ex));
			}
		}
	}

	private static void RenderIcon(CustomPiece cp)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Expected O, but got Unknown
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			RenderRequest val = new RenderRequest(cp.PiecePrefab);
			val.Width = 128;
			val.Height = 128;
			val.Rotation = RenderManager.IsometricRotation;
			val.DistanceMultiplier = 1f;
			Sprite val2 = RenderManager.Instance.Render(val);
			if ((Object)(object)val2 != (Object)null && (Object)(object)cp.Piece != (Object)null)
			{
				cp.Piece.m_icon = val2;
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Icon render failed for " + ((Object)cp.PiecePrefab).name + ": " + ex.Message));
		}
	}

	private static void SavePreviews(CustomPiece cp, string id)
	{
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Expected O, but got Unknown
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		if (!Plugin.RenderPreviews.Value)
		{
			return;
		}
		try
		{
			string text = Path.Combine(Paths.ConfigPath, "Guilds/previews");
			Directory.CreateDirectory(text);
			float[,] array = new float[4, 2]
			{
				{ 25f, 35f },
				{ 25f, 215f },
				{ 70f, 0f },
				{ 10f, 90f }
			};
			for (int i = 0; i < 4; i++)
			{
				RenderRequest val = new RenderRequest(cp.PiecePrefab);
				val.Width = 768;
				val.Height = 768;
				val.Rotation = Quaternion.Euler(array[i, 0], array[i, 1], 0f);
				val.DistanceMultiplier = 1.05f;
				Sprite val2 = RenderManager.Instance.Render(val);
				if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2.texture == (Object)null))
				{
					File.WriteAllBytes(Path.Combine(text, id + "_" + i + ".png"), ImageConversion.EncodeToPNG(val2.texture));
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Preview render failed for " + id + ": " + ex.Message));
		}
	}

	private static void CreateOne(BuildingDef d)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Expected O, but got Unknown
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Expected O, but got Unknown
		//IL_019d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a4: Expected O, but got Unknown
		PieceConfig val = new PieceConfig();
		val.Name = Loc.T("b_" + d.Id);
		val.Description = Loc.T("bd_" + d.Id);
		val.PieceTable = "Hammer";
		val.Category = "Guild";
		CustomPiece val2 = new CustomPiece(d.PrefabName, d.BasePrefab, val);
		GameObject piecePrefab = val2.PiecePrefab;
		if ((Object)(object)piecePrefab == (Object)null)
		{
			Plugin.Log.LogError((object)("Base prefab " + d.BasePrefab + " missing for " + d.Id));
			return;
		}
		int layer = piecePrefab.layer;
		Collider[] componentsInChildren = piecePrefab.GetComponentsInChildren<Collider>(true);
		int num = 0;
		if (num < componentsInChildren.Length)
		{
			Collider val3 = componentsInChildren[num];
			layer = ((Component)val3).gameObject.layer;
		}
		Renderer[] componentsInChildren2 = piecePrefab.GetComponentsInChildren<Renderer>(true);
		foreach (Renderer val4 in componentsInChildren2)
		{
			Object.DestroyImmediate((Object)(object)val4);
		}
		MeshFilter[] componentsInChildren3 = piecePrefab.GetComponentsInChildren<MeshFilter>(true);
		foreach (MeshFilter val5 in componentsInChildren3)
		{
			Object.DestroyImmediate((Object)(object)val5);
		}
		Collider[] componentsInChildren4 = piecePrefab.GetComponentsInChildren<Collider>(true);
		foreach (Collider val6 in componentsInChildren4)
		{
			Object.DestroyImmediate((Object)(object)val6);
		}
		Transform[] componentsInChildren5 = piecePrefab.GetComponentsInChildren<Transform>(true);
		foreach (Transform val7 in componentsInChildren5)
		{
			if ((Object)(object)val7 != (Object)(object)piecePrefab.transform && ((Component)val7).CompareTag("snappoint"))
			{
				Object.DestroyImmediate((Object)(object)((Component)val7).gameObject);
			}
		}
		GameObject val8 = new GameObject("Model");
		val8.layer = layer;
		val8.transform.SetParent(piecePrefab.transform, false);
		KitBuilder kitBuilder = new KitBuilder(piecePrefab.transform, val8.transform, layer);
		d.Layout(kitBuilder);
		kitBuilder.Finish();
		if (kitBuilder.Missing.Count > 0)
		{
			Plugin.Log.LogWarning((object)("Guild building " + d.Id + ": missing vanilla parts " + string.Join(", ", kitBuilder.Missing.ToArray())));
		}
		d.Furniture.Clear();
		d.Furniture.AddRange(kitBuilder.Spots);
		Piece component = piecePrefab.GetComponent<Piece>();
		if ((Object)(object)component != (Object)null)
		{
			component.m_notOnFloor = false;
			component.m_inCeilingOnly = false;
			component.m_groundPiece = false;
			component.m_groundOnly = false;
			component.m_cultivatedGroundOnly = false;
			component.m_waterPiece = false;
			component.m_noInWater = true;
			component.m_notOnWood = false;
			component.m_notOnTiltingSurface = false;
			component.m_clipGround = true;
			component.m_clipEverything = true;
			component.m_noClipping = false;
			component.m_onlyInTeleportArea = false;
			component.m_allowRotatedOverlap = true;
			component.m_resources = Costs(d, kitBuilder);
			component.m_craftingStation = null;
		}
		WearNTear component2 = piecePrefab.GetComponent<WearNTear>();
		if ((Object)(object)component2 != (Object)null)
		{
			component2.m_health = d.Health;
			component2.m_noRoofWear = true;
			component2.m_noSupportWear = true;
			component2.m_supports = true;
		}
		GuildBuilding guildBuilding = piecePrefab.AddComponent<GuildBuilding>();
		guildBuilding.Kind = d.Id;
		Transform[] componentsInChildren6 = piecePrefab.GetComponentsInChildren<Transform>(true);
		foreach (Transform val9 in componentsInChildren6)
		{
			if (((Object)val9).name == "Access")
			{
				((Component)val9).gameObject.AddComponent<GuildBuildingPoint>();
			}
		}
		PieceManager.Instance.AddPiece(val2);
		RenderIcon(val2);
		SavePreviews(val2, d.Id);
		Plugin.Log.LogInfo((object)("Guild building " + d.Id + ": cost " + d.CostText + ", pieces " + d.Furniture.Count));
	}

	private static Requirement[] Costs(BuildingDef d, KitBuilder kb)
	{
		//IL_0141: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: Expected O, but got Unknown
		Dictionary<string, float> dictionary = new Dictionary<string, float>();
		string text = d.CostOverride.Value.Trim();
		if (text.Length > 0)
		{
			string[] array = text.Split(',');
			foreach (string text2 in array)
			{
				string[] array2 = text2.Split(':');
				if (array2.Length == 2 && int.TryParse(array2[1].Trim(), out var result) && result > 0)
				{
					dictionary[array2[0].Trim()] = result;
				}
			}
		}
		else
		{
			foreach (KeyValuePair<string, float> item in kb.Cost)
			{
				dictionary[item.Key] = item.Value;
			}
		}
		List<Requirement> list = new List<Requirement>();
		List<string> list2 = new List<string>();
		foreach (KeyValuePair<string, float> item2 in dictionary)
		{
			GameObject prefab = PrefabManager.Instance.GetPrefab(item2.Key);
			ItemDrop val = (((Object)(object)prefab != (Object)null) ? prefab.GetComponent<ItemDrop>() : null);
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogWarning((object)("Unknown cost item " + item2.Key + " for " + d.Id));
				continue;
			}
			Requirement val2 = new Requirement();
			val2.m_resItem = val;
			val2.m_amount = Mathf.Max(1, Mathf.CeilToInt(item2.Value - 0.05f));
			val2.m_recover = true;
			list.Add(val2);
			list2.Add(item2.Key + ":" + val2.m_amount);
		}
		list.Sort((Requirement a, Requirement b) => b.m_amount.CompareTo(a.m_amount));
		d.CostText = string.Join(",", list2.ToArray());
		return list.ToArray();
	}

	public static bool IsFurniture(ZNetView nv)
	{
		if ((Object)(object)nv != (Object)null && nv.IsValid())
		{
			return nv.GetZDO().GetBool("Guilds_Furniture", false);
		}
		return false;
	}
}
internal class KitBuilder
{
	public readonly List<string> Missing = new List<string>();

	public readonly List<FurnitureSpot> Spots = new List<FurnitureSpot>();

	public readonly Dictionary<string, float> Cost = new Dictionary<string, float>();

	public Transform Root;

	public Transform Target;

	private readonly Transform _model;

	private Transform _preview;

	private readonly int _layer;

	private readonly GameObject _holder;

	private Transform Preview
	{
		get
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			if ((Object)(object)_preview == (Object)null)
			{
				GameObject val = new GameObject("FurniturePreview");
				val.layer = _layer;
				val.transform.SetParent(_model, false);
				_preview = val.transform;
			}
			return _preview;
		}
	}

	public KitBuilder(Transform root, Transform model, int layer)
	{
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Expected O, but got Unknown
		Root = root;
		Target = model;
		_model = model;
		_layer = layer;
		_holder = new GameObject("Guilds_KitHolder");
		_holder.SetActive(false);
	}

	public void Finish()
	{
		Object.DestroyImmediate((Object)(object)_holder);
	}

	private Transform Group(string name)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Expected O, but got Unknown
		GameObject val = new GameObject(name);
		val.layer = _layer;
		val.transform.SetParent(Target, false);
		return val.transform;
	}

	private GameObject Clone(string prefab, out GameObject src)
	{
		//IL_005a: 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)
		src = PrefabManager.Instance.GetPrefab(prefab);
		if ((Object)(object)src == (Object)null)
		{
			if (!Missing.Contains(prefab))
			{
				Missing.Add(prefab);
			}
			return null;
		}
		GameObject val = Object.Instantiate<GameObject>(src, _holder.transform, false);
		((Object)val).name = prefab;
		Strip(val);
		val.transform.localPosition = Vector3.zero;
		val.transform.localRotation = Quaternion.identity;
		return val;
	}

	private void AddCost(GameObject src)
	{
		Piece val = (((Object)(object)src != (Object)null) ? src.GetComponent<Piece>() : null);
		if ((Object)(object)val == (Object)null || val.m_resources == null)
		{
			return;
		}
		Requirement[] resources = val.m_resources;
		foreach (Requirement val2 in resources)
		{
			if (val2 != null && !((Object)(object)val2.m_resItem == (Object)null) && val2.m_amount > 0)
			{
				string name = ((Object)val2.m_resItem).name;
				Cost.TryGetValue(name, out var value);
				Cost[name] = value + (float)val2.m_amount;
			}
		}
	}

	public void Put(string prefab, Vector3 pivot, float yaw)
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: 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)
		GameObject src;
		GameObject val = Clone(prefab, out src);
		if (!((Object)(object)val == (Object)null))
		{
			Collider[] componentsInChildren = val.GetComponentsInChildren<Collider>(true);
			foreach (Collider val2 in componentsInChildren)
			{
				Object.DestroyImmediate((Object)(object)val2);
			}
			val.transform.localRotation = Quaternion.Euler(0f, yaw, 0f);
			val.transform.localPosition = pivot;
			val.transform.SetParent(Preview, false);
			AddCost(src);
			FurnitureSpot furnitureSpot = new FurnitureSpot();
			furnitureSpot.Prefab = prefab;
			furnitureSpot.Pos = pivot;
			furnitureSpot.Yaw = yaw;
			Spots.Add(furnitureSpot);
		}
	}

	public void Furnish(string prefab, Vector3 ground, float yaw)
	{
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0062: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		GameObject prefab2 = PrefabManager.Instance.GetPrefab(prefab);
		if ((Object)(object)prefab2 == (Object)null)
		{
			if (!Missing.Contains(prefab))
			{
				Missing.Add(prefab);
			}
		}
		else
		{
			GameObject src;
			GameObject val = Clone(prefab, out src);
			Bounds val2 = LocalBounds(val.transform, _holder.transform);
			Object.DestroyImmediate((Object)(object)val);
			Vector3 val3 = Quaternion.Euler(0f, yaw, 0f) * ((Bounds)(ref val2)).center;
			Put(prefab, new Vector3(ground.x - val3.x, ground.y - ((Bounds)(ref val2)).min.y, ground.z - val3.z), yaw);
		}
	}

	public void Access(Vector3 center, float yaw)
	{
		//IL_006b: 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_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: 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_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		Transform val = Group("Access");
		GameObject src;
		GameObject val2 = Clone("sign_notext", out src);
		if ((Object)(object)val2 != (Object)null)
		{
			val2.transform.localRotation = Quaternion.Euler(0f, yaw, 0f);
			val2.transform.localPosition = center;
			val2.transform.SetParent(val, false);
			AddCost(src);
		}
		BoxCollider val3 = ((Component)val).gameObject.AddComponent<BoxCollider>();
		val3.center = center;
		Vector3 val4 = Quaternion.Euler(0f, yaw, 0f) * new Vector3(1.05f, 0.55f, 0.16f);
		val3.size = new Vector3(Mathf.Abs(val4.x), Mathf.Abs(val4.y), Mathf.Abs(val4.z));
	}

	public void Snap(Vector3 pos)
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Expected O, but got Unknown
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		GameObject val = new GameObject("_snappoint");
		val.tag = "snappoint";
		val.layer = _layer;
		val.transform.SetParent(Root, false);
		val.transform.localPosition = pos;
		val.SetActive(false);
	}

	private static bool Keep(Component c)
	{
		if (!(c is Transform) && !(c is MeshFilter) && !(c is MeshRenderer) && !(c is SkinnedMeshRenderer) && !(c is Collider) && !(c is LODGroup) && !(c is ParticleSystem))
		{
			return c is ParticleSystemRenderer;
		}
		return true;
	}

	private static void Strip(GameObject inst)
	{
		WearNTear component = inst.GetComponent<WearNTear>();
		if ((Object)(object)component != (Object)null)
		{
			if ((Object)(object)component.m_worn != (Object)null && (Object)(object)component.m_worn != (Object)(object)component.m_new)
			{
				Object.DestroyImmediate((Object)(object)component.m_worn);
			}
			if ((Object)(object)component.m_broken != (Object)null && (Object)(object)component.m_broken != (Object)(object)component.m_new)
			{
				Object.DestroyImmediate((Object)(object)component.m_broken);
			}
		}
		List<GameObject> list = new List<GameObject>();
		Transform[] componentsInChildren = inst.GetComponentsInChildren<Transform>(true);
		foreach (Transform val in componentsInChildren)
		{
			if ((Object)(object)val != (Object)(object)inst.transform && ((Component)val).CompareTag("snappoint"))
			{
				list.Add(((Component)val).gameObject);
			}
		}
		foreach (GameObject item in list)
		{
			Object.DestroyImmediate((Object)(object)item);
		}
		for (int j = 0; j < 4; j++)
		{
			bool flag = false;
			Component[] componentsInChildren2 = inst.GetComponentsInChildren<Component>(true);
			foreach (Component val2 in componentsInChildren2)
			{
				if (!((Object)(object)val2 == (Object)null) && !Keep(val2) && (j != 0 || (val2 is MonoBehaviour && !(val2 is ZNetView))) && (j != 1 || val2 is MonoBehaviour))
				{
					flag = true;
					try
					{
						Object.DestroyImmediate((Object)(object)val2);
					}
					catch
					{
					}
				}
			}
			if (!flag && j >= 2)
			{
				break;
			}
		}
		Collider[] componentsInChildren3 = inst.GetComponentsInChildren<Collider>(true);
		foreach (Collider val3 in componentsInChildren3)
		{
			if (val3.isTrigger)
			{
				Object.DestroyImmediate((Object)(object)val3);
			}
		}
	}

	private static Bounds LocalBounds(Transform t, Transform space)
	{
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0165: Unknown result type (might be due to invalid IL or missing references)
		//IL_0156: Unknown result type (might be due to invalid IL or missing references)
		//IL_015b: 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_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: 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_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0100: Unknown result type (might be due to invalid IL or missing references)
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: 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_010c: Unknown result type (might be due to invalid IL or missing references)
		//IL_010e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_0118: Unknown result type (might be due to invalid IL or missing references)
		bool flag = false;
		Bounds result = default(Bounds);
		((Bounds)(ref result))..ctor(Vector3.zero, Vector3.zero);
		Matrix4x4 worldToLocalMatrix = space.worldToLocalMatrix;
		MeshFilter[] componentsInChildren = ((Component)t).GetComponentsInChildren<MeshFilter>(true);
		foreach (MeshFilter val in componentsInChildren)
		{
			if ((Object)(object)val.sharedMesh == (Object)null)
			{
				continue;
			}
			MeshRenderer component = ((Component)val).GetComponent<MeshRenderer>();
			if ((Object)(object)component != (Object)null && (Object)(object)((Renderer)component).sharedMaterial != (Object)null && (Object)(object)((Renderer)component).sharedMaterial.shader != (Object)null && ((Object)((Renderer)component).sharedMaterial.shader).name.IndexOf("Snow", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				continue;
			}
			Matrix4x4 val2 = worldToLocalMatrix * ((Component)val).transform.localToWorldMatrix;
			Bounds bounds = val.sharedMesh.bounds;
			for (int j = 0; j < 8; j++)
			{
				Vector3 val3 = ((Bounds)(ref bounds)).center + Vector3.Scale(((Bounds)(ref bounds)).extents, new Vector3((float)(((j & 1) != 0) ? 1 : (-1)), (float)(((j & 2) != 0) ? 1 : (-1)), (float)(((j & 4) != 0) ? 1 : (-1))));
				Vector3 val4 = ((Matrix4x4)(ref val2)).MultiplyPoint3x4(val3);
				if (!flag)
				{
					result = new Bounds(val4, Vector3.zero);
					flag = true;
				}
				else
				{
					((Bounds)(ref result)).Encapsulate(val4);
				}
			}
		}
		if (!flag)
		{
			((Bounds)(ref result))..ctor(new Vector3(0f, 0.5f, 0f), Vector3.one);
		}
		return result;
	}
}
[Flags]
public enum Perm
{
	None = 0,
	Invite = 1,
	Kick = 2,
	Promote = 4,
	EditInfo = 8,
	ManageRanks = 0x10,
	VaultDeposit = 0x20,
	VaultItems = 0x40,
	VaultCoins = 0x80,
	ViewLog = 0x100,
	WardAccess = 0x200,
	BindWard = 0x400,
	Chat = 0x800,
	Banner = 0x1000,
	MapPins = 0x2000,
	Buildings = 0x4000,
	Diplomacy = 0x8000,
	All = 0xFFFF
}
public class ItemRecord
{
	private const int Version = 1;

	public string Prefab = "";

	public int Stack = 1;

	public int Quality = 1;

	public int Variant;

	public float Durability;

	public long CrafterID;

	public string CrafterName = "";

	public int WorldLevel;

	public Dictionary<string, string> CustomData = new Dictionary<string, string>();

	public void Write(ZPackage pkg)
	{
		pkg.Write(1);
		pkg.Write(Prefab);
		pkg.Write(Stack);
		pkg.Write(Quality);
		pkg.Write(Variant);
		pkg.Write(Durability);
		pkg.Write(CrafterID);
		pkg.Write(CrafterName ?? "");
		pkg.Write(WorldLevel);
		pkg.Write(CustomData.Count);
		foreach (KeyValuePair<string, string> customDatum in CustomData)
		{
			pkg.Write(customDatum.Key);
			pkg.Write(customDatum.Value ?? "");
		}
	}

	public static ItemRecord Read(ZPackage pkg)
	{
		ItemRecord itemRecord = new ItemRecord();
		pkg.ReadInt();
		itemRecord.Prefab = pkg.ReadString();
		itemRecord.Stack = pkg.ReadInt();
		itemRecord.Quality = pkg.ReadInt();
		itemRecord.Variant = pkg.ReadInt();
		itemRecord.Durability = pkg.ReadSingle();
		itemRecord.CrafterID = pkg.ReadLong();
		itemRecord.CrafterName = pkg.ReadString();
		itemRecord.WorldLevel = pkg.ReadInt();
		int num = pkg.ReadInt();
		for (int i = 0; i < num; i++)
		{
			string key = pkg.ReadString();
			itemRecord.CustomData[key] = pkg.ReadString();
		}
		return itemRecord;
	}

	public ItemRecord Clone(int stack)
	{
		ItemRecord itemRecord = (ItemRecord)MemberwiseClone();
		itemRecord.CustomData = new Dictionary<string, string>(CustomData);
		itemRecord.Stack = stack;
		return itemRecord;
	}

	public bool SameKind(ItemRecord o)
	{
		if (o == null || o.Prefab != Prefab || o.Quality != Quality || o.Variant != Variant)
		{
			return false;
		}
		if (o.CrafterID != CrafterID || o.WorldLevel != WorldLevel)
		{
			return false;
		}
		if (Math.Abs(o.Durability - Durability) > 0.01f)
		{
			return false;
		}
		if (CustomData.Count == 0)
		{
			return o.CustomData.Count == 0;
		}
		return false;
	}

	public static ItemRecord FromItem(ItemData item, int amount)
	{
		ItemRecord itemRecord = new ItemRecord();
		itemRecord.Prefab = (((Object)(object)item.m_dropPrefab != (Object)null) ? ((Object)item.m_dropPrefab).name : "");
		itemRecord.Stack = amount;
		itemRecord.Quality = item.m_quality;
		itemRecord.Variant = item.m_variant;
		itemRecord.Durability = item.m_durability;
		itemRecord.CrafterID = item.m_crafterID;
		itemRecord.CrafterName = item.m_crafterName ?? "";
		itemRecord.WorldLevel = item.m_worldLevel;
		if (item.m_customData != null)
		{
			itemRecord.CustomData = new Dictionary<string, string>(item.m_customData);
		}
		return itemRecord;
	}

	public static ItemDrop PrefabDrop(string prefab)
	{
		if ((Object)(object)ObjectDB.instance == (Object)null || string.IsNullOrEmpty(prefab))
		{
			return null;
		}
		GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(prefab);
		if (!((Object)(object)itemPrefab != (Object)null))
		{
			return null;
		}
		return itemPrefab.GetComponent<ItemDrop>();
	}

	public ItemData ToItemData()
	{
		ItemDrop val = PrefabDrop(Prefab);
		if ((Object)(object)val == (Object)null)
		{
			return null;
		}
		ItemData val2 = val.m_itemData.Clone();
		val2.m_dropPrefab = ((Component)val).gameObject;
		val2.m_stack = Stack;
		val2.m_quality = Quality;
		val2.m_variant = Variant;
		val2.m_durability = Durability;
		val2.m_crafterID = CrafterID;
		val2.m_crafterName = CrafterName;
		val2.m_worldLevel = WorldLevel;
		val2.m_customData = new Dictionary<string, string>(CustomData);
		val2.m_equipped = false;
		return val2;
	}
}
public class Rank
{
	public string Name = "";

	public Perm Perms;

	public int DailyCoinLimit;

	public Rank()
	{
	}

	public Rank(string name, Perm perms, int limit)
	{
		Name = name;
		Perms = perms;
		DailyCoinLimit = limit;
	}

	public void Write(ZPackage pkg)
	{
		pkg.Write(Name ?? "");
		pkg.Write((int)Perms);
		pkg.Write(DailyCoinLimit);
	}

	public static Rank Read(ZPackage pkg)
	{
		Rank rank = new Rank();
		rank.Name = pkg.ReadString();
		rank.Perms = (Perm)pkg.ReadInt();
		rank.DailyCoinLimit = pkg.ReadInt();
		return rank;
	}
}
public class Member
{
	public long Pid;

	public string Name = "";

	public int Rank;

	public long JoinedTicks;

	public long LastSeenTicks;

	public long WithdrawnToday;

	public int WithdrawDay;

	public long Contribution;

	public void Write(ZPackage pkg)
	{
		pkg.Write(Pid);
		pkg.Write(Name ?? "");
		pkg.Write(Rank);
		pkg.Write(JoinedTicks);
		pkg.Write(LastSeenTicks);
		pkg.Write(WithdrawnToday);
		pkg.Write(WithdrawDay);
		pkg.Write(Contribution);
	}

	public static Member Read(ZPackage pkg, int version)
	{
		Member member = new Member();
		member.Pid = pkg.ReadLong();
		member.Name = pkg.ReadString();
		member.Rank = pkg.ReadInt();
		member.JoinedTicks = pkg.ReadLong();
		member.LastSeenTicks = pkg.ReadLong();
		member.WithdrawnToday = pkg.ReadLong();
		member.WithdrawDay = pkg.ReadInt();
		if (version >= 2)
		{
			member.Contribution = pkg.ReadLong();
		}
		return member;
	}
}
public class Invite
{
	public long Id;

	public long GuildId;

	public long TargetPid;

	public string TargetName = "";

	public long ActorPid;

	public string ActorName = "";

	public long Ticks;

	public bool IsApplication;

	public void Write(ZPackage pkg)
	{
		pkg.Write(Id);
		pkg.Write(GuildId);
		pkg.Write(TargetPid);
		pkg.Write(TargetName ?? "");
		pkg.Write(ActorPid);
		pkg.Write(ActorName ?? "");
		pkg.Write(Ticks);
		pkg.Write(IsApplication);
	}

	public static Invite Read(ZPackage pkg)
	{
		Invite invite = new Invite();
		invite.Id = pkg.ReadLong();
		invite.GuildId = pkg.ReadLong();
		invite.TargetPid = pkg.ReadLong();
		invite.TargetName = pkg.ReadString();
		invite.ActorPid = pkg.ReadLong();
		invite.ActorName = pkg.ReadString();
		invite.Ticks = pkg.ReadLong();
		invite.IsApplication = pkg.ReadBool();
		return invite;
	}
}
public enum LogKind
{
	Created,
	Joined,
	Left,
	Kicked,
	Promoted,
	Demoted,
	Leader,
	Info,
	Ranks,
	ItemIn,
	ItemOut,
	CoinsIn,
	CoinsOut,
	Invited,
	Applied,
	Declined,
	Knowledge,
	Renamed,
	LevelUp,
	Upgrade,
	Achievement,
	Donation,
	BannerPlaced,
	BannerLost,
	BossFirst,
	Building,
	Diplomacy
}
public class GuildPin
{
	public long Id;

	public float X;

	public float Z;

	public int Type;

	public string Text = "";

	public string Author = "";

	public void Write(ZPackage pkg)
	{
		pkg.Write(Id);
		pkg.Write(X);
		pkg.Write(Z);
		pkg.Write(Type);
		pkg.Write(Text ?? "");
		pkg.Write(Author ?? "");
	}

	public static GuildPin Read(ZPackage pkg)
	{
		GuildPin guildPin = new GuildPin();
		guildPin.Id = pkg.ReadLong();
		guildPin.X = pkg.ReadSingle();
		guildPin.Z = pkg.ReadSingle();
		guildPin.Type = pkg.ReadInt();
		guildPin.Text = pkg.ReadString();
		guildPin.Author = pkg.ReadString();
		return guildPin;
	}
}
public class LogEntry
{
	public LogKind Kind;

	public long Ticks;

	public string Actor = "";

	public string Target = "";

	public string Prefab = "";

	public long Amount;

	public string Text = "";

	public void Write(ZPackage pkg)
	{
		pkg.Write((int)Kind);
		pkg.Write(Ticks);
		pkg.Write(Actor ?? "");
		pkg.Write(Target ?? "");
		pkg.Write(Prefab ?? "");
		pkg.Write(Amount);
		pkg.Write(Text ?? "");
	}

	public static LogEntry Read(ZPackage pkg)
	{
		LogEntry logEntry = new LogEntry();
		logEntry.Kind = (LogKind)pkg.ReadInt();
		logEntry.Ticks = pkg.ReadLong();
		logEntry.Actor = pkg.ReadString();
		logEntry.Target = pkg.ReadString();
		logEntry.Prefab = pkg.ReadString();
		logEntry.Amount = pkg.ReadLong();
		logEntry.Text = pkg.ReadString();
		return logEntry;
	}
}
public class Guild
{
	public const int MaxLog = 200;

	public long Id;

	public string Name = "";

	public string Tag = "";

	public string Color = "FFD27A";

	public string Emblem = "";

	public string Motd = "";

	public string Description = "";

	public long CreatedTicks;

	public long Coins;

	public List<Rank> Ranks = new List<Rank>();

	public List<Member> Members = new List<Member>();

	public List<ItemRecord> Vault = new List<ItemRecord>();

	public List<LogEntry> Log = new List<LogEntry>();

	public HashSet<string> Keys = new HashSet<string>();

	public long Xp;

	public int SpentPoints;

	public Dictionary<string, int> Upgrades = new Dictionary<string, int>();

	public bool HasBanner;

	public ZDOID BannerId = ZDOID.None;

	public Vector3 BannerPos;

	public long BannerTicks;

	public Dictionary<string, double> Stats = new Dictionary<string, double>();

	public Dictionary<string, int> Achievements = new Dictionary<string, int>();

	public HashSet<string> BossFirsts = new HashSet<string>();

	public List<GuildPin> Pins = new List<GuildPin>();

	public long NextPinId = 1L;

	public Dictionary<long, Relation> Relations = new Dictionary<long, Relation>();

	public Dictionary<long, Proposal> Proposals = new Dictionary<long, Proposal>();

	public Dictionary<long, long> RelationSince = new Dictionary<long, long>();

	public Member Leader
	{
		get
		{
			foreach (Member member in Members)
			{
				if (member.Rank == 0)
				{
					return member;
				}
			}
			return null;
		}
	}

	public Relation RelationWith(long gid)
	{
		if (!Relations.TryGetValue(gid, out var value))
		{
			return Relation.Neutral;
		}
		return value;
	}

	public int Tier(string upgrade)
	{
		if (!Upgrades.TryGetValue(upgrade, out var value))
		{
			return 0;
		}
		return value;
	}

	public Member Find(long pid)
	{
		foreach (Member member in Members)
		{
			if (member.Pid == pid)
			{
				return member;
			}
		}
		return null;
	}

	public Perm PermsOf(Member m)
	{
		if (m == null)
		{
			return Perm.None;
		}
		if (m.Rank == 0)
		{
			return Perm.All;
		}
		if (m.Rank >= Ranks.Count)
		{
			return Perm.None;
		}
		return Ranks[m.Rank].Perms;
	}

	public bool Can(Member m, Perm p)
	{
		return (PermsOf(m) & p) == p;
	}

	public void AddLog(LogKind kind, string actor, string target, string prefab, long amount, string text)
	{
		LogEntry logEntry = new LogEntry();
		logEntry.Kind = kind;
		logEntry.Ticks = DateTime.UtcNow.Ticks;
		logEntry.Actor = actor ?? "";
		logEntry.Target = target ?? "";
		logEntry.Prefab = prefab ?? "";
		logEntry.Amount = amount;
		logEntry.Text = text ?? "";
		Log.Insert(0, logEntry);
		if (Log.Count > 200)
		{
			Log.RemoveRange(200, Log.Count - 200);
		}
	}

	public void Write(ZPackage pkg)
	{
		//IL_0258: Unknown result type (might be due to invalid IL or missing references)
		//IL_0264: Unknown result type (might be due to invalid IL or missing references)
		pkg.Write(Id);
		pkg.Write(Name);
		pkg.Write(Tag);
		pkg.Write(Color);
		pkg.Write(Emblem);
		pkg.Write(Motd);
		pkg.Write(Description);
		pkg.Write(CreatedTicks);
		pkg.Write(Coins);
		pkg.Write(Ranks.Count);
		foreach (Rank rank in Ranks)
		{
			rank.Write(pkg);
		}
		pkg.Write(Members.Count);
		foreach (Member member in Members)
		{
			member.Write(pkg);
		}
		pkg.Write(Vault.Count);
		foreach (ItemRecord item in Vault)
		{
			item.Write(pkg);
		}
		pkg.Write(Log.Count);
		foreach (LogEntry item2 in Log)
		{
			item2.Write(pkg);
		}
		pkg.Write(Keys.Count);
		foreach (string key in Keys)
		{
			pkg.Write(key);
		}
		pkg.Write(Xp);
		pkg.Write(SpentPoints);
		pkg.Write(Upgrades.Count);
		foreach (KeyValuePair<string, int> upgrade in Upgrades)
		{
			pkg.Write(upgrade.Key);
			pkg.Write(upgrade.Value);
		}
		pkg.Write(HasBanner);
		pkg.Write(BannerId);
		pkg.Write(BannerPos);
		pkg.Write(BannerTicks);
		pkg.Write(Stats.Count);
		foreach (KeyValuePair<string, double> stat in Stats)
		{
			pkg.Write(stat.Key);
			pkg.Write(stat.Value);
		}
		pkg.Write(Achievements.Count);
		foreach (KeyValuePair<string, int> achievement in Achievements)
		{
			pkg.Write(achievement.Key);
			pkg.Write(achievement.Value);
		}
		pkg.Write(BossFirsts.Count);
		foreach (string bossFirst in BossFirsts)
		{
			pkg.Write(bossFirst);
		}
		pkg.Write(Pins.Count);
		foreach (GuildPin pin in Pins)
		{
			pin.Write(pkg);
		}
		pkg.Write(NextPinId);
		pkg.Write(Relations.Count);
		foreach (KeyValuePair<long, Relation> relation in Relations)
		{
			RelationSince.TryGetValue(relation.Key, out var value);
			pkg.Write(relation.Key);
			pkg.Write((int)relation.Value);
			pkg.Write(value);
		}
		pkg.Write(Proposals.Count);
		foreach (KeyValuePair<long, Proposal> proposal in Proposals)
		{
			pkg.Write(proposal.Key);
			pkg.Write((int)proposal.Value);
		}
	}

	public static Guild Read(ZPackage pkg, int version)
	{
		//IL_021e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0223: Unknown result type (might be due to invalid IL or missing references)
		//IL_022a: Unknown result type (might be due to invalid IL or missing references)
		//IL_022f: Unknown result type (might be due to invalid IL or missing references)
		Guild guild = new Guild();
		guild.Id = pkg.ReadLong();
		guild.Name = pkg.ReadString();
		guild.Tag = pkg.ReadString(