Decompiled source of DivineWar v0.1.61

BepInEx\plugins\DivineWar\DivineWar.dll

Decompiled an hour ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using DG.Tweening;
using HarmonyLib;
using I2.Loc;
using I2.Loc.SimpleJSON;
using Malee;
using Microsoft.CodeAnalysis;
using ShinyShoe;
using ShinyShoe.Loading;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.TextCore;
using UnityEngine.UI;

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

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DivineWar
{
	internal static class BossRewardSwap
	{
		internal const string RewardId = "tch.divinewar.bossPyreDraft.v1";

		private static RelicDraftRewardData reward;

		internal static RelicDraftRewardData GetOrCreate(AllGameData allData)
		{
			if ((Object)(object)reward != (Object)null)
			{
				return reward;
			}
			GrantableRewardData obj = allData.FindRewardDataByName("BlessingDraftBoss") ?? allData.FindRewardData("3ba5d3bc-17d2-4cd2-9121-371f8c2e8043");
			RelicDraftRewardData val = (RelicDraftRewardData)(object)((obj is RelicDraftRewardData) ? obj : null);
			if ((Object)(object)val == (Object)null || (Object)(object)val.DraftPool == (Object)null)
			{
				Plugin.Log("Classic boss pyre draft unavailable; omitting the soul reward.");
				return null;
			}
			RelicDraftRewardData val2 = Object.Instantiate<RelicDraftRewardData>(val);
			((Object)val2).name = "DivineWarBossPyreDraft";
			AccessTools.Field(typeof(GameData), "id").SetValue(val2, "tch.divinewar.bossPyreDraft.v1");
			reward = val2;
			return reward;
		}

		internal static bool IsRegionBossReward(NodeDistanceData distance, SaveManager save)
		{
			RunData val = ((save != null) ? save.GetRunData() : null);
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			for (int i = 0; i < val.RegionRunData.NumSelectableRegions; i++)
			{
				if (distance == val.GetDistanceData(RegionRunSetupHelper.GetRegionEndDistance(i)))
				{
					return true;
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(AllGameData), "FindRewardData")]
	internal static class LoadDivineBossReward
	{
		private static bool Prefix(AllGameData __instance, string id, ref GrantableRewardData __result)
		{
			if (id != "tch.divinewar.bossPyreDraft.v1")
			{
				return true;
			}
			RelicDraftRewardData orCreate = BossRewardSwap.GetOrCreate(__instance);
			if ((Object)(object)orCreate == (Object)null)
			{
				return true;
			}
			__result = (GrantableRewardData)(object)orCreate;
			return false;
		}
	}
	[HarmonyPatch(typeof(NodeDistanceData), "GetBattleRewards")]
	internal static class SwapRegionBossRewards
	{
		private static void Postfix(NodeDistanceData __instance, SaveManager saveManager, ref List<GrantableRewardData> __result)
		{
			if (!Plugin.IsDivine || __result == null || !BossRewardSwap.IsRegionBossReward(__instance, saveManager))
			{
				return;
			}
			for (int num = __result.Count - 1; num >= 0; num--)
			{
				if (__result[num] is SoulDraftRewardData)
				{
					RelicDraftRewardData orCreate = BossRewardSwap.GetOrCreate(saveManager.GetAllGameData());
					if ((Object)(object)orCreate == (Object)null)
					{
						__result.RemoveAt(num);
					}
					else
					{
						((GrantableRewardData)orCreate).SetSaveManager(saveManager);
						__result[num] = (GrantableRewardData)(object)orCreate;
					}
				}
				else if (__result[num] is RegionRewardUpgradeRewardData)
				{
					__result.RemoveAt(num);
				}
			}
		}
	}
	[HarmonyPatch(typeof(RelicDraftRewardData), "GetRelicsFromClasses")]
	internal static class RepeatBossPyreChoices
	{
		private static bool Prefix(RelicDraftRewardData __instance, List<CollectableRelicData> outList)
		{
			if (!Plugin.IsDivine || ((GameData)__instance).GetID() != "tch.divinewar.bossPyreDraft.v1")
			{
				return true;
			}
			outList.Clear();
			__instance.DraftPool.GetAllChoices(outList);
			return false;
		}
	}
	internal static class DivineArtifactArt
	{
		private static Texture2D background;

		internal static Sprite Compose(Sprite foreground)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Expected O, but got Unknown
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: 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_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c6: Expected O, but got Unknown
			//IL_01db: Unknown result type (might be due to invalid IL or missing references)
			//IL_0204: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)foreground == (Object)null)
			{
				throw new InvalidDataException("Missing divine artifact foreground.");
			}
			if ((Object)(object)background == (Object)null)
			{
				background = new Texture2D(2, 2, (TextureFormat)4, false);
				string path = Path.Combine(DivineArtifacts.DirectoryPath, "assets", "DivineArtifactBG.png");
				if (!ImageConversion.LoadImage(background, File.ReadAllBytes(path)))
				{
					throw new InvalidDataException("Invalid DivineArtifactBG.png.");
				}
			}
			RenderTexture active = RenderTexture.active;
			RenderTexture temporary = RenderTexture.GetTemporary(256, 256, 0, (RenderTextureFormat)0);
			Texture2D val = null;
			try
			{
				RenderTexture.active = temporary;
				GL.Clear(true, true, Color.clear);
				GL.PushMatrix();
				try
				{
					GL.LoadPixelMatrix(0f, 256f, 256f, 0f);
					Graphics.DrawTexture(new Rect(0f, 0f, 256f, 256f), (Texture)(object)background);
					Rect textureRect = foreground.textureRect;
					Rect val2 = default(Rect);
					((Rect)(ref val2))..ctor(((Rect)(ref textureRect)).x / (float)((Texture)foreground.texture).width, ((Rect)(ref textureRect)).y / (float)((Texture)foreground.texture).height, ((Rect)(ref textureRect)).width / (float)((Texture)foreground.texture).width, ((Rect)(ref textureRect)).height / (float)((Texture)foreground.texture).height);
					float num = 194.56f / Math.Max(((Rect)(ref textureRect)).width, ((Rect)(ref textureRect)).height);
					float num2 = ((Rect)(ref textureRect)).width * num;
					float num3 = ((Rect)(ref textureRect)).height * num;
					Graphics.DrawTexture(new Rect((256f - num2) / 2f, (256f - num3) / 2f, num2, num3), (Texture)(object)foreground.texture, val2, 0, 0, 0, 0);
				}
				finally
				{
					GL.PopMatrix();
				}
				val = new Texture2D(256, 256, (TextureFormat)4, false)
				{
					name = "DivineWar_" + ((Object)foreground).name
				};
				val.ReadPixels(new Rect(0f, 0f, 256f, 256f), 0, 0);
				val.Apply(false, true);
				return Sprite.Create(val, new Rect(0f, 0f, 256f, 256f), new Vector2(0.5f, 0.5f), 100f);
			}
			catch
			{
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
				throw;
			}
			finally
			{
				RenderTexture.active = active;
				RenderTexture.ReleaseTemporary(temporary);
			}
		}
	}
	[HarmonyPatch(typeof(CardManager), "DrawDeploymentPhaseHand")]
	internal static class DivineCheatersHandDeployment
	{
		internal static void Postfix(CardManager __instance, RelicManager ___relicManager)
		{
			int num = 0;
			foreach (RelicEffectChangeStartingHandSize relicEffect in ___relicManager.GetRelicEffects<RelicEffectChangeStartingHandSize>(new List<RelicEffectChangeStartingHandSize>()))
			{
				RelicState sourceRelicState = ((RelicEffectBase)relicEffect).SourceRelicState;
				if (DivineArtifacts.PortFor((sourceRelicState != null) ? sourceRelicState.GetRelicDataID() : null) == "CheatersHand")
				{
					num += (int)relicEffect.Value;
				}
			}
			if (num > 0)
			{
				__instance.DrawCards(num, (CardState)null, (CardType)4, -1);
			}
		}
	}
	internal static class DivineArtifactJson
	{
		internal static DivineArtifactTable ReadTable(string json)
		{
			JSONNode source = Object(JSON.Parse(json));
			DivineArtifactTable divineArtifactTable = new DivineArtifactTable
			{
				schema = Text(source, "schema")
			};
			foreach (JSONNode child in ((JSONNode)Array(source, "entries")).Childs)
			{
				divineArtifactTable.entries.Add(ReadEntry(child));
			}
			return divineArtifactTable;
		}

		internal static DivineArtifactDefinition ReadDefinition(string json)
		{
			return ReadEntry(JSON.Parse(json));
		}

		private static JSONNode Object(JSONNode source)
		{
			if (!((JSONNode)(object)((source != null) ? source.AsObject : null) != (object)null))
			{
				throw new InvalidDataException("Expected a divine artifact JSON object.");
			}
			return source;
		}

		private static JSONArray Array(JSONNode source, string field)
		{
			JSONNode obj = source[field];
			return (JSONArray)(object)(((obj is JSONArray) ? obj : null) ?? throw new InvalidDataException("Expected divine artifact array: " + field));
		}

		private static string Text(JSONNode source, string field)
		{
			return source[field].Value;
		}

		private static string OptionalText(JSONNode source, string field)
		{
			JSONNode obj = source[field];
			JSONData val = (JSONData)(object)((obj is JSONData) ? obj : null);
			if (val == null)
			{
				return null;
			}
			if (!(((JSONNode)val).Value == "null"))
			{
				return ((JSONNode)val).Value;
			}
			return null;
		}

		private static int Number(JSONNode source, string field, int? fallback = null)
		{
			string text = Text(source, field);
			if (string.IsNullOrEmpty(text) && fallback.HasValue)
			{
				return fallback.Value;
			}
			if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
			{
				return result;
			}
			throw new InvalidDataException("Invalid divine artifact integer: " + field);
		}

		private static DivineArtifactDefinition ReadEntry(JSONNode source)
		{
			Object(source);
			if (!bool.TryParse(Text(source, "enabled"), out var result))
			{
				throw new InvalidDataException("Invalid divine artifact enabled flag.");
			}
			DivineArtifactDefinition divineArtifactDefinition = new DivineArtifactDefinition
			{
				id = Text(source, "id"),
				sourceId = Text(source, "sourceId"),
				sourceAsset = Text(source, "sourceAsset"),
				clanId = Text(source, "clanId"),
				name = Text(source, "name"),
				description = Text(source, "description"),
				descriptionOverride = OptionalText(source, "descriptionOverride"),
				origin = OptionalText(source, "origin"),
				notes = OptionalText(source, "notes"),
				port = OptionalText(source, "port"),
				enabled = result,
				weight = Number(source, "weight", 1),
				effectClasses = ((JSONNode)Array(source, "effectClasses")).Childs.Select((JSONNode x) => x.Value).ToList()
			};
			foreach (JSONNode child in ((JSONNode)Array(source, "patches")).Childs)
			{
				Object(child);
				divineArtifactDefinition.patches.Add(new DivineArtifactPatch
				{
					effect = Number(child, "effect"),
					field = Text(child, "field"),
					expected = Number(child, "expected"),
					value = Number(child, "value"),
					statusId = OptionalText(child, "statusId")
				});
			}
			return divineArtifactDefinition;
		}

		private static string Quote(string value)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected O, but got Unknown
			if (value != null)
			{
				return ((object)new JSONData(value)).ToString();
			}
			return "null";
		}

		private static string N(int value)
		{
			return value.ToString(CultureInfo.InvariantCulture);
		}

		internal static string WriteDefinition(DivineArtifactDefinition e)
		{
			return "{" + string.Join(",", "\"id\":" + Quote(e.id), "\"sourceId\":" + Quote(e.sourceId), "\"sourceAsset\":" + Quote(e.sourceAsset), "\"clanId\":" + Quote(e.clanId), "\"name\":" + Quote(e.name), "\"description\":" + Quote(e.description), "\"descriptionOverride\":" + Quote(e.descriptionOverride), "\"origin\":" + Quote(e.origin), "\"notes\":" + Quote(e.notes), "\"port\":" + Quote(e.port), "\"enabled\":" + (e.enabled ? "true" : "false"), "\"weight\":" + N(e.weight), "\"effectClasses\":[" + string.Join(",", e.effectClasses.Select(Quote)) + "]", "\"patches\":[" + string.Join(",", e.patches.Select((DivineArtifactPatch p) => "{\"effect\":" + N(p.effect) + ",\"field\":" + Quote(p.field) + ",\"expected\":" + N(p.expected) + ",\"value\":" + N(p.value) + ",\"statusId\":" + Quote(p.statusId) + "}")) + "]") + "}";
		}
	}
	[Serializable]
	internal sealed class DivineArtifactTable
	{
		public string schema;

		public List<DivineArtifactDefinition> entries = new List<DivineArtifactDefinition>();
	}
	[Serializable]
	internal sealed class DivineArtifactDefinition
	{
		public string id;

		public string sourceId;

		public string sourceAsset;

		public string clanId;

		public string name;

		public string description;

		public string descriptionOverride;

		public string origin;

		public string notes;

		public string port;

		public bool enabled;

		public int weight = 1;

		public List<string> effectClasses = new List<string>();

		public List<DivineArtifactPatch> patches = new List<DivineArtifactPatch>();
	}
	[Serializable]
	internal sealed class DivineArtifactPatch
	{
		public int effect;

		public string field;

		public int expected;

		public int value;

		public string statusId;
	}
	internal static class DivineArtifactPolicy
	{
		internal const string Prefix = "tch.divinewar.artifact.";

		internal static readonly string[] Ports = new string[16]
		{
			"UnitCost", "GoldVault", "CheatersHand", "Plating", "HellBanner", "IronCage", "InfusedMallet", "CarelessLoader", "ImprovedFirebox", "Conscription",
			"Grindstone", "StunCoal", "StewardPrototype", "EnemyAttack", "PyrePackage", "LightGift"
		};

		private const string SnapshotSeparator = ".snapshot.";

		internal static string RuntimeStatusId(string id)
		{
			if (!(id == "meleeweakness"))
			{
				return id;
			}
			return "melee weakness";
		}

		internal static bool IsDivine(string id)
		{
			return id?.StartsWith("tch.divinewar.artifact.", StringComparison.Ordinal) ?? false;
		}

		internal static string SnapshotId(string key, string json)
		{
			return "tch.divinewar.artifact." + key + ".snapshot." + Convert.ToBase64String(Encoding.UTF8.GetBytes(json));
		}

		internal static bool TrySnapshot(string id, out string key, out string json)
		{
			key = null;
			json = null;
			if (!IsDivine(id))
			{
				return false;
			}
			int num = id.IndexOf(".snapshot.", "tch.divinewar.artifact.".Length, StringComparison.Ordinal);
			if (num < 0)
			{
				return false;
			}
			if (id.Length > 65536)
			{
				throw new ArgumentException("Oversized divine artifact snapshot.");
			}
			key = id.Substring("tch.divinewar.artifact.".Length, num - "tch.divinewar.artifact.".Length);
			json = Encoding.UTF8.GetString(Convert.FromBase64String(id.Substring(num + ".snapshot.".Length)));
			return true;
		}

		internal static void Validate(DivineArtifactTable table)
		{
			if (table == null || table.schema != "divine-artifacts-1" || table.entries == null)
			{
				throw new ArgumentException("Unsupported divine artifact table.");
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			foreach (DivineArtifactDefinition entry in table.entries)
			{
				if (entry == null || string.IsNullOrEmpty(entry.id) || entry.id.Contains(".snapshot.") || entry.id.Contains(".upgrade.") || entry.id.Any((char c) => !char.IsLetterOrDigit(c) && c != '-' && c != '.') || !hashSet.Add(entry.id) || !Guid.TryParse(entry.sourceId, out var result) || string.IsNullOrEmpty(entry.sourceAsset) || string.IsNullOrEmpty(entry.name) || string.IsNullOrEmpty(entry.description) || entry.weight < 1 || entry.weight > 1000 || (entry.clanId != "none" && !Guid.TryParse(entry.clanId, out result)) || entry.effectClasses == null || entry.effectClasses.Count == 0 || entry.effectClasses.Any((string x) => string.IsNullOrEmpty(x) || x == "RelicEffectRemoveSelf") || entry.patches == null || entry.patches.Count == 0)
				{
					throw new ArgumentException("Invalid divine artifact definition: " + entry?.id);
				}
				if (!string.IsNullOrEmpty(entry.port) && (!IEnumerableUtility.Contains<string>((ReadOnlySpan<string>)Ports, entry.port) || entry.clanId != "none"))
				{
					throw new ArgumentException("Unknown or non-neutral MT1 artifact port: " + entry.id);
				}
				HashSet<string> hashSet2 = new HashSet<string>();
				foreach (DivineArtifactPatch patch in entry.patches)
				{
					if (patch == null || patch.effect < 0 || patch.effect >= entry.effectClasses.Count || !IEnumerableUtility.Contains<string>((ReadOnlySpan<string>)new string[12]
					{
						"paramInt", "paramInt2", "paramInt3", "statusCount", "upgradeAttack", "upgradeHP", "upgradeCost", "upgradeSize", "upgradeStatusCount", "conditionAmount",
						"cardEffectAmount", "cardStatusCount"
					}, patch.field) || patch.expected == 0 || patch.value == 0 || Math.Abs((long)patch.value) > 100000 || ((patch.expected < 0 || patch.value < 0) && (((!(entry.port == "EnemyAttack") || !(patch.field == "paramInt")) && (!(entry.port == "Conscription") || !(patch.field == "upgradeSize"))) || patch.expected >= 0 || patch.value >= 0)) || ((patch.field == "statusCount" || patch.field == "upgradeStatusCount" || patch.field == "cardStatusCount") && string.IsNullOrEmpty(patch.statusId)) || !hashSet2.Add(patch.effect + ":" + patch.field + ":" + patch.statusId))
					{
						throw new ArgumentException("Invalid divine artifact patch: " + entry.id);
					}
					if ((entry.port == "InfusedMallet" || entry.port == "StunCoal" || entry.sourceAsset == "ChanceToCleanse") && patch.field == "paramInt" && patch.value > 100)
					{
						throw new ArgumentException("Artifact probability must be between 1 and 100: " + entry.id);
					}
					if ((patch.field == "conditionAmount" && entry.port != "HellBanner") || (patch.field == "cardEffectAmount" && entry.port != "InfusedMallet") || (patch.field == "cardStatusCount" && entry.port != "StunCoal") || (patch.field == "upgradeStatusCount" && entry.port != "StewardPrototype") || (patch.field == "upgradeSize" && entry.port != "Conscription") || (patch.field == "upgradeCost" && entry.port != "UnitCost" && entry.port != "Conscription"))
					{
						throw new ArgumentException("Field requires its reviewed MT1 port template: " + entry.id);
					}
				}
			}
		}

		internal static bool MatchesClan(string clan, string main, string sub)
		{
			if (!(clan == "none") && !(clan == main))
			{
				return clan == sub;
			}
			return true;
		}

		internal static List<DivineArtifactDefinition> Draw(IEnumerable<DivineArtifactDefinition> pool, string seed, int count)
		{
			uint num = 2166136261u;
			foreach (char c in seed)
			{
				num ^= c;
				num *= 16777619;
			}
			if (num == 0)
			{
				num = 1u;
			}
			List<DivineArtifactDefinition> list = pool.OrderBy<DivineArtifactDefinition, string>((DivineArtifactDefinition x) => x.id, StringComparer.Ordinal).ToList();
			List<DivineArtifactDefinition> list2 = new List<DivineArtifactDefinition>();
			while (list.Count > 0 && list2.Count < count)
			{
				long num2 = ((IEnumerable<DivineArtifactDefinition>)list).Sum((Func<DivineArtifactDefinition, long>)((DivineArtifactDefinition x) => x.weight));
				num ^= num << 13;
				num ^= num >> 17;
				num ^= num << 5;
				long num3 = num % num2;
				int index = 0;
				while (num3 >= list[index].weight)
				{
					num3 -= list[index++].weight;
				}
				list2.Add(list[index]);
				list.RemoveAt(index);
			}
			return list2;
		}
	}
	public sealed class DivineCardlessHealthEffect : RelicEffectBase
	{
		private int amount;

		public override bool CanApplyInPreviewMode => true;

		public override PropDescriptions CreateEditorInspectorDescriptions()
		{
			return PropDescriptions.DisplayNone;
		}

		public override void Initialize(RelicState s, RelicData d, RelicEffectData e)
		{
			((RelicEffectBase)this).Initialize(s, d, e);
			amount = e.GetParamInt();
		}

		internal static bool Eligible(CharacterState c, CardState card)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Invalid comparison between Unknown and I4
			if ((Object)(object)c != (Object)null && (int)c.GetTeamType() == 2 && !c.IsPyreHeart() && !c.GetIsClone())
			{
				if (card != null)
				{
					return c.HasStatusEffect("cardless");
				}
				return true;
			}
			return false;
		}

		public override IEnumerator OnCharacterAdded(CharacterState c, CardState card, ICoreGameManagers m)
		{
			if (Eligible(c, card))
			{
				yield return c.BuffMaxHP(amount, false, base._srcRelicState, true);
			}
		}
	}
	public sealed class DivineCardlessAttackEffect : RelicEffectBase
	{
		private int amount;

		public override bool CanApplyInPreviewMode => true;

		public override PropDescriptions CreateEditorInspectorDescriptions()
		{
			return PropDescriptions.DisplayNone;
		}

		public override void Initialize(RelicState s, RelicData d, RelicEffectData e)
		{
			((RelicEffectBase)this).Initialize(s, d, e);
			amount = e.GetParamInt();
		}

		public override IEnumerator OnCharacterAdded(CharacterState c, CardState card, ICoreGameManagers m)
		{
			if (DivineCardlessHealthEffect.Eligible(c, card))
			{
				c.BuffDamage(amount, base._srcRelicState, false);
			}
			yield break;
		}
	}
	public sealed class DivineStewardPrototypeEffect : RelicEffectBase, ICardModifierRelicEffect, IRelicEffect, IStatusEffectRelicEffect
	{
		private readonly RelicEffectAddTempUpgrade cards = new RelicEffectAddTempUpgrade();

		private CardUpgradeData upgrade;

		public override PropDescriptions CreateEditorInspectorDescriptions()
		{
			return PropDescriptions.DisplayNone;
		}

		public override void Initialize(RelicState s, RelicData d, RelicEffectData e)
		{
			((RelicEffectBase)this).Initialize(s, d, e);
			((RelicEffectBase)cards).Initialize(s, d, e);
			upgrade = e.GetParamCardUpgradeData();
		}

		public bool ApplyCardStateModifiers(CardState c, RelicManager r, SaveManager s, CardManager m)
		{
			return cards.ApplyCardStateModifiers(c, r, s, m);
		}

		public bool GetTooltip(out string title, out string body)
		{
			return cards.GetTooltip(ref title, ref body);
		}

		public StatusEffectStackData[] GetStatusEffects()
		{
			return cards.GetStatusEffects();
		}

		public override IEnumerator OnCharacterAdded(CharacterState c, CardState card, ICoreGameManagers m)
		{
			if (DivineCardlessHealthEffect.Eligible(c, card) && c.GetSourceCharacterData().GetSubtypes().Any((SubtypeData s) => s.Key == "SubtypesData_TrainSteward"))
			{
				CardUpgradeState val = new CardUpgradeState();
				val.Setup(upgrade, false, false);
				yield return c.ApplyCardUpgrade(val, false, "", true, false, (CardState)null, (Action<UpgradeApplicationResult>)null, (TrainRoomAttachmentState)null, false);
			}
		}
	}
	public sealed class DivineLightGiftEffect : RelicEffectBase, ICharacterActionRelicEffect, IRelicEffect, IStatusEffectRelicEffect
	{
		private StatusEffectStackData[] statuses;

		public override PropDescriptions CreateEditorInspectorDescriptions()
		{
			return PropDescriptions.DisplayNone;
		}

		public override void Initialize(RelicState state, RelicData data, RelicEffectData effect)
		{
			((RelicEffectBase)this).Initialize(state, data, effect);
			statuses = effect.GetParamStatusEffects();
		}

		public bool TestCharacterTriggerEffect(CharacterTriggerRelicEffectParams p, ICoreGameManagers m)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Invalid comparison between Unknown and I4
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Invalid comparison between Unknown and I4
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Invalid comparison between Unknown and I4
			if ((Object)(object)((CharacterRelicEffectParams)p).characterState != (Object)null && !((CharacterRelicEffectParams)p).characterState.IsDestroyed && (int)((CharacterRelicEffectParams)p).characterState.GetTeamType() == 1 && !((CharacterRelicEffectParams)p).characterState.HasStatusEffect("untouchable") && ((int)p.trigger == 16 || (int)p.trigger == 13))
			{
				return ((CharacterRelicEffectParams)p).characterState.GetCurrentRoomIndex() == ((RoomState)m.GetRoomManager().GetPyreRoom()).GetRoomIndex() - 1;
			}
			return false;
		}

		public IEnumerator ApplyCharacterTriggerEffect(CharacterTriggerRelicEffectParams p, ICoreGameManagers m)
		{
			StatusEffectStackData[] array = statuses;
			foreach (StatusEffectStackData val in array)
			{
				((CharacterRelicEffectParams)p).characterState.AddStatusEffect(val.statusId, val.count, new AddStatusEffectParams
				{
					sourceRelicState = base._srcRelicState
				}, (CharacterState)null, true, false, true, false, false);
			}
			((RelicEffectBase)this).NotifyRelicTriggered(m.GetRelicManager(), ((CharacterRelicEffectParams)p).characterState);
			yield break;
		}

		public StatusEffectStackData[] GetStatusEffects()
		{
			return statuses;
		}
	}
	public sealed class DivineConscriptEffect : RelicEffectBase, ICharacterActionRelicEffect, IRelicEffect
	{
		private CardUpgradeData upgrade;

		private bool busy;

		public override PropDescriptions CreateEditorInspectorDescriptions()
		{
			return PropDescriptions.DisplayNone;
		}

		public override void Initialize(RelicState state, RelicData data, RelicEffectData effect)
		{
			((RelicEffectBase)this).Initialize(state, data, effect);
			upgrade = effect.GetParamCardUpgradeData();
		}

		public bool TestCharacterTriggerEffect(CharacterTriggerRelicEffectParams p, ICoreGameManagers m)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Invalid comparison between Unknown and I4
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Invalid comparison between Unknown and I4
			if (!busy && (int)p.trigger == 2 && (Object)(object)((CharacterRelicEffectParams)p).characterState != (Object)null && (int)((CharacterRelicEffectParams)p).characterState.GetTeamType() == 2)
			{
				CharacterData sourceCharacterData = ((CharacterRelicEffectParams)p).characterState.GetSourceCharacterData();
				if (sourceCharacterData == null)
				{
					return false;
				}
				return sourceCharacterData.IsChampion();
			}
			return false;
		}

		public IEnumerator ApplyCharacterTriggerEffect(CharacterTriggerRelicEffectParams p, ICoreGameManagers m)
		{
			SaveManager save = m.GetSaveManager();
			List<CardData> list = (from card in save.GetAllGameData().GetAllCardData()
				where (Object)(object)card != (Object)null && !((GameData)card).IsArchived && (int)card.GetCardType() == 1 && (int)card.GetRarity() == 1 && (Object)(object)card.GetSpawnCharacterData() != (Object)null && !card.GetSpawnCharacterData().IsChampion() && card.GetSpawnCharacterData().GetSubtypes().Any((SubtypeData s) => s.Key == "SubtypesData_BannerUnit") && save.IsDlcEnabledForCurrentRun(card.GetRequiredDLC())
				select card).OrderBy<CardData, string>((CardData c) => ((GameData)c).GetID(), StringComparer.Ordinal).ToList();
			if (list.Count == 0)
			{
				yield break;
			}
			busy = true;
			try
			{
				CardData chosen = list[RandomManager.Range(0, list.Count, (RngId)6)];
				bool loaded = false;
				LoadingScreen.AddTask((LoadingTask)new LoadAdditionalCards(new List<CardData> { chosen }, true, (DisplayStyle)2, (Action)delegate
				{
					loaded = true;
				}), true);
				yield return (object)new WaitUntil((Func<bool>)(() => loaded));
				AddCardUpgradingInfo val = new AddCardUpgradingInfo
				{
					tempCardUpgrade = true,
					upgradeDatas = { upgrade }
				};
				m.GetCardManager().AddNewCardWithSpecialPlacement(chosen, (CardPile)3, true, false, 0, 1, val);
				((RelicEffectBase)this).NotifyRelicTriggered(m.GetRelicManager(), ((CharacterRelicEffectParams)p).characterState);
			}
			finally
			{
				busy = false;
			}
		}
	}
	[HarmonyPatch(typeof(DamageHelper), "IsPiercingDamage")]
	internal static class DivineMalletPiercing
	{
		private static void Postfix(RelicState damageSourceRelic, ref bool __result)
		{
			if (DivineArtifacts.PortFor((damageSourceRelic != null) ? damageSourceRelic.GetRelicDataID() : null) == "InfusedMallet")
			{
				__result = true;
			}
		}
	}
	[HarmonyPatch]
	internal static class DivineStairsEnemyOnly
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			yield return AccessTools.Method(typeof(RelicEffectDamageEnemyOnAscend), "TestCharacterTriggerEffect", (Type[])null, (Type[])null);
			yield return AccessTools.Method(typeof(RelicEffectDamageEnemyOnDescend), "TestCharacterTriggerEffect", (Type[])null, (Type[])null);
		}

		private static void Postfix(RelicEffectBase __instance, CharacterTriggerRelicEffectParams relicEffectParams, ref bool __result)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Invalid comparison between Unknown and I4
			RelicState sourceRelicState = __instance.SourceRelicState;
			if (DivineArtifacts.SourceFor((sourceRelicState != null) ? sourceRelicState.GetRelicDataID() : null) == "269a6f43-9982-4683-ac39-1a862e481898")
			{
				bool num = __result;
				CharacterState characterState = ((CharacterRelicEffectParams)relicEffectParams).characterState;
				__result = num & (characterState != null && (int)characterState.GetTeamType() == 1);
			}
		}
	}
	internal static class DivineArtifactPorts
	{
		internal static void Set(object target, string field, object value)
		{
			AccessTools.Field(target.GetType(), field).SetValue(target, value);
		}

		internal static T New<T>() where T : ScriptableObject
		{
			T val = ScriptableObject.CreateInstance<T>();
			Collections(val);
			return val;
		}

		private static void Collections(object value)
		{
			Type type = value.GetType();
			while (type != null && type != typeof(Object))
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				foreach (FieldInfo fieldInfo in fields)
				{
					if (fieldInfo.GetValue(value) == null)
					{
						if (fieldInfo.FieldType.IsArray)
						{
							fieldInfo.SetValue(value, Array.CreateInstance(fieldInfo.FieldType.GetElementType(), 0));
						}
						else if (fieldInfo.FieldType.IsGenericType && fieldInfo.FieldType.GetGenericTypeDefinition() == typeof(List<>))
						{
							fieldInfo.SetValue(value, Activator.CreateInstance(fieldInfo.FieldType));
						}
					}
				}
				type = type.BaseType;
			}
		}

		private static RelicEffectData Effect(string name, int amount = 0, Type team = (Type)2)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_006c: Expected O, but got Unknown
			RelicEffectData val = new RelicEffectData();
			Collections((object)val);
			Set((object)val, "relicEffectClassName", name);
			Set((object)val, "paramInt", amount);
			Set((object)val, "paramSourceTeam", team);
			Set((object)val, "paramCharacterSubtype", "SubtypesData_None");
			Set((object)val, "paramCardType", (object)(CardType)4);
			Set((object)val, "paramTrigger", (object)(Trigger)2);
			return val;
		}

		private static RelicEffectData Status(string name, string status, int count, int room = 0, bool first = false)
		{
			//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_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			RelicEffectData val = Effect(name, room, (Type)1);
			Set(val, "paramStatusEffects", new StatusEffectStackData[1]
			{
				new StatusEffectStackData
				{
					statusId = status,
					count = count
				}
			});
			Set(val, "paramBool", first);
			return val;
		}

		private static RelicEffectCondition Condition(TrackedValueType tracked, int amount, bool perBattle = false)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Expected O, but got Unknown
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Expected O, but got Unknown
			//IL_0093: Expected O, but got Unknown
			RelicEffectCondition val = new RelicEffectCondition();
			Set((object)val, "paramTrackedValue", tracked);
			Set((object)val, "paramCardType", (object)(CardTypeTarget)2);
			Set((object)val, "paramEntryDuration", (object)(EntryDuration)(perBattle ? 2 : 0));
			Set((object)val, "paramTrackTriggerCount", perBattle);
			Set((object)val, "paramInt", amount);
			Set((object)val, "paramComparator", (object)(Comparator)6);
			Set((object)val, "allowMultipleTriggersPerDuration", false);
			Set((object)val, "paramSubtype", "SubtypesData_None");
			return val;
		}

		private static CardUpgradeData Upgrade(string id, int attack = 0, int health = 0, int cost = 0, int size = 0)
		{
			CardUpgradeData obj = DivineArtifactPorts.New<CardUpgradeData>();
			((Object)obj).name = "DivineWarPortUpgrade";
			Set(obj, "id", id);
			Set(obj, "bonusDamage", attack);
			Set(obj, "bonusHP", health);
			Set(obj, "costReduction", cost);
			Set(obj, "bonusSize", size);
			Set(obj, "isUnique", true);
			return obj;
		}

		internal static CollectableRelicData Create(DivineArtifactDefinition entry, string id)
		{
			//IL_06c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e3: Expected O, but got Unknown
			//IL_06e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0700: Expected O, but got Unknown
			//IL_081a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0821: Expected O, but got Unknown
			//IL_084c: Unknown result type (might be due to invalid IL or missing references)
			//IL_085b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0508: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fe: Expected O, but got Unknown
			//IL_04f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_050f: Expected O, but got Unknown
			CollectableRelicData val = DivineArtifactPorts.New<CollectableRelicData>();
			((Object)val).name = entry.sourceAsset;
			Set(val, "id", entry.sourceId);
			Set(val, "rarity", (object)(CollectableRarity)1);
			Set(val, "nameKey", "");
			Set(val, "descriptionKey", "");
			Set(val, "relicActivatedKey", "");
			List<RelicEffectData> list = new List<RelicEffectData>();
			switch (entry.port)
			{
			case "GoldVault":
				list.Add(Effect("RelicEffectCurrencyForPyreDamage", 25, (Type)2));
				break;
			case "CheatersHand":
				list.Add(Effect("RelicEffectChangeStartingHandSize", 1, (Type)2));
				list.Add(Effect("RelicEffectCardsFromHandToDeck", 0, (Type)2));
				break;
			case "UnitCost":
			{
				RelicEffectData val2 = Effect("RelicEffectAddTempUpgrade", 0, (Type)2);
				CardUpgradeData val3 = Upgrade(id + ".upgrade.0", 0, 0, 1);
				Set(val3, "xCostReduction", 1);
				CardUpgradeMaskData val6 = DivineArtifactPorts.New<CardUpgradeMaskData>();
				Set(val6, "cardType", (object)(CardType)1);
				Set(val3, "filters", new List<CardUpgradeMaskData> { val6 });
				Set(val2, "paramCardUpgradeData", val3);
				list.Add(val2);
				break;
			}
			case "Plating":
			{
				RelicEffectData val2 = Effect("RelicEffectModifyCardHealth", 5, (Type)2);
				Set(val2, "paramCardType", (object)(CardType)1);
				list.Add(val2);
				list.Add(Effect(typeof(DivineCardlessHealthEffect).FullName + ", DivineWar", 5, (Type)2));
				break;
			}
			case "Grindstone":
			{
				RelicEffectData val2 = Effect("RelicEffectModifyCardAttack", 5, (Type)2);
				Set(val2, "paramCardType", (object)(CardType)1);
				list.Add(val2);
				list.Add(Effect(typeof(DivineCardlessAttackEffect).FullName + ", DivineWar", 5, (Type)2));
				break;
			}
			case "EnemyAttack":
				list.Add(Effect("RelicEffectModifyCharacterAttackDamage", -1, (Type)1));
				break;
			case "HellBanner":
			{
				RelicEffectData val2 = Effect("RelicEffectEnergyOnUnitSpawned", 3, (Type)2);
				Set(val2, "effectConditions", new List<RelicEffectCondition> { Condition((TrackedValueType)23, 2) });
				list.Add(val2);
				break;
			}
			case "IronCage":
			{
				RelicEffectData val2 = Status(typeof(DivineIronCageEffect).FullName + ", DivineWar", "dazed", 2);
				list.Add(val2);
				break;
			}
			case "StunCoal":
			case "InfusedMallet":
			{
				RelicEffectData val2 = Effect("RelicEffectChanceAddEffectOnSpawn", (entry.port == "InfusedMallet") ? 50 : 50, (Type)1);
				CardEffectData val5 = ((entry.port == "InfusedMallet") ? new CardEffectData("CardEffectDamage", (CharacterData)null, (Type)1, (StatusEffectStackData)null) : new CardEffectData("CardEffectAddStatusEffect", (CharacterData)null, (Type)1, new StatusEffectStackData
				{
					statusId = "dazed",
					count = 1
				}));
				Set(val5, "targetMode", (object)(TargetMode)12);
				Set(val5, "paramInt", (entry.port == "InfusedMallet") ? 10 : 0);
				Set(val2, "paramCardEffects", new List<CardEffectData> { val5 });
				list.Add(val2);
				break;
			}
			case "CarelessLoader":
				list.Add(Status("RelicEffectAddStatusEffectOnEnterRoomIndex", "dazed", 1, 0, first: true));
				list.Add(Status("RelicEffectAddStatusEffectOnEnterRoomIndex", "melee weakness", 1, 0, first: true));
				break;
			case "ImprovedFirebox":
				list.Add(Effect("RelicEffectModifyEnergyStartOfCombat", 7, (Type)2));
				Set(val, "disallowInDeploymentPhase", true);
				break;
			case "Conscription":
			{
				RelicEffectData val2 = Effect(typeof(DivineConscriptEffect).FullName + ", DivineWar", 1, (Type)2);
				Set(val2, "effectConditions", new List<RelicEffectCondition> { Condition((TrackedValueType)23, 1, perBattle: true) });
				Set(val2, "paramCardUpgradeData", Upgrade(id + ".upgrade.0", 10, 10, 1, -1));
				list.Add(val2);
				break;
			}
			case "StewardPrototype":
			{
				RelicEffectData val2 = Effect(typeof(DivineStewardPrototypeEffect).FullName + ", DivineWar", 0, (Type)2);
				CardUpgradeData val3 = Upgrade(id + ".upgrade.0", 5, 5);
				CardUpgradeMaskData val4 = DivineArtifactPorts.New<CardUpgradeMaskData>();
				Set(val4, "cardType", (object)(CardType)1);
				Set(val4, "requiredSubtypes", new List<string> { "SubtypesData_TrainSteward" });
				Set(val3, "filters", new List<CardUpgradeMaskData> { val4 });
				Set(val3, "statusEffectUpgrades", new List<StatusEffectStackData>
				{
					new StatusEffectStackData
					{
						statusId = "damage shield",
						count = 2
					},
					new StatusEffectStackData
					{
						statusId = "multistrike",
						count = 1
					}
				});
				Set(val2, "paramCardUpgradeData", val3);
				Set(val2, "paramBool", true);
				list.Add(val2);
				break;
			}
			case "PyrePackage":
			{
				list.Add(Effect("RelicEffectIncreasePyreAttackFlat", 15, (Type)2));
				list.Add(Effect("RelicEffectIncreasePyreHealthFlat", 40, (Type)2));
				RelicEffectData val2 = Status("RelicEffectAddStatusEffectOnSpawn", "armor", 15);
				Set(val2, "paramSourceTeam", (object)(Type)2);
				Set(val2, "paramCharacterSubtype", "SubtypesData_Pyre");
				list.Add(val2);
				break;
			}
			case "LightGift":
				list.Add(Status(typeof(DivineLightGiftEffect).FullName + ", DivineWar", "dazed", 1));
				break;
			default:
				throw new InvalidDataException("Unknown versioned MT1 artifact port: " + entry.port);
			}
			Set(val, "effects", list);
			string path = Path.Combine(DivineArtifacts.DirectoryPath, "assets", "Mt1Artifacts", Path.GetFileName(entry.sourceAsset) + ".png");
			if (File.Exists(path))
			{
				Texture2D val7 = new Texture2D(2, 2, (TextureFormat)4, false);
				ImageConversion.LoadImage(val7, File.ReadAllBytes(path));
				Sprite value = Sprite.Create(val7, new Rect(0f, 0f, (float)((Texture)val7).width, (float)((Texture)val7).height), new Vector2(0.5f, 0.5f));
				Set(val, "icon", value);
				Set(val, "iconSmall", value);
			}
			return val;
		}

		internal static string Describe(string port, List<RelicEffectData> e)
		{
			return port switch
			{
				"UnitCost" => $"所有单位牌的费用 -{U().GetCostReduction()}[ember]。", 
				"GoldVault" => $"只要你拥有至少 {I()}[coin],薪火在战斗中受到伤害时,改为失去 {I()}[coin]。", 
				"CheatersHand" => $"每回合多抽 {I()} 张牌,然后将一张手牌放回抽牌堆顶部。", 
				"Plating" => $"友方单位获得 +{I()}[health]。", 
				"Grindstone" => $"友方单位获得 +{I()}[attack]。", 
				"EnemyAttack" => $"所有敌方单位获得 {I()}[attack]。", 
				"HellBanner" => string.Format("当你在一回合内召唤第 {0} 个友方单位时,获得 {1}[ember]。", AccessTools.Field(typeof(RelicEffectCondition), "paramInt").GetValue(e[0].GetEffectConditions()[0]), I()), 
				"IronCage" => $"当你用法术令敌方单位上升或下降时(即使升降失败),对其施加 [dazed] {S()}。", 
				"InfusedMallet" => $"敌方单位进入火车时,有 {I()}% 几率对其造成 {e[0].GetParamCardEffectData()[0].GetParamInt()} 点[piercing]伤害。", 
				"StunCoal" => $"敌方单位进入火车时,有 {I()}% 几率对其施加 [dazed] {e[0].GetParamCardEffectData()[0].GetParamStatusEffectStackData()[0].count}。", 
				"CarelessLoader" => $"对第一波位于底层的敌方单位施加 [dazed] {S()} 和 [meleeweakness] {S(1)}。", 
				"ImprovedFirebox" => $"在[deployphase]后的第一个回合,获得 {I()}[ember]。", 
				"Conscription" => $"每场战斗首次召唤勇者时,随机获得一张任意氏族的非常见战旗单位牌。本场战斗获得 +{U().GetBonusDamage()}[attack]、+{U().GetBonusHP()}[health],费用 -{U().GetCostReduction()}[ember],占用 {U().GetBonusSize()}[capacity]。", 
				"StewardPrototype" => string.Format("乘务员单位获得 +{0}[attack]、+{1}[health]、[damageshield] {2} 和 [multistrike] {3}。", U().GetBonusDamage(), U().GetBonusHP(), U().GetStatusEffectUpgrades().Single((StatusEffectStackData x) => x.statusId == "damage shield").count, U().GetStatusEffectUpgrades().Single((StatusEffectStackData x) => x.statusId == "multistrike").count), 
				"PyrePackage" => $"你的薪火获得 +{I()}[attack] 和 +{I(1)}[health]。战斗开始时,薪火获得 [armor] {S(2)}。", 
				"LightGift" => $"当敌方单位进入薪火室下方的楼层时,对其施加 [dazed] {S()}。", 
				_ => throw new InvalidDataException("Unknown port description."), 
			};
			int I(int n = 0)
			{
				return e[n].GetParamInt();
			}
			int S(int n = 0)
			{
				return e[n].GetParamStatusEffects()[0].count;
			}
			CardUpgradeData U()
			{
				return e[0].GetParamCardUpgradeData();
			}
		}
	}
	internal static class DivineArtifactRegistry
	{
		private sealed class Registration
		{
			internal bool Building;

			internal bool Ready;

			internal bool ReportedFailure;

			internal readonly List<CollectableRelicData> Published = new List<CollectableRelicData>();
		}

		private static readonly ConditionalWeakTable<AllGameData, Registration> Registrations = new ConditionalWeakTable<AllGameData, Registration>();

		internal static void Ensure(AllGameData all)
		{
			if ((Object)(object)all == (Object)null)
			{
				return;
			}
			Registration value = Registrations.GetValue(all, (AllGameData _) => new Registration());
			if (value.Building || value.Ready)
			{
				return;
			}
			value.Building = true;
			try
			{
				List<CollectableRelicData> list = Plugin.Field<List<CollectableRelicData>>(all, "collectableRelicDatas");
				if (list == null || !list.Any((CollectableRelicData r) => (Object)(object)r != (Object)null && !DivineArtifactPolicy.IsDivine(((GameData)r).GetID())) || LocalizationManager.Sources.Count == 0 || LocalizationUtil.GetMainLanguageSource().mLanguages.Count == 0)
				{
					return;
				}
				HashSet<string> hashSet = new HashSet<string>(from r in list
					where (Object)(object)r != (Object)null
					select ((GameData)r).GetID());
				bool flag = true;
				foreach (DivineArtifactDefinition item in DivineArtifacts.Catalog.Where((DivineArtifactDefinition e) => e.enabled))
				{
					string id = DivineArtifacts.Id(item);
					if (value.Published.Any((CollectableRelicData r) => ((GameData)r).GetID() == id))
					{
						continue;
					}
					if (string.IsNullOrEmpty(item.port) && !hashSet.Contains(item.sourceId))
					{
						flag = false;
						continue;
					}
					CollectableRelicData val = DivineArtifacts.Resolve(all, id);
					if ((Object)(object)val == (Object)null)
					{
						flag = false;
						continue;
					}
					if (!list.Any((CollectableRelicData r) => (Object)(object)r != (Object)null && ((GameData)r).GetID() == id))
					{
						list.Add(val);
					}
					value.Published.Add(val);
				}
				value.Ready = flag;
				if (flag)
				{
					Plugin.Log("Published " + value.Published.Count + " divine artifacts to native metadata catalogs; reward pools unchanged.");
				}
			}
			catch (Exception exception)
			{
				if (!value.ReportedFailure)
				{
					value.ReportedFailure = true;
					Plugin.Error(exception);
				}
			}
			finally
			{
				value.Building = false;
			}
		}

		internal static List<CollectableRelicData> Accessible(AllGameData all, List<CollectableRelicData> original)
		{
			if ((Object)(object)all == (Object)null)
			{
				return original;
			}
			Ensure(all);
			List<CollectableRelicData> list = new List<CollectableRelicData>(original);
			HashSet<string> hashSet = new HashSet<string>(from r in list
				where (Object)(object)r != (Object)null
				select ((GameData)r).GetID());
			foreach (CollectableRelicData item in Registrations.GetValue(all, (AllGameData _) => new Registration()).Published)
			{
				if (hashSet.Add(((GameData)item).GetID()))
				{
					list.Add(item);
				}
			}
			return list;
		}
	}
	[HarmonyPatch(typeof(AllGameData), "GetAllCollectableRelicData")]
	internal static class RegisterDivineArtifactCatalog
	{
		private static void Postfix(AllGameData __instance)
		{
			DivineArtifactRegistry.Ensure(__instance);
		}
	}
	[HarmonyPatch(typeof(AllGameData), "GetDataLists")]
	internal static class RegisterDivineArtifactSearch
	{
		private static void Postfix(AllGameData __instance)
		{
			DivineArtifactRegistry.Ensure(__instance);
		}
	}
	[HarmonyPatch(typeof(AllGameData), "CollectAllAccessibleRelicDatas")]
	internal static class RegisterAccessibleDivineArtifacts
	{
		private static void Postfix(AllGameData __instance, ref List<CollectableRelicData> __result)
		{
			__result = DivineArtifactRegistry.Accessible(__instance, __result);
		}
	}
	internal static class DivineArtifacts
	{
		private static readonly Dictionary<string, CollectableRelicData> Relics = new Dictionary<string, CollectableRelicData>();

		private static readonly Dictionary<string, CardUpgradeData> Upgrades = new Dictionary<string, CardUpgradeData>();

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

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

		private static readonly HashSet<string> Failed = new HashSet<string>();

		private static readonly MethodInfo CloneMethod = AccessTools.Method(typeof(object), "MemberwiseClone", (Type[])null, (Type[])null);

		private static DivineArtifactTable defaults;

		private static DivineArtifactTable configured;

		private static bool loaded;

		internal static string DirectoryPath => Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

		internal static IReadOnlyList<DivineArtifactDefinition> Catalog
		{
			get
			{
				Load();
				return configured.entries;
			}
		}

		internal static string PortFor(string id)
		{
			if (id == null || !PortIds.TryGetValue(id, out var value))
			{
				return null;
			}
			return value;
		}

		internal static string SourceFor(string id)
		{
			if (id == null || !SourceIds.TryGetValue(id, out var value))
			{
				return null;
			}
			return value;
		}

		private static void Load()
		{
			if (loaded)
			{
				return;
			}
			loaded = true;
			using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("DivineWar.divine-artifacts.json"))
			{
				using StreamReader streamReader = new StreamReader(stream);
				defaults = DivineArtifactJson.ReadTable(streamReader.ReadToEnd());
			}
			DivineArtifactPolicy.Validate(defaults);
			configured = defaults;
			string text = Path.Combine(DirectoryPath, "config", "divine-artifacts.json");
			if (!File.Exists(text))
			{
				Plugin.Log("Divine artifact built-in catalog: " + configured.entries.Count + " entries.");
				return;
			}
			try
			{
				DivineArtifactTable divineArtifactTable = DivineArtifactJson.ReadTable(File.ReadAllText(text));
				DivineArtifactPolicy.Validate(divineArtifactTable);
				configured = divineArtifactTable;
				Plugin.Log("Divine artifact catalog: " + divineArtifactTable.entries.Count + " entries, " + IEnumerableUtility.Count<DivineArtifactDefinition>(divineArtifactTable.entries, (Func<DivineArtifactDefinition, bool>)((DivineArtifactDefinition x) => x.enabled)) + " enabled; " + text);
			}
			catch (Exception exception)
			{
				configured = new DivineArtifactTable
				{
					schema = "divine-artifacts-1"
				};
				Plugin.Log("Divine artifact config invalid; hoard disabled. Built-in IDs remain loadable.");
				Plugin.Error(exception);
			}
		}

		internal static CollectableRelicData Resolve(AllGameData all, string id)
		{
			if (!DivineArtifactPolicy.IsDivine(id))
			{
				return null;
			}
			if (Relics.TryGetValue(id, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			if (Failed.Contains(id))
			{
				return null;
			}
			CollectableRelicData val = null;
			try
			{
				DivineArtifactDefinition entry;
				if (DivineArtifactPolicy.TrySnapshot(id, out var key, out var json))
				{
					entry = DivineArtifactJson.ReadDefinition(json);
					DivineArtifactPolicy.Validate(new DivineArtifactTable
					{
						schema = "divine-artifacts-1",
						entries = { entry }
					});
					if (entry.id != key)
					{
						throw new InvalidDataException("Mismatched divine artifact snapshot.");
					}
				}
				else
				{
					Load();
					key = id.Substring("tch.divinewar.artifact.".Length);
					entry = configured.entries.FirstOrDefault((DivineArtifactDefinition x) => x.id == key) ?? defaults.entries.FirstOrDefault((DivineArtifactDefinition x) => x.id == key);
					if (entry == null)
					{
						return null;
					}
				}
				bool num = !string.IsNullOrEmpty(entry.port);
				CollectableRelicData val2 = (CollectableRelicData)(num ? ((object)DivineArtifactPorts.Create(entry, id)) : ((object)((IEnumerable<CollectableRelicData>)all.GetAllCollectableRelicData()).FirstOrDefault((Func<CollectableRelicData, bool>)((CollectableRelicData x) => (Object)(object)x != (Object)null && ((GameData)x).GetID() == entry.sourceId))));
				if (num && (Object)(object)((RelicData)val2).GetIcon() == (Object)null)
				{
					CollectableRelicData val3 = ((IEnumerable<CollectableRelicData>)all.GetAllCollectableRelicData()).FirstOrDefault((Func<CollectableRelicData, bool>)((CollectableRelicData x) => (Object)(object)x != (Object)null && ((GameData)x).GetID() == entry.sourceId)) ?? ((IEnumerable<CollectableRelicData>)all.GetAllCollectableRelicData()).FirstOrDefault((Func<CollectableRelicData, bool>)((CollectableRelicData x) => (Object)(object)((x != null) ? ((RelicData)x).GetIcon() : null) != (Object)null));
					if ((Object)(object)val3 != (Object)null)
					{
						Set(typeof(RelicData), val2, "icon", ((RelicData)val3).GetIcon());
						Set(typeof(RelicData), val2, "iconSmall", ((RelicData)val3).GetIconSmall());
					}
				}
				if ((Object)(object)val2 == (Object)null || ((Object)val2).name != entry.sourceAsset || val2.IsBossGivenRelic() || (val2.GetLinkedClassID() ?? "none") != entry.clanId || !(from x in ((RelicData)val2).GetEffects()
					select x.GetEffectClassName()).SequenceEqual(entry.effectClasses))
				{
					throw new InvalidDataException("Source artifact changed or unavailable: " + entry.id);
				}
				val = (num ? val2 : Object.Instantiate<CollectableRelicData>(val2));
				((Object)val).name = "DivineWar_" + entry.id;
				Set(typeof(GameData), val, "id", id);
				List<RelicEffectData> list = ((IEnumerable<RelicEffectData>)((RelicData)val2).GetEffects()).Select((Func<RelicEffectData, RelicEffectData>)((RelicEffectData x) => (RelicEffectData)CloneMethod.Invoke(x, null))).ToList();
				Set(typeof(RelicData), val, "effects", list);
				Dictionary<int, CardUpgradeData> dictionary = new Dictionary<int, CardUpgradeData>();
				foreach (DivineArtifactPatch patch in entry.patches)
				{
					Apply(list[patch.effect], patch, id, dictionary);
				}
				RegisterText(val2, val, entry, id);
				try
				{
					Set(typeof(RelicData), val, "icon", DivineArtifactArt.Compose(((RelicData)val2).GetIcon()));
					Set(typeof(RelicData), val, "iconSmall", DivineArtifactArt.Compose(((RelicData)val2).GetIconSmall() ?? ((RelicData)val2).GetIcon()));
				}
				catch (Exception exception)
				{
					Set(typeof(RelicData), val, "icon", ((RelicData)val2).GetIcon());
					Set(typeof(RelicData), val, "iconSmall", ((RelicData)val2).GetIconSmall());
					Plugin.Log("Divine artifact art unavailable; retaining source icon for " + entry.id);
					Plugin.Error(exception);
				}
				foreach (CardUpgradeData value2 in dictionary.Values)
				{
					Upgrades[((GameData)value2).GetID()] = value2;
				}
				foreach (RelicEffectData item in list)
				{
					if ((Object)(object)item.GetParamCardUpgradeData() != (Object)null)
					{
						Upgrades[((GameData)item.GetParamCardUpgradeData()).GetID()] = item.GetParamCardUpgradeData();
					}
				}
				Relics[id] = val;
				SourceIds[id] = entry.sourceId;
				PortIds[id] = entry.port;
				Plugin.Log("Registered permanent divine artifact " + entry.id);
				return val;
			}
			catch (Exception exception2)
			{
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
				}
				Failed.Add(id);
				Plugin.Error(exception2);
				return null;
			}
		}

		private static void Apply(RelicEffectData effect, DivineArtifactPatch patch, string id, Dictionary<int, CardUpgradeData> upgrades)
		{
			object obj = effect;
			string text = patch.field;
			string statusId = DivineArtifactPolicy.RuntimeStatusId(patch.statusId);
			switch (text)
			{
			case "conditionAmount":
			{
				List<RelicEffectCondition> list2 = (from x in effect.GetEffectConditions()
					select x.Copy()).ToList();
				obj = list2[0];
				text = "paramInt";
				Set(typeof(RelicEffectData), effect, "effectConditions", list2);
				break;
			}
			case "cardEffectAmount":
			case "cardStatusCount":
			{
				List<CardEffectData> list = ((IEnumerable<CardEffectData>)effect.GetParamCardEffectData()).Select((Func<CardEffectData, CardEffectData>)((CardEffectData x) => (CardEffectData)CloneMethod.Invoke(x, null))).ToList();
				Set(typeof(RelicEffectData), effect, "paramCardEffects", list);
				obj = list[0];
				if (text == "cardStatusCount")
				{
					StatusEffectStackData[] array = (from x in list[0].GetParamStatusEffectStackData()
						select x.Copy()).ToArray();
					StatusEffectStackData obj2 = array.Single((StatusEffectStackData x) => x.statusId == statusId);
					if (obj2.count != patch.expected)
					{
						throw new InvalidDataException("Nested status changed.");
					}
					obj2.count = patch.value;
					Set(typeof(CardEffectData), list[0], "paramStatusEffects", array);
					return;
				}
				text = "paramInt";
				break;
			}
			}
			if (text == "statusCount")
			{
				StatusEffectStackData[] paramStatusEffects = effect.GetParamStatusEffects();
				int num = Array.FindIndex(paramStatusEffects, (StatusEffectStackData x) => x.statusId == statusId);
				if (num < 0 || paramStatusEffects[num].count != patch.expected)
				{
					throw new InvalidDataException("Source status changed: " + id);
				}
				StatusEffectStackData[] array2 = paramStatusEffects.Select((StatusEffectStackData x) => x.Copy()).ToArray();
				array2[num].count = patch.value;
				Set(typeof(RelicEffectData), effect, "paramStatusEffects", array2);
				return;
			}
			if (text.StartsWith("upgrade", StringComparison.Ordinal))
			{
				if (!upgrades.TryGetValue(patch.effect, out var value))
				{
					CardUpgradeData paramCardUpgradeData = effect.GetParamCardUpgradeData();
					if ((Object)(object)paramCardUpgradeData == (Object)null)
					{
						throw new InvalidDataException("Missing source upgrade: " + id);
					}
					value = Object.Instantiate<CardUpgradeData>(paramCardUpgradeData);
					Set(typeof(GameData), value, "id", id + ".upgrade." + patch.effect);
					upgrades.Add(patch.effect, value);
					Set(typeof(RelicEffectData), effect, "paramCardUpgradeData", value);
				}
				obj = value;
				if (text == "upgradeStatusCount")
				{
					List<StatusEffectStackData> list3 = (from x in value.GetStatusEffectUpgrades()
						select x.Copy()).ToList();
					StatusEffectStackData obj3 = list3.Single((StatusEffectStackData x) => x.statusId == statusId);
					if (obj3.count != patch.expected)
					{
						throw new InvalidDataException("Upgrade status changed.");
					}
					obj3.count = patch.value;
					Set(typeof(CardUpgradeData), value, "statusEffectUpgrades", list3);
					return;
				}
				if (text == "upgradeCost" && value.GetXCostReduction() == patch.expected)
				{
					Set(typeof(CardUpgradeData), value, "xCostReduction", patch.value);
				}
				text = text switch
				{
					"upgradeCost" => "costReduction", 
					"upgradeHP" => "bonusHP", 
					"upgradeAttack" => "bonusDamage", 
					_ => "bonusSize", 
				};
			}
			FieldInfo fieldInfo = AccessTools.Field(obj.GetType(), text);
			if (fieldInfo == null || (int)fieldInfo.GetValue(obj) != patch.expected)
			{
				throw new InvalidDataException("Source benefit changed: " + id + ":" + text);
			}
			fieldInfo.SetValue(obj, patch.value);
		}

		private static void Set(Type type, object target, string field, object value)
		{
			AccessTools.Field(type, field).SetValue(target, value);
		}

		private static void RegisterText(CollectableRelicData source, CollectableRelicData clone, DivineArtifactDefinition entry, string id)
		{
			LanguageSourceData mainLanguageSource = LocalizationUtil.GetMainLanguageSource();
			TermData termData = mainLanguageSource.GetTermData(((RelicData)source).GetNameKey(), false);
			TermData val = mainLanguageSource.GetTermData(id + ".name", false) ?? mainLanguageSource.AddTerm(id + ".name", (eTermType)0, true);
			val.SetNumLanguages(mainLanguageSource.mLanguages.Count);
			for (int i = 0; i < mainLanguageSource.mLanguages.Count; i++)
			{
				val.Languages[i] = ((mainLanguageSource.mLanguages[i].Code ?? "").StartsWith("zh", StringComparison.OrdinalIgnoreCase) ? entry.name : ("Divine " + (((termData != null) ? ((IEnumerable<string>)termData.Languages).ElementAtOrDefault(i) : null) ?? ((Object)source).name)));
			}
			Set(typeof(RelicData), clone, "nameKey", id + ".name");
			string text = ((!string.IsNullOrEmpty(entry.port)) ? DivineArtifactPorts.Describe(entry.port, ((RelicData)clone).GetEffects()) : entry.descriptionOverride);
			if (string.IsNullOrEmpty(text))
			{
				return;
			}
			TermData termData2 = mainLanguageSource.GetTermData(((RelicData)source).GetDescriptionKey(), false);
			TermData val2 = mainLanguageSource.GetTermData(id + ".description", false) ?? mainLanguageSource.AddTerm(id + ".description", (eTermType)0, true);
			val2.SetNumLanguages(mainLanguageSource.mLanguages.Count);
			for (int j = 0; j < mainLanguageSource.mLanguages.Count; j++)
			{
				string text2 = ((termData2 != null) ? ((IEnumerable<string>)termData2.Languages).ElementAtOrDefault(j) : null) ?? entry.description;
				if (entry.sourceAsset == "GainBonusOnThreeCardsPlayed")
				{
					text2 = text2.Replace("[effect0.power]", "[effect0.editorDraw]").Replace("[effect0.secondarypower]", "[effect0.power]").Replace("[effect0.editorDraw]", "[effect0.secondarypower]");
				}
				val2.Languages[j] = ((mainLanguageSource.mLanguages[j].Code ?? "").StartsWith("zh", StringComparison.OrdinalIgnoreCase) ? text : ((!string.IsNullOrEmpty(entry.port)) ? text : text2));
			}
			Set(typeof(RelicData), clone, "descriptionKey", id + ".description");
		}

		internal static CardUpgradeData ResolveUpgrade(AllGameData all, string id)
		{
			if (!DivineArtifactPolicy.IsDivine(id))
			{
				return null;
			}
			int num = id.LastIndexOf(".upgrade.", StringComparison.Ordinal);
			if (num < 0)
			{
				return null;
			}
			Resolve(all, id.Substring(0, num));
			if (!Upgrades.TryGetValue(id, out var value))
			{
				return null;
			}
			return value;
		}

		internal static List<DivineArtifactDefinition> Eligible(SaveManager save)
		{
			Load();
			HashSet<string> ownedSources = new HashSet<string>(StringComparer.Ordinal);
			foreach (RelicState collectedRelic in save.GetCollectedRelics())
			{
				string relicDataID = collectedRelic.GetRelicDataID();
				if (DivineArtifactPolicy.IsDivine(relicDataID))
				{
					Resolve(save.GetAllGameData(), relicDataID);
					if (SourceIds.TryGetValue(relicDataID, out var value))
					{
						ownedSources.Add(value);
					}
				}
			}
			List<DivineArtifactDefinition> list = configured.entries.Where((DivineArtifactDefinition entry) => entry.enabled).ToList();
			List<DivineArtifactDefinition> list2 = list.Where(delegate(DivineArtifactDefinition entry)
			{
				string clanId = entry.clanId;
				ClassData mainClass = save.GetMainClass();
				string main = ((mainClass != null) ? ((GameData)mainClass).GetID() : null);
				ClassData subClass = save.GetSubClass();
				return DivineArtifactPolicy.MatchesClan(clanId, main, (subClass != null) ? ((GameData)subClass).GetID() : null);
			}).ToList();
			List<DivineArtifactDefinition> list3 = list2.Where((DivineArtifactDefinition entry) => !ownedSources.Contains(entry.sourceId)).ToList();
			List<DivineArtifactDefinition> list4 = list3.Where((DivineArtifactDefinition entry) => SourceUnlocked(save, entry)).ToList();
			List<DivineArtifactDefinition> list5 = list4.Where((DivineArtifactDefinition entry) => !save.IsRelicReserved(Id(entry))).ToList();
			Plugin.Log("Divine hoard eligibility: configured=" + configured.entries.Count + ", enabled=" + list.Count + ", clan=" + list2.Count + ", unowned=" + list3.Count + ", resolved=" + list4.Count + ", unreserved=" + list5.Count);
			return list5;
		}

		internal static string Id(DivineArtifactDefinition entry)
		{
			return DivineArtifactPolicy.SnapshotId(entry.id, DivineArtifactJson.WriteDefinition(entry));
		}

		private static bool SourceUnlocked(SaveManager save, DivineArtifactDefinition entry)
		{
			if (!string.IsNullOrEmpty(entry.port))
			{
				return (Object)(object)Resolve(save.GetAllGameData(), Id(entry)) != (Object)null;
			}
			CollectableRelicData val = ((IEnumerable<CollectableRelicData>)save.GetAllGameData().GetAllCollectableRelicData()).FirstOrDefault((Func<CollectableRelicData, bool>)((CollectableRelicData x) => (Object)(object)x != (Object)null && ((GameData)x).GetID() == entry.sourceId));
			if ((Object)(object)val != (Object)null && save.IsItemUnlockedForRun((IUnlockableData)(object)val, false))
			{
				return (Object)(object)Resolve(save.GetAllGameData(), Id(entry)) != (Object)null;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(AllGameData), "FindCollectableRelicData")]
	internal static class ResolveDivineArtifact
	{
		private static bool Prefix(AllGameData __instance, string id, ref CollectableRelicData __result)
		{
			if (!DivineArtifactPolicy.IsDivine(id))
			{
				return true;
			}
			__result = DivineArtifacts.Resolve(__instance, id);
			if ((Object)(object)__result == (Object)null)
			{
				throw new InvalidDataException("Cannot restore divine artifact; refusing to let native loading remove its saved ID. See DivineWar log.");
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(AllGameData), "FindCardUpgradeData")]
	internal static class ResolveDivineArtifactUpgrade
	{
		private static bool Prefix(AllGameData __instance, string id, ref CardUpgradeData __result)
		{
			if (!DivineArtifactPolicy.IsDivine(id))
			{
				return true;
			}
			__result = DivineArtifacts.ResolveUpgrade(__instance, id);
			return false;
		}
	}
	internal static class DivineCoroutines
	{
		internal static IEnumerator<object> Empty()
		{
			yield break;
		}
	}
	public sealed class DivineEntry : MonoBehaviour
	{
		private const string BackgroundArtName = "BG_CovenantOutpost2";

		private const string GroundFile = "MainMenuGroundPatch.png";

		private const string HighlightFile = "MainMenuStationHighlight.png";

		private const string StationFile = "MainMenuStation.png";

		private const float ArtHeight = 1200f;

		private const float StationLeft = 1000f;

		private const float StationTop = 810f;

		private const float StationWidth = 740f;

		private const float StationHeight = 555f;

		private static Sprite groundSprite;

		private static Sprite highlightSprite;

		private static Sprite stationSprite;

		private Image stationHighlight;

		private MainMenuButton button;

		private MainMenuScreen screen;

		internal MainMenuButton Button => button;

		internal void Install(MainMenuScreen owner)
		{
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: 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_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_019f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0215: Unknown result type (might be due to invalid IL or missing references)
			//IL_021a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0225: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_024d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_0292: Unknown result type (might be due to invalid IL or missing references)
			//IL_0273: Unknown result type (might be due to invalid IL or missing references)
			//IL_0283: Unknown result type (might be due to invalid IL or missing references)
			screen = owner;
			Image val = InstallArtwork(owner);
			if ((Object)(object)button != (Object)null)
			{
				((Component)button).gameObject.SetActive(true);
				UpdateStationHighlight();
				return;
			}
			MainMenuButton val2 = Plugin.Field<MainMenuButton>(owner, "startRunButton");
			if ((Object)(object)val2 == (Object)null)
			{
				return;
			}
			GameObject val3 = Object.Instantiate<GameObject>(((Component)val2).gameObject, ((Component)val2).transform.parent);
			((Object)val3).name = "DivineWarMenuButton";
			button = val3.GetComponent<MainMenuButton>();
			TextMeshProUGUI val4 = Plugin.Field<TextMeshProUGUI>(button, "label") ?? val3.GetComponentInChildren<TextMeshProUGUI>(true);
			if ((Object)(object)val4 != (Object)null)
			{
				((TMP_Text)val4).font = DivineFont.Get(((TMP_Text)val4).font);
				((TMP_Text)val4).text = "圣战模式";
			}
			KeepButtonOnly(val3.transform, ((Component)button.Button).transform, ((Object)(object)val4 == (Object)null) ? null : ((TMP_Text)val4).transform.parent);
			RectTransform component = val3.GetComponent<RectTransform>();
			if ((Object)(object)component != (Object)null && (Object)(object)val4 != (Object)null && (Object)(object)val != (Object)null)
			{
				Canvas.ForceUpdateCanvases();
				Vector3[] array = (Vector3[])(object)new Vector3[4];
				((Graphic)val).rectTransform.GetWorldCorners(array);
				Vector3 val5 = array[0] + (array[3] - array[0]) * 0.75f + (array[1] - array[0]) * 0.16f;
				((Transform)component).position = ((Transform)component).position + (val5 - ((TMP_Text)val4).transform.position);
			}
			else if ((Object)(object)component != (Object)null && (Object)(object)val4 != (Object)null)
			{
				RectTransform component2 = ((Component)button.Button).GetComponent<RectTransform>();
				MainMenuButton val6 = Plugin.Field<MainMenuButton>(owner, "soulSaviorButton");
				TextMeshProUGUI val7 = (((Object)(object)val6 == (Object)null) ? null : Plugin.Field<TextMeshProUGUI>(val6, "label"));
				if ((Object)(object)component2 != (Object)null)
				{
					Canvas.ForceUpdateCanvases();
					Rect rect = component2.rect;
					float num = ((Rect)(ref rect)).width * Mathf.Abs(((Transform)component2).lossyScale.x);
					Vector3 position = ((Transform)component).position + ((Transform)component).right * (num * 2.8f);
					if ((Object)(object)val7 != (Object)null)
					{
						position.y += ((TMP_Text)val7).transform.position.y - ((TMP_Text)val4).transform.position.y;
					}
					((Transform)component).position = position;
				}
			}
			button.ResetButton();
			button.Button.StateChangedSignal.AddListener((Action)UpdateStationHighlight);
			UpdateStationHighlight();
			List<MainMenuButton> list = Plugin.Field<List<MainMenuButton>>(owner, "menuButtons");
			if (list != null && !list.Contains(button))
			{
				list.Add(button);
			}
			Plugin.Log("Divine War menu entry installed");
		}

		private Image InstallArtwork(MainMenuScreen owner)
		{
			Image val = null;
			Image[] componentsInChildren = ((Component)owner).GetComponentsInChildren<Image>(true);
			foreach (Image val2 in componentsInChildren)
			{
				if ((Object)(object)val2.sprite != (Object)null && ((Object)val2.sprite).name == "BG_CovenantOutpost2")
				{
					val = val2;
					break;
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			if (groundSprite == null)
			{
				groundSprite = LoadArtwork("MainMenuGroundPatch.png", val.sprite, matchNativeRect: true);
			}
			if (highlightSprite == null)
			{
				highlightSprite = LoadArtwork("MainMenuStationHighlight.png", val.sprite, matchNativeRect: false);
			}
			if (stationSprite == null)
			{
				stationSprite = LoadArtwork("MainMenuStation.png", val.sprite, matchNativeRect: false);
			}
			if ((Object)(object)groundSprite == (Object)null || (Object)(object)highlightSprite == (Object)null || (Object)(object)stationSprite == (Object)null)
			{
				return null;
			}
			CreateLayer(val, "DivineWarGroundPatch", groundSprite, stationPlacement: false);
			stationHighlight = CreateLayer(val, "DivineWarStationHighlight", highlightSprite, stationPlacement: true);
			CreateLayer(val, "DivineWarStation", stationSprite, stationPlacement: true);
			((Component)stationHighlight).gameObject.SetActive(false);
			return val;
		}

		private static Sprite LoadArtwork(string filename, Sprite native, bool matchNativeRect)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: 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_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			string text = Path.Combine(Path.GetDirectoryName(typeof(DivineEntry).Assembly.Location), "assets", filename);
			if (!File.Exists(text))
			{
				Plugin.Log("Divine War main-menu art missing: " + text);
				return null;
			}
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			if (!ImageConversion.LoadImage(val, File.ReadAllBytes(text)))
			{
				Object.Destroy((Object)(object)val);
				return null;
			}
			((Object)val).name = filename;
			Rect val2 = (Rect)(matchNativeRect ? native.rect : new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height));
			if (matchNativeRect && (((Rect)(ref val2)).xMax > (float)((Texture)val).width || ((Rect)(ref val2)).yMax > (float)((Texture)val).height))
			{
				Plugin.Log("Divine War main-menu art size mismatch: " + filename);
				Object.Destroy((Object)(object)val);
				return null;
			}
			Vector2 val3 = (matchNativeRect ? new Vector2(native.pivot.x / ((Rect)(ref val2)).width, native.pivot.y / ((Rect)(ref val2)).height) : new Vector2(0.5f, 0.5f));
			Sprite obj = Sprite.Create(val, val2, val3, native.pixelsPerUnit);
			((Object)obj).name = filename;
			return obj;
		}

		private static Image CreateLayer(Image background, string name, Sprite sprite, bool stationPlacement)
		{
			//IL_003f: 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_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: 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_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			Transform val = ((Component)background).transform.Find(name);
			GameObject val2 = (GameObject)((!((Object)(object)val == (Object)null)) ? ((object)((Component)val).gameObject) : ((object)new GameObject(name, new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			})));
			val2.layer = ((Component)background).gameObject.layer;
			if ((Object)(object)val == (Object)null)
			{
				val2.transform.SetParent(((Component)background).transform, false);
			}
			RectTransform component = val2.GetComponent<RectTransform>();
			if (stationPlacement)
			{
				Rect rect = background.sprite.rect;
				float num = (1000f - ((Rect)(ref rect)).x) / ((Rect)(ref rect)).width;
				float num2 = (1740f - ((Rect)(ref rect)).x) / ((Rect)(ref rect)).width;
				float num3 = (-165f - ((Rect)(ref rect)).y) / ((Rect)(ref rect)).height;
				float num4 = (390f - ((Rect)(ref rect)).y) / ((Rect)(ref rect)).height;
				component.anchorMin = new Vector2(num, num3);
				component.anchorMax = new Vector2(num2, num4);
			}
			else
			{
				component.anchorMin = Vector2.zero;
				component.anchorMax = Vector2.one;
			}
			component.offsetMin = Vector2.zero;
			component.offsetMax = Vector2.zero;
			((Transform)component).localScale = Vector3.one;
			Image component2 = val2.GetComponent<Image>();
			component2.sprite = sprite;
			((Graphic)component2).raycastTarget = false;
			val2.transform.SetAsLastSibling();
			return component2;
		}

		private void UpdateStationHighlight()
		{
			if (!((Object)(object)stationHighlight == (Object)null) && !((Object)(object)button == (Object)null))
			{
				GameUISelectableButton val = button.Button;
				((Component)stationHighlight).gameObject.SetActive(val.IsCurrentlyHighlighted() || val.IsCurrentlySelected() || val.IsSelectionStatePressed());
			}
		}

		private void OnDestroy()
		{
			if ((Object)(object)button != (Object)null)
			{
				button.Button.StateChangedSignal.RemoveListener((Action)UpdateStationHighlight);
			}
		}

		private static void KeepButtonOnly(Transform root, Transform buttonRoot, Transform signRoot)
		{
			Renderer[] componentsInChildren = ((Component)root).GetComponentsInChildren<Renderer>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].enabled = false;
			}
			TextMeshProUGUI[] componentsInChildren2 = ((Component)root).GetComponentsInChildren<TextMeshProUGUI>(true);
			foreach (TextMeshProUGUI val in componentsInChildren2)
			{
				if ((Object)(object)signRoot == (Object)null || !((TMP_Text)val).transform.IsChildOf(signRoot))
				{
					((Component)val).gameObject.SetActive(false);
				}
			}
			for (int j = 0; j < root.childCount; j++)
			{
				KeepButtonBranch(root.GetChild(j), buttonRoot, signRoot);
			}
		}

		private static void KeepButtonBranch(Transform node, Transform buttonRoot, Transform signRoot)
		{
			if (!((Object)(object)node == (Object)(object)buttonRoot) && !buttonRoot.IsChildOf(node) && (!((Object)(object)signRoot != (Object)null) || (!((Object)(object)node == (Object)(object)signRoot) && !signRoot.IsChildOf(node))))
			{
				((Component)node).gameObject.SetActive(false);
			}
			else if (!((Object)(object)node == (Object)(object)buttonRoot) && !((Object)(object)node == (Object)(object)signRoot))
			{
				for (int i = 0; i < node.childCount; i++)
				{
					KeepButtonBranch(node.GetChild(i), buttonRoot, signRoot);
				}
			}
		}

		internal bool Handle(CoreInputControlMapping mapping, IGameUIComponent triggeredUI, Controls control)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)button == (Object)null || !button.Button.TryTrigger(mapping, triggeredUI, control, false, false))
			{
				return false;
			}
			Open();
			return true;
		}

		private void Open()
		{
			SaveManager save = Plugin.Field<SaveManager>(screen, "saveManager");
			GameStateManager game = Plugin.Field<GameStateManager>(screen, "gameStateManager");
			ScreenManager screens = Plugin.Field<ScreenManager>(screen, "screenManager");
			SaveSlot.CancelReplayTransition(save);
			if (!SaveSlot.Select(save, divine: true))
			{
				return;
			}
			if (!File.Exists(SaveManager.GetGameSavePath("save-divineWar")))
			{
				game.StartNewRun((RunType)6, (string)null, (Action)null, true);
				return;
			}
			save.StartLoad((RunType)6, "", (Action<bool>)delegate(bool success)
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: 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_002a: Expected O, but got Unknown
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0064: Unknown result type (might be due to invalid IL or missing references)
				//IL_006f: 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_0085: 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_00d5: Expected O, but got Unknown
				if (!success)
				{
					screens.ShowDialog(new Data
					{
						content = "圣战进度无法读取;原存档已保留。",
						button1Text = "确定"
					}, (Data)null);
				}
				else if (!save.HasRun((RunType)6, "", false))
				{
					Plugin.Log("Divine save contains no started run; opening setup.");
					game.StartNewRun((RunType)6, (string)null, (Action)null, true);
				}
				else
				{
					screens.ShowDialog(new Data
					{
						content = "圣战模式",
						button1Text = "回到游戏",
						button2Text = "新游戏",
						callback1 = delegate
						{
							save.ContinueRunWithReplay((RunType)6, "", (Action)null, false);
						},
						callback2 = delegate
						{
							game.StartNewRun((RunType)6, (string)null, (Action)null, false);
						}
					}, (Data)null);
				}
			});
		}
	}
	internal static class DivineFont
	{
		private static TMP_FontAsset isolated;

		private static bool attempted;

		internal static TMP_FontAsset Get(TMP_FontAsset preferred = null)
		{
			if ((Object)(object)isolated != (Object)null)
			{
				return isolated;
			}
			if (attempted)
			{
				return preferred ?? TMP_Settings.defaultFontAsset;
			}
			attempted = true;
			try
			{
				TMP_FontAsset? obj = ((IEnumerable<TMP_FontAsset>)Resources.FindObjectsOfTypeAll<TMP_FontAsset>()).FirstOrDefault((Func<TMP_FontAsset, bool>)((TMP_FontAsset asset) => (Object)(object)asset != (Object)null && (Object)(object)asset.sourceFontFile != (Object)null && ((Object)asset).name.IndexOf("NotoSansSC", StringComparison.OrdinalIgnoreCase) >= 0));
				Font val = ((obj != null) ? obj.sourceFontFile : null);
				if ((Object)(object)val == (Object)null)
				{
					val = Font.CreateDynamicFontFromOSFont(new string[3] { "Microsoft YaHei", "Microsoft YaHei UI", "SimHei" }, 32);
				}
				if ((Object)(object)val == (Object)null)
				{
					val = ((preferred != null) ? preferred.sourceFontFile : null);
				}
				if ((Object)(object)val == (Object)null)
				{
					throw new InvalidOperationException("No Chinese font source");
				}
				isolated = TMP_FontAsset.CreateFontAsset(val);
				if ((Object)(object)isolated == (Object)null)
				{
					throw new InvalidOperationException("TMP font creation failed");
				}
				((Object)isolated).name = "DivineWar Isolated Chinese Font";
				((Object)isolated).hideFlags = (HideFlags)32;
				bool flag = isolated.HasCharacter('使', false, true);
				Plugin.Log($"Created isolated TMP font from {((Object)val).name}; own glyph U+4F7F={flag}");
			}
			catch (Exception exception)
			{
				Plugin.Error(exception);
				isolated = null;
			}
			return isolated ?? preferred ?? TMP_Settings.defaultFontAsset;
		}
	}
	internal static class DivineHistory
	{
		private const string Marker = "tch.divinewar.history.v1";

		internal static bool IsDivine(RunAggregateData run)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Invalid comparison between Unknown and I4
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			if (run == null || (int)((BaseSaveData)run).GetRunTypeEnum() != 6)
			{
				return false;
			}
			if (((BaseSaveData)run).GetChallengeId() == "tch.divinewar.history.v1")
			{
				return true;
			}
			StartingConditions startingConditionsCopy = ((BaseSaveData)run).GetStartingConditionsCopy();
			if (string.IsNullOrEmpty(((BaseSaveData)run).GetChallengeId()) && (((StartingConditions)(ref startingConditionsCopy)).Souls == null || ((StartingConditions)(ref startingConditionsCopy)).Souls.Count == 0))
			{
				if (run.GetSouls() != null)
				{
					return run.GetSouls().Count == 0;
				}
				return true;
			}
			return false;
		}

		internal static void Mark(RunAggregateData run)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Invalid comparison between Unknown and I4
			if (Plugin.IsDivine && (int)((BaseSaveData)run).GetRunTypeEnum() == 6)
			{
				((BaseSaveData)run).SetChallengeId("tch.divinewar.history.v1");
			}
		}
	}
	[HarmonyPatch(typeof(RunAggregateData), "ResetData")]
	internal static class MarkDivineHistory
	{
		private static void Postfix(RunAggregateData __instance)
		{
			DivineHistory.Mark(__instance);
		}
	}
	[HarmonyPatch(typeof(RunHistoryEntryUI), "Set")]
	internal static class LabelDivineHistoryRow
	{
		private static void Postfix(RunHistoryEntryUI __instance)
		{
			if (DivineHistory.IsDivine(__instance.GetRunData()))
			{
				TextMeshProUGUI val = Plugin.Field<TextMeshProUGUI>(__instance, "runTypeLabel");
				if ((Object)(object)val != (Object)null)
				{
					((TMP_Text)val).text = "圣战模式";
				}
			}
		}
	}
	[HarmonyPatch(typeof(RunSummaryDetailsUI), "Set")]
	internal static class LabelDivineHistoryDetails
	{
		private static void Postfix(RunSummaryDetailsUI __instance, RunAggregateData data)
		{
			if (DivineHistory.IsDivine(data))
			{
				TextMeshProUGUI val = Plugin.Field<TextMeshProUGUI>(__instance, "runTypeLabel");
				if ((Object)(object)val != (Object)null)
				{
					((TMP_Text)val).text = "圣战模式";
				}
			}
		}
	}
	internal static class DivineHoard
	{
		private static SaveManager activeSave;

		private static string activeRun;

		private static bool active;

		private const string OfferPrefix = "tch.divinewar.hoardOffers.v1=";

		private static List<CollectableRelicData> Offers(SaveManager save, Location location)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			SaveData data = (SaveData)AccessTools.Property(typeof(SaveManager), "ActiveSaveData").GetValue(save, null);
			List<string> markers = (List<string>)AccessTools.Field(typeof(SaveData), "regionRunDefeatedBosses").GetValue(data);
			string node = location.Distance + "." + location.Branch + "." + location.Index;
			string text = "tch.divinewar.hoardOffers.v1=" + node + "=";
			return (from x in (from x in DivineHoardOfferStore.GetOrCreate(markers, text, delegate
					{
						List<DivineArtifactDefinition> list = DivineArtifactPolicy.Draw(DivineArtifacts.Eligible(save), ((BaseSaveData)data).GetSeed() + ":divine-hoard:" + node, Plugin.NodeSettings.HoardOfferCount);
						Plugin.Log("Divine hoard offers at " + node + ": " + list.Count + " / requested " + Plugin.NodeSettings.HoardOfferCount);
						return list.Select(DivineArtifacts.Id).ToList();
					}, delegate
					{
						save.Save(true, false);
					}).Substring(text.Length).Split(';')
					where DivineArtifactPolicy.IsDivine(x)
					select x).Distinct()
				select DivineArtifacts.Resolve(save.GetAllGameData(), x) into x
				where (Object)(object)x != (Object)null && !save.GetHasRelic((RelicData)(object)x) && !save.IsRelicReserved(((GameData)x).GetID())
				select x).ToList();
		}

		internal static void Start(Location location, SaveManager save, ScreenManager screens, Action callback)
		{
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Expected O, but got Unknown
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Expected O, but got Unknown
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: 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_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Expected O, but got Unknown
			if (!Plugin.IsDivine || DivineRunState.ServiceClaimed(save, location, "hoard"))
			{
				callback?.Invoke();
				return;
			}
			string run = Plugin.RunId(save);
			if (active && activeSave == save && activeRun == run && screens.GetScreenActive((ScreenName)4))
			{
				return;
			}
			List<CollectableRelicData> offered = Offers(save, location);
			if (offered.Count == 0)
			{
				screens.ShowDialog(new Data
				{
					content = "没有符合当前氏族、解锁与持有条件的神圣神器。",
					button1Text = "确定",
					callback1 = delegate
					{
						callback?.Invoke();
					}
				}, (Data)null);
				return;
			}
			active = true;
			activeSave = save;
			activeRun = run;
			string selected = null;
			bool completed = false;
			screens.OnScreenCompleted((ScreenName)4, (ScreenActiveCallback)delegate
			{
				if (!completed)
				{
					Commit();
					completed = true;
					active = false;
					activeSave = null;
					activeRun = null;
					callback?.Invoke();
				}
			});
			screens.ShowScreen((ScreenName)4, (ScreenActiveCallback)delegate(IScreen screen)
			{
				//IL_000f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0019: Expected O, but got Unknown
				RelicDraftScreen draft = (RelicDraftScreen)screen;
				draft.Setup(offered, "神圣囤积", false, (Action<RelicData>)delegate(RelicData relic)
				{
					if (!completed && Current() && !((Object)(object)relic == (Object)null) && !DivineRunState.ServiceClaimed(save, location, "hoard") && offered.Any((CollectableRelicData x) => ((GameData)x).GetID() == ((GameData)relic).GetID()) && !save.GetHasRelic(relic))
					{
						selected = ((GameData)relic).GetID();
						draft.GrantRelicAndClose();
						Commit();
					}
				});
			});
			void Commit()
			{
				if (Current() && selected != null && !DivineRunState.ServiceClaimed(save, location, "hoard"))
				{
					CollectableRelicData val = DivineArtifacts.Resolve(save.GetAllGameData(), selected);
					if (!((Object)(object)val == (Object)null) && save.GetHasRelic((RelicData)(object)val))
					{
						DivineRunState.AddShards(save, Plugin.NodeSettings.HoardShards);
						DivineRunState.ClaimService(save, location, "hoard");
						save.Save(true, false);
					}
				}
			}
			bool Current()
			{
				if (Plugin.IsDivine)
				{
					return Plugin.RunId(save) == run;
				}
				return false;
			}
		}
	}
	internal static class DivineHoardOfferStore
	{
		internal static string GetOrCreate(List<string> markers, string key, Func<List<string>> draw, Action save)
		{
			string text = markers.Find((string x) => x.StartsWith(key, StringComparison.Ordinal));
			if (text != null && text != key)
			{
				return text;
			}
			if (text != null)
			{
				markers.Remove(text);
			}
			List<string> list = draw();
			text = key + string.Join(";", list);
			if (list.Count > 0)
			{
				markers.Add(text);
				save();
			}
			return text;
		}
	}
	internal static class DivineSpellMovement
	{
		private static readonly Dictionary<CharacterState, int> Active = new Dictionary<CharacterState, int>();

		internal static bool Contains(CharacterState character)
		{
			if ((Object)(object)character != (Object)null)
			{
				return Active.ContainsKey(character);
			}
			return false;
		}

		internal static IEnumerator Wrap(IEnumerator inner, CharacterState[] targets)
		{
			CharacterState array = targets;
			foreach (CharacterState key in array)
			{
				Active[key] = ((!Active.TryGetValue(key, out var value)) ? 1 : (value + 1));
			}
			try
			{
				yield return inner;
			}
			finally
			{
				for (int j = 0; j < targets.Length; j++)
				{
					array = targets[j];
					if (--Active[array] == 0)
					{
						Active.Remove(array);
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(CardEffectBump), "ApplyEffect")]
	internal static class TrackDivineSpellMovement
	{
		private static void Postfix(CardEffectParams cardEffectParams, ref IEnumerator __result)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			CardState val = cardEffectParams?.playedCard;
			if (Plugin.IsDivine && val != null && (int)val.GetCardType() == 0 && !val.IsAnyAbility())
			{
				__result = DivineSpellMovement.Wrap(__result, cardEffectParams.targets.Where((CharacterState x) => (Object)(object)x != (Object)null).Distinct().ToArray());
			}
		}
	}
	public sealed class DivineIronCageEffect : RelicEffectAddStatusOnUnitMovedUpDown, ICharacterRoomChangeRelicEffect, IRelicEffect
	{
		public override void Initialize(RelicState state, RelicData data, RelicEffectData effect)
		{
			((RelicEffectAddStatusOnUnitMovedUpDown)this).Initialize(state, data, effect);
			base.paramRestrictions &= -5;
		}

		public bool TestCharacterRoomChangeEffect(RelicEffectParams parameters, CharacterState character, Trigger trigger, ICoreGameManagers managers)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			if (DivineSpellMovement.Contains(character))
			{
				return ((RelicEffectAddStatusOnUnitMovedUpDown)this).TestCharacterRoomChangeEffect(parameters, character, trigger, managers);
			}
			return false;
		}
	}
	internal static class DivineMinimapData
	{
		private sealed class RectSnapshot
		{
			internal RectState State;

			internal RectSnapshot(RectState state)
			{
				State = state;
			}
		}

		private sealed class ParentSnapshot
		{
			internal Transform Parent;

			internal ParentSnapshot(Transform parent)
			{
				Parent = parent;
			}
		}

		private sealed class TitleSnapshot
		{
			internal TitleState State;

			internal TitleSnapshot(TitleState state)
			{
				State = state;
			}
		}

		private struct TitleState
		{
			internal bool AutoSize;

			internal bool Wrap;

			internal float FontSize;

			internal TextOverflowModes Overflow;

			internal TitleState(TextMeshProUGUI title)
			{
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				AutoSize = ((TMP_Text)title).enableAutoSizing;
				Wrap = ((TMP_Text)title).enableWordWrapping;
				FontSize = ((TMP_Text)title).fontSize;
				Overflow = ((TMP_Text)title).overflowMode;
			}
		}

		private struct RectState
		{
			internal Vector2 AnchorMin;

			internal Vector2 AnchorMax;

			internal Vector2 Pivot;

			internal Vector2 Position;

			internal Vector2 Size;

			internal Vector3 Scale;

			internal RectState(RectTransform rect)
			{
				//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_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0013: 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_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				AnchorMin = rect.anchorMin;
				AnchorMax = rect.anchorMax;
				Pivot = rect.pivot;
				Position = rect.anchoredPosition;
				Size = rect.sizeDelta;
				Scale = ((Transform)rect).localScale;
			}
		}

		private static MapDisplayData original;

		private static MapDisplayData divine;

		private static UnknownDivineMapNode unknown;

		private static Sprite questionDisc;

		private static TextMeshProUGUI mapHeading;

		private static string originalHeading;

		private static int lastHeadingSearchFrame = -100;

		private static readonly ConditionalWeakTable<RectTransform, RectSnapshot> OriginalPositions = new ConditionalWeakTable<RectTransform, RectSnapshot>();

		private static readonly ConditionalWeakTable<MinimapBattleNode, ParentSnapshot> OriginalBattleParents = new ConditionalWeakTable<MinimapBattleNode, ParentSnapshot>();

		private static readonly ConditionalWeakTable<TextMeshProUGUI, TitleSnapshot> OriginalTitles = new ConditionalWeakTable<TextMeshProUGUI, TitleSnapshot>();

		internal static MapNodeData Unknown => (MapNodeData)(object)(unknown ?? (unknown = ScriptableObject.CreateInstance<UnknownDivineMapNode>()));

		private static RectState Remember(RectTransform rect)
		{
			return OriginalPositions.GetValue(rect, (RectTransform r) => new RectSnapshot(new RectState(r))).State;
		}

		internal static void SelectDisplayData(MinimapScreen screen)
		{
			//IL_039a: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a1: Expected O, but got Unknown
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			FieldInfo fieldInfo = AccessTools.Field(typeof(MinimapScreen), "mapDisplayData");
			object? value = fieldInfo.GetValue(screen);
			MapDisplayData val = (MapDisplayData)((value is MapDisplayData) ? value : null);
			if (!Plugin.IsDivine)
			{
				if ((Object)(object)mapHeading != (Object)null)
				{
					Localize component = ((Component)mapHeading).GetComponent<Localize>();
					if ((Ob