Decompiled source of CreaturesCatch v1.2.4

plugins/CreaturesCatch.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using CreaturesCatch.Ball;
using CreaturesCatch.Catching;
using CreaturesCatch.Loot;
using CreaturesCatch.Lore;
using CreaturesCatch.Releasing;
using CreaturesCatch.Text;
using CreaturesCatch.Workshops;
using HarmonyLib;
using Jotunn;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("CreaturesCatch")]
[assembly: AssemblyProduct("CreaturesCatch")]
[assembly: AssemblyFileVersion("1.2.4.0")]
[assembly: AssemblyCopyright("Copyright (c) 2026 AugusDogus, sz3ry")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("1.2.4.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;
		}
	}
	internal static class IsExternalInit
	{
	}
}
namespace CreaturesCatch
{
	[BepInPlugin("sz3ry.mods.CreaturesCatch", "Creatures Catch", "1.2.4")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	[SynchronizationMode(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginId = "sz3ry.mods.CreaturesCatch";

		public const string PluginVersion = "1.2.4";

		private void Awake()
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			CatchConfig.Bind(((BaseUnityPlugin)this).Config);
			RestConfig.Bind(((BaseUnityPlugin)this).Config);
			ReleaseConfig.Bind(((BaseUnityPlugin)this).Config);
			GuardianConfig.Bind(((BaseUnityPlugin)this).Config);
			LootConfig.Bind(((BaseUnityPlugin)this).Config);
			CraftingConfig.Bind(((BaseUnityPlugin)this).Config);
			WorkshopConfig.Bind(((BaseUnityPlugin)this).Config);
			AddTranslations();
			CaptureBallItem.Register();
			FragmentItems.Register();
			WorkshopPrefabs.Register();
			new Harmony("sz3ry.mods.CreaturesCatch").PatchAll(typeof(Plugin).Assembly);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Creatures Catch loaded.");
		}

		private static void AddTranslations()
		{
			CustomLocalization localization = LocalizationManager.Instance.GetLocalization();
			string text = "English";
			localization.AddTranslation(ref text, new Dictionary<string, string>(Strings.English));
			text = "Polish";
			localization.AddTranslation(ref text, new Dictionary<string, string>(Strings.Polish));
		}
	}
}
namespace CreaturesCatch.Workshops
{
	internal static class EntranceStairs
	{
		[HarmonyPatch(typeof(DungeonGenerator), "Generate", new Type[]
		{
			typeof(int),
			typeof(SpawnMode)
		})]
		private static class TrackMode
		{
			private static void Prefix(SpawnMode mode)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				EntranceStairs.mode = mode;
			}
		}

		[HarmonyPatch(typeof(DungeonGenerator), "Save")]
		private static class PlaceRune
		{
			private static readonly FieldRef<List<Room>> PlacedRooms = AccessTools.StaticFieldRefAccess<List<Room>>(AccessTools.Field(typeof(DungeonGenerator), "m_placedRooms"));

			private static void Postfix(DungeonGenerator __instance)
			{
				//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_0007: 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_000e: Invalid comparison between Unknown and I4
				//IL_0072: Unknown result type (might be due to invalid IL or missing references)
				//IL_0077: Unknown result type (might be due to invalid IL or missing references)
				//IL_007f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0084: Unknown result type (might be due to invalid IL or missing references)
				//IL_008f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0096: Unknown result type (might be due to invalid IL or missing references)
				//IL_009b: Unknown result type (might be due to invalid IL or missing references)
				//IL_009e: Unknown result type (might be due to invalid IL or missing references)
				//IL_00a4: Invalid comparison between Unknown and I4
				//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
				SpawnMode mode = EntranceStairs.mode;
				if (((int)mode != 0 && (int)mode != 2) || 1 == 0)
				{
					return;
				}
				WorkshopTheme workshopTheme = WorkshopRules.ThemeFor(((Object)__instance).name);
				if ((object)workshopTheme != null && WorkshopRules.IsWorkshop(__instance.m_generatedSeed, WorkshopConfig.Chance))
				{
					List<Room> list = PlacedRooms.Invoke();
					if (list.Count != 0)
					{
						Room start = WorkshopLevels.Entrance(list.ToArray());
						Room val = WorkshopLevels.Farthest(list, start);
						Physics.SyncTransforms();
						Vector3 position = ((Component)__instance).transform.position;
						WorkshopStairs.Spawn(WorkshopLevels.Floor(((Component)val).transform.position), ((Component)val).transform.rotation, down: true, 1, Vector3.zero, position, workshopTheme, (int)EntranceStairs.mode == 2);
						Logger.LogInfo((object)$"Workshops: {workshopTheme.GeneratorPrefix} at {position} is a workshop");
					}
				}
			}
		}

		private static SpawnMode mode;
	}
	[HarmonyPatch(typeof(DungeonGenerator), "Awake")]
	internal static class LevelDressing
	{
		private static readonly Dictionary<string, (GameObject Door, Vector3 Offset, Quaternion Rotation)?> Doors = new Dictionary<string, (GameObject, Vector3, Quaternion)?>();

		private static void Postfix(DungeonGenerator __instance)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			WorkshopTheme workshopTheme = WorkshopPrefabs.ThemeOfLevel(((Object)__instance).name);
			if ((object)workshopTheme == null)
			{
				return;
			}
			ZNetView val = default(ZNetView);
			if (((Component)__instance).TryGetComponent<ZNetView>(ref val) && val.IsValid())
			{
				int num = val.GetZDO().GetInt(WorkshopLevels.LevelDepthKey, 0);
				if (num > 1)
				{
					LevelRegistry.Register(((Component)__instance).transform.position, num, workshopTheme);
				}
			}
			AddEnvironment(__instance, workshopTheme);
			AddExitDoor(((Component)__instance).transform, workshopTheme);
		}

		private static void AddEnvironment(DungeonGenerator generator, WorkshopTheme theme)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("CC_LevelEnvironment");
			val.transform.SetParent(((Component)generator).transform, false);
			int num = LayerMask.NameToLayer("character_trigger");
			val.layer = ((num >= 0) ? num : 0);
			BoxCollider obj = val.AddComponent<BoxCollider>();
			((Collider)obj).isTrigger = true;
			obj.size = generator.m_zoneSize;
			EnvZone obj2 = val.AddComponent<EnvZone>();
			obj2.m_environment = (((Object)(object)EnvMan.instance != (Object)null && !EnvMan.instance.m_environments.Exists((EnvSetup e) => e.m_name == theme.Environment)) ? "Crypt" : theme.Environment);
			obj2.m_force = true;
		}

		private static void AddExitDoor(Transform generator, WorkshopTheme theme)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			if (!Doors.TryGetValue(theme.GeneratorPrefix, out (GameObject, Vector3, Quaternion)? value))
			{
				value = FindVanillaDoor(theme);
				Doors[theme.GeneratorPrefix] = value;
			}
			if (!value.HasValue)
			{
				return;
			}
			(GameObject, Vector3, Quaternion) valueOrDefault = value.GetValueOrDefault();
			GameObject val = Object.Instantiate<GameObject>(valueOrDefault.Item1, generator.position + generator.rotation * valueOrDefault.Item2, generator.rotation * valueOrDefault.Item3, generator);
			Component[] componentsInChildren = val.GetComponentsInChildren<Component>(true);
			foreach (Component val2 in componentsInChildren)
			{
				if ((val2 is Teleport || val2 is ZNetView) ? true : false)
				{
					Object.DestroyImmediate((Object)(object)val2);
				}
			}
			val.SetActive(true);
		}

		private static (GameObject, Vector3, Quaternion)? FindVanillaDoor(WorkshopTheme theme)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: 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_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZoneSystem.instance == (Object)null)
			{
				return null;
			}
			foreach (ZoneLocation location in ZoneSystem.instance.m_locations)
			{
				if (location.m_prefabName.StartsWith(theme.ExitLocationPrefix, StringComparison.Ordinal) && location.m_prefab.IsValid)
				{
					location.m_prefab.Load();
					GameObject asset = location.m_prefab.Asset;
					DungeonGenerator componentInChildren = asset.GetComponentInChildren<DungeonGenerator>(true);
					Teleport val = ((IEnumerable<Teleport>)asset.GetComponentsInChildren<Teleport>(true)).FirstOrDefault((Func<Teleport, bool>)((Teleport t) => ((Component)t).transform.position.y > 1000f));
					if (!((Object)(object)componentInChildren == (Object)null) && !((Object)(object)val == (Object)null))
					{
						Quaternion val2 = Quaternion.Inverse(((Component)componentInChildren).transform.rotation);
						Logger.LogInfo((object)("Workshops: exit door for " + theme.GeneratorPrefix + " from " + location.m_prefabName));
						return (((Component)val).gameObject, val2 * (((Component)val).transform.position - ((Component)componentInChildren).transform.position), val2 * ((Component)val).transform.rotation);
					}
				}
			}
			Logger.LogWarning((object)("Workshops: no exit door found for " + theme.GeneratorPrefix));
			return null;
		}
	}
	public static class LevelRegistry
	{
		[HarmonyPatch(typeof(ZNetScene), "Awake")]
		private static class ClearOnWorldStart
		{
			private static void Postfix()
			{
				Levels.Clear();
			}
		}

		private static readonly Dictionary<Vector2i, (int Depth, WorkshopTheme Theme)> Levels = new Dictionary<Vector2i, (int, WorkshopTheme)>();

		public static void Register(Vector3 generatorPosition, int depth, WorkshopTheme theme)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: 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)
			Dictionary<Vector2i, (int Depth, WorkshopTheme Theme)> levels = Levels;
			Vector2s zone = ZoneSystem.GetZone(generatorPosition);
			levels[((Vector2s)(ref zone)).ToVector2i()] = (depth, theme);
		}

		public static bool Contains(Vector2i zone)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			return Levels.ContainsKey(zone);
		}

		public static bool TryGet(Vector3 position, out int depth, out WorkshopTheme theme)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: 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_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			if (position.y > 3000f)
			{
				Dictionary<Vector2i, (int Depth, WorkshopTheme Theme)> levels = Levels;
				Vector2s zone = ZoneSystem.GetZone(position);
				if (levels.TryGetValue(((Vector2s)(ref zone)).ToVector2i(), out (int, WorkshopTheme) value))
				{
					(depth, theme) = value;
					return true;
				}
			}
			depth = 0;
			theme = null;
			return false;
		}
	}
	public static class RewardBall
	{
		public static BallContents Contents(string prefab)
		{
			return new BallContents(prefab, 3, 1f, 1f);
		}
	}
	public enum StairsAction
	{
		Teleport,
		Create,
		Wait,
		Refuse
	}
	public static class StairsRequests
	{
		public static StairsAction Decide(bool isDown, bool hasTarget, bool isOwner, bool creating)
		{
			if (hasTarget)
			{
				return StairsAction.Teleport;
			}
			if (!isDown)
			{
				return StairsAction.Refuse;
			}
			if (!isOwner || creating)
			{
				return StairsAction.Wait;
			}
			return StairsAction.Create;
		}

		public static bool ShowsLore(bool isDown, int depth, bool alreadyRead)
		{
			if (isDown && depth == 1)
			{
				return !alreadyRead;
			}
			return false;
		}
	}
	public static class StairsScreen
	{
		[HarmonyPatch(typeof(Hud), "UpdateBlackScreen")]
		private static class SwapTeleportScreen
		{
			private static void Postfix(Hud __instance)
			{
				Player localPlayer = Player.m_localPlayer;
				bool flag = _text != null && (Object)(object)localPlayer != (Object)null && ((Character)localPlayer).IsTeleporting() && localPlayer.ShowTeleportAnimation();
				if (_text != null && !flag && Time.time - _since > 1f)
				{
					_text = null;
				}
				if (!flag)
				{
					if ((Object)(object)_overlay != (Object)null)
					{
						_overlay.SetActive(false);
					}
					return;
				}
				if ((Object)(object)_overlay == (Object)null)
				{
					Build(__instance);
				}
				if (!((Object)(object)_overlay == (Object)null))
				{
					__instance.m_teleportingProgress.SetActive(false);
					_overlay.SetActive(true);
					if ((Object)(object)_label != (Object)null)
					{
						_label.text = _text;
					}
				}
			}
		}

		private static string? _text;

		private static float _since;

		private static GameObject? _overlay;

		private static TMP_Text? _label;

		public static void Show(string text)
		{
			_text = text;
			_since = Time.time;
		}

		private static void Build(Hud hud)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			Texture2D val = FragmentItems.LoadTexture("CreaturesCatch.stairs_loading.jpg");
			if (!((Object)(object)val == (Object)null))
			{
				_overlay = new GameObject("CC_StairsScreen", new Type[1] { typeof(RectTransform) });
				RectTransform val2 = (RectTransform)_overlay.transform;
				((Transform)val2).SetParent(((Component)hud.m_loadingScreen).transform, false);
				val2.anchorMin = Vector2.zero;
				val2.anchorMax = Vector2.one;
				val2.offsetMin = Vector2.zero;
				val2.offsetMax = Vector2.zero;
				Image obj = _overlay.AddComponent<Image>();
				obj.sprite = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
				obj.preserveAspect = false;
				GameObject obj2 = Object.Instantiate<GameObject>(((Component)hud.m_loadingTip).gameObject, (Transform)(object)val2, false);
				obj2.SetActive(true);
				RectTransform val3 = (RectTransform)obj2.transform;
				val3.anchorMin = new Vector2(0f, 0f);
				val3.anchorMax = new Vector2(1f, 0f);
				val3.pivot = new Vector2(0.5f, 0f);
				val3.anchoredPosition = new Vector2(0f, 80f);
				val3.sizeDelta = new Vector2(0f, 80f);
				_label = obj2.GetComponent<TMP_Text>();
				_label.alignment = (TextAlignmentOptions)514;
				_label.fontSize = 42f;
			}
		}
	}
	internal static class WorkshopBottom
	{
		[HarmonyPatch(typeof(Character), "SetupMaxHealth")]
		private static class DoubleHealth
		{
			private static void Prefix(Character __instance, out bool __state)
			{
				__state = __instance.GetHealth() >= __instance.GetMaxHealth();
			}

			private static void Postfix(Character __instance, bool __state)
			{
				ZNetView val = default(ZNetView);
				if (((Component)__instance).TryGetComponent<ZNetView>(ref val) && val.IsValid() && val.GetZDO().GetBool(GuardianKey, false))
				{
					__instance.SetMaxHealth(__instance.GetMaxHealth() * 2f);
					__instance.SetHealth(GuardianRules.HealthAfterScaling(__state, __instance.GetHealth(), __instance.GetMaxHealth()));
				}
			}
		}

		internal static readonly int GuardianKey = StringExtensionMethods.GetStableHashCode("cc_workshop_guardian");

		private const string FallbackChest = "TreasureChest_blackforest";

		private static readonly Dictionary<string, string> Chests = new Dictionary<string, string>
		{
			["ForestCrypt"] = "TreasureChest_forestcrypt",
			["SunkenCrypt"] = "TreasureChest_sunkencrypt",
			["Cave"] = "TreasureChest_mountaincave",
			["DvergrTown"] = "TreasureChest_dvergrtown"
		};

		public static void Furnish(Room hall, WorkshopTheme theme, int seed)
		{
			//IL_0006: 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_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: 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_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = WorkshopLevels.Floor(((Component)hall).transform.position);
			SpawnGuardian(theme, position, ((Component)hall).transform.rotation);
			SpawnChest(theme, seed, WorkshopLevels.Floor(((Component)hall).transform.position - ((Component)hall).transform.forward * 3f), ((Component)hall).transform.rotation);
		}

		private static void SpawnGuardian(WorkshopTheme theme, Vector3 position, Quaternion rotation)
		{
			//IL_0031: 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)
			GameObject val = WorkshopPrefabs.Prefab(theme.Guardian);
			if ((Object)(object)val == (Object)null)
			{
				Logger.LogError((object)("Workshops: guardian " + theme.Guardian + " not found"));
				return;
			}
			GameObject val2 = Object.Instantiate<GameObject>(val, position, rotation);
			Character val3 = default(Character);
			ZNetView val4 = default(ZNetView);
			if (val2.TryGetComponent<Character>(ref val3) && val2.TryGetComponent<ZNetView>(ref val4))
			{
				val4.GetZDO().Set(GuardianKey, true);
				val3.SetLevel(3);
				val3.SetHealth(val3.GetMaxHealth());
			}
		}

		private static void SpawnChest(WorkshopTheme theme, int seed, Vector3 position, Quaternion rotation)
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			string value;
			GameObject val = WorkshopPrefabs.Prefab(Chests.TryGetValue(theme.GeneratorPrefix, out value) ? value : "TreasureChest_blackforest");
			if ((Object)(object)val == (Object)null)
			{
				val = WorkshopPrefabs.Prefab("TreasureChest_blackforest");
			}
			GameObject val2 = WorkshopPrefabs.Prefab("CC_CaptureBall");
			ItemDrop val3 = default(ItemDrop);
			Container val4 = default(Container);
			if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || !val2.TryGetComponent<ItemDrop>(ref val3))
			{
				Logger.LogError((object)"Workshops: Sigrun's chest or the ball prefab not found");
			}
			else if (Object.Instantiate<GameObject>(val, position, rotation).TryGetComponent<Container>(ref val4))
			{
				ItemData val5 = val3.m_itemData.Clone();
				val5.m_dropPrefab = val2;
				BallData.Write(val5.m_customData, RewardBall.Contents(WorkshopRules.RewardPrefab(theme, seed)));
				if (!val4.GetInventory().AddItem(val5))
				{
					ItemDrop.DropItem(val5, 1, position + Vector3.up * 1.5f, rotation);
					Logger.LogWarning((object)"Workshops: Sigrun's chest was full, reward ball dropped beside it");
				}
			}
		}
	}
	public static class WorkshopConfig
	{
		private const float DefaultChance = 15f;

		private static ConfigEntry<float>? chance;

		public static float Chance => chance?.Value ?? 15f;

		public static void Bind(ConfigFile config)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			chance = config.Bind<float>("Workshops", "Chance", 15f, new ConfigDescription("Percent chance that a newly generated dungeon is one of Sigrun's workshops, with levels below it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
		}
	}
	public static class WorkshopLevels
	{
		internal static readonly int LevelDepthKey = StringExtensionMethods.GetStableHashCode("cc_level_depth");

		internal static readonly int LevelThemeKey = StringExtensionMethods.GetStableHashCode("cc_level_theme");

		private static readonly List<ZDO> SectorObjects = new List<ZDO>();

		private static readonly HashSet<SectorIndex> Visited = new HashSet<SectorIndex>();

		private static readonly Action<ZDOMan, Vector2s, List<ZDO>, HashSet<SectorIndex>>? FindObjects;

		public static Vector3 Create(WorkshopTheme theme, Vector3 root, int depth, Vector3 returnPoint)
		{
			//IL_000c: 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_0061: 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)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0189: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: 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_0193: 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_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: Unknown result type (might be due to invalid IL or missing references)
			//IL_0235: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = WorkshopPrefabs.Prefab(WorkshopPrefabs.GeneratorName(theme));
			int num = WorkshopRules.LevelSeed((int)root.x, (int)root.z, depth);
			if (!((Object)(object)val == (Object)null))
			{
				Vector3? val2 = FindPosition(num, depth);
				if (val2.HasValue)
				{
					Vector3 valueOrDefault = val2.GetValueOrDefault();
					GameObject obj = Object.Instantiate<GameObject>(val, valueOrDefault, Quaternion.identity);
					ZDO zDO = obj.GetComponent<ZNetView>().GetZDO();
					zDO.Set(LevelDepthKey, depth, false);
					zDO.Set(LevelThemeKey, theme.GeneratorPrefix);
					LevelRegistry.Register(valueOrDefault, depth, theme);
					DungeonGenerator component = obj.GetComponent<DungeonGenerator>();
					if (!WorkshopRules.HasStairsDown(depth))
					{
						component.m_minRooms = 9;
						component.m_maxRooms = 12;
					}
					component.Generate(num, (SpawnMode)0);
					Physics.SyncTransforms();
					Room[] componentsInChildren = obj.GetComponentsInChildren<Room>();
					if (componentsInChildren.Length == 0)
					{
						Logger.LogError((object)$"Workshops: level {depth} at {valueOrDefault} has no rooms");
						return Vector3.zero;
					}
					Room val3 = Entrance(componentsInChildren);
					Room val4 = Farthest(componentsInChildren, val3);
					Vector3 result = Floor(((Component)val3).transform.position) + Vector3.up * 0.3f;
					Vector3 position = ((Component)val3.GetEntrance()).transform.position;
					Vector3 val5 = ((Component)val3).transform.position - position;
					val5.y = 0f;
					Quaternion val6 = ((((Vector3)(ref val5)).sqrMagnitude > 0.01f) ? Quaternion.LookRotation(((Vector3)(ref val5)).normalized) : ((Component)val3).transform.rotation);
					WorkshopStairs.Spawn(Floor(position + val6 * Vector3.forward), val6, down: false, depth, returnPoint, root, theme);
					if (WorkshopRules.HasStairsDown(depth))
					{
						WorkshopStairs.Spawn(Floor(((Component)val4).transform.position), ((Component)val4).transform.rotation, down: true, depth, Vector3.zero, root, theme);
					}
					else
					{
						WorkshopBottom.Furnish(val4, theme, num);
					}
					Logger.LogInfo((object)$"Workshops: level {depth} of {theme.GeneratorPrefix} at {valueOrDefault}, {componentsInChildren.Length} rooms");
					return result;
				}
			}
			Logger.LogError((object)$"Workshops: no place for level {depth} of {theme.GeneratorPrefix}");
			return Vector3.zero;
		}

		internal static Room Entrance(Room[] rooms)
		{
			Room val = ((IEnumerable<Room>)rooms).FirstOrDefault((Func<Room, bool>)((Room r) => r.m_entrance));
			if (!((Object)(object)val != (Object)null))
			{
				return rooms[0];
			}
			return val;
		}

		internal static Room Farthest(IEnumerable<Room> rooms, Room start)
		{
			return rooms.Where((Room r) => !r.m_endCap && (Object)(object)r != (Object)(object)start).OrderByDescending(delegate(Room r)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				Vector3 val = ((Component)r).transform.position - ((Component)start).transform.position;
				return ((Vector3)(ref val)).sqrMagnitude;
			}).DefaultIfEmpty(start)
				.First();
		}

		internal static Vector3 Floor(Vector3 point)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: 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_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			int mask = LayerMask.GetMask(new string[4] { "Default", "static_solid", "Default_small", "piece" });
			RaycastHit val = default(RaycastHit);
			if (!Physics.Raycast(point + Vector3.up * 0.5f, Vector3.down, ref val, 8f, mask))
			{
				return point;
			}
			return ((RaycastHit)(ref val)).point;
		}

		private static Vector3? FindPosition(int seed, int depth)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			foreach (var item3 in WorkshopRules.RingCandidates(seed))
			{
				float item = item3.X;
				float item2 = item3.Z;
				Vector2s zone = ZoneSystem.GetZone(new Vector3(item, 0f, item2));
				string text = WorkshopRules.ZoneKey(zone.x, zone.y);
				if (!ZoneSystem.instance.GetGlobalKey(text) && !ZoneSystem.instance.m_locationInstances.ContainsKey(zone) && !LevelRegistry.Contains(((Vector2s)(ref zone)).ToVector2i()) && !HasLevelObjects(zone))
				{
					ZoneSystem.instance.SetGlobalKey(text);
					Vector3 zonePos = ZoneSystem.GetZonePos(zone);
					return new Vector3(zonePos.x, WorkshopRules.Altitude(depth), zonePos.z);
				}
			}
			return null;
		}

		private static bool HasLevelObjects(Vector2s zone)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			if (FindObjects == null)
			{
				return false;
			}
			SectorObjects.Clear();
			Visited.Clear();
			FindObjects(ZDOMan.instance, zone, SectorObjects, Visited);
			return SectorObjects.Any((ZDO zdo) => zdo.GetPosition().y > 3000f);
		}

		static WorkshopLevels()
		{
			MethodInfo methodInfo = AccessTools.Method(typeof(ZDOMan), "FindObjects", (Type[])null, (Type[])null);
			FindObjects = (((object)methodInfo != null) ? AccessTools.MethodDelegate<Action<ZDOMan, Vector2s, List<ZDO>, HashSet<SectorIndex>>>(methodInfo, (object)null, true) : null);
		}
	}
	internal static class WorkshopLoot
	{
		public static string Biome(Vector3 position)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			if (!LevelRegistry.TryGet(position, out int _, out WorkshopTheme theme))
			{
				return ((object)WorldGenerator.instance.GetBiome(position)/*cast due to .constrained prefix*/).ToString();
			}
			return theme.Biome;
		}

		public static int Depth(Vector3 position)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			if (!LevelRegistry.TryGet(position, out int depth, out WorkshopTheme _))
			{
				return 1;
			}
			return depth;
		}
	}
	public static class WorkshopPrefabs
	{
		public const string StairsName = "CC_SigrunStairs";

		public const string GeneratorPrefix = "CC_DG_";

		private const string StairsSource = "Runestone_BlackForest";

		public static string GeneratorName(WorkshopTheme theme)
		{
			return "CC_DG_" + theme.GeneratorPrefix;
		}

		public static WorkshopTheme? ThemeOfLevel(string generatorName)
		{
			if (!generatorName.StartsWith("CC_DG_", StringComparison.Ordinal))
			{
				return null;
			}
			return WorkshopRules.ThemeFor(generatorName.Substring(3));
		}

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

		public static GameObject? Prefab(string name)
		{
			if (!((Object)(object)ZNetScene.instance != (Object)null))
			{
				return null;
			}
			return ZNetScene.instance.GetPrefab(name);
		}

		private static void AddPrefabs()
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Expected O, but got Unknown
			PrefabManager.OnVanillaPrefabsAvailable -= AddPrefabs;
			ZNetView val2 = default(ZNetView);
			foreach (WorkshopTheme theme in WorkshopRules.Themes)
			{
				GameObject val = PrefabManager.Instance.CreateClonedPrefab(GeneratorName(theme), "DG_" + theme.GeneratorPrefix);
				if ((Object)(object)val == (Object)null || !val.TryGetComponent<ZNetView>(ref val2))
				{
					Logger.LogError((object)("Workshops: generator DG_" + theme.GeneratorPrefix + " not found"));
					continue;
				}
				val2.m_persistent = true;
				PrefabManager.Instance.AddPrefab(new CustomPrefab(val, false));
				foreach (string reward in theme.Rewards)
				{
					WarnIfMissing(reward);
				}
				WarnIfMissing(theme.Guardian);
			}
			AddStairs();
		}

		private static void AddStairs()
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			GameObject val = PrefabManager.Instance.CreateClonedPrefab("CC_SigrunStairs", "Runestone_BlackForest");
			if ((Object)(object)val == (Object)null)
			{
				Logger.LogError((object)"Workshops: Runestone_BlackForest not found");
				return;
			}
			Component[] componentsInChildren = val.GetComponentsInChildren<Component>(true);
			foreach (Component val2 in componentsInChildren)
			{
				if ((val2 is RuneStone || val2 is StaticPhysics || val2 is Rigidbody) ? true : false)
				{
					Object.DestroyImmediate((Object)(object)val2);
				}
			}
			ZNetView val3 = default(ZNetView);
			if (!val.TryGetComponent<ZNetView>(ref val3))
			{
				val3 = val.AddComponent<ZNetView>();
			}
			val3.m_persistent = true;
			Transform transform = val.transform;
			transform.localScale *= 0.4f;
			val.AddComponent<WorkshopStairs>();
			PrefabManager.Instance.AddPrefab(new CustomPrefab(val, false));
		}

		private static void WarnIfMissing(string prefab)
		{
			if ((Object)(object)PrefabManager.Instance.GetPrefab(prefab) == (Object)null)
			{
				Logger.LogError((object)("Workshops: creature prefab " + prefab + " not found"));
			}
		}
	}
	public sealed record WorkshopTheme(string GeneratorPrefix, string Biome, string Guardian, IReadOnlyList<string> Rewards, string ExitLocationPrefix, string Environment);
	public static class WorkshopRules
	{
		public const int MaxDepth = 5;

		public const float LevelAltitude = 4000f;

		public const float RingRadius = 9200f;

		public const int BottomRooms = 10;

		private const int RingPoints = 64;

		public static IReadOnlyList<WorkshopTheme> Themes { get; } = new <>z__ReadOnlyArray<WorkshopTheme>(new WorkshopTheme[4]
		{
			new WorkshopTheme("ForestCrypt", "BlackForest", "Greydwarf_Elite", new <>z__ReadOnlyArray<string>(new string[2] { "Troll", "Greydwarf_Shaman" }), "Crypt", "Crypt"),
			new WorkshopTheme("SunkenCrypt", "Swamp", "Abomination", new <>z__ReadOnlyArray<string>(new string[2] { "Abomination", "Draugr_Elite" }), "SunkenCrypt", "SunkenCrypt"),
			new WorkshopTheme("Cave", "Mountain", "Fenring_Cultist", new <>z__ReadOnlyArray<string>(new string[2] { "StoneGolem", "Ulv" }), "MountainCave", "Caves"),
			new WorkshopTheme("DvergrTown", "Mistlands", "SeekerBrute", new <>z__ReadOnlyArray<string>(new string[2] { "SeekerBrute", "Gjall" }), "Mistlands_DvergrTown", "InfectedMine")
		});

		public static IReadOnlyCollection<string> TooTallIndoors { get; } = new HashSet<string> { "Troll", "Bjorn", "Unbjorn" };

		public static WorkshopTheme? ThemeFor(string generatorName)
		{
			foreach (WorkshopTheme theme in Themes)
			{
				string text = "DG_" + theme.GeneratorPrefix;
				if (generatorName == text || generatorName == text + "(Clone)")
				{
					return theme;
				}
			}
			return null;
		}

		public static bool IsWorkshop(int dungeonSeed, float chancePercent)
		{
			if (float.IsNaN(chancePercent) || chancePercent <= 0f)
			{
				return false;
			}
			if (!(chancePercent >= 100f))
			{
				return (float)(Mix(dungeonSeed) % 10000) < chancePercent * 100f;
			}
			return true;
		}

		public static int Level(int depth)
		{
			return Math.Clamp(depth, 1, 3);
		}

		public static float ExtraSpawnChance(int depth)
		{
			return Math.Clamp(0.25f * (float)(depth - 2), 0f, 1f);
		}

		public static float BallChestChance(float biomeChance, int depth)
		{
			if (!float.IsNaN(biomeChance))
			{
				return Math.Clamp(biomeChance * (float)depth, 0f, 1f);
			}
			return 0f;
		}

		public static int ExtraLootRolls(int depth)
		{
			return Math.Max(0, depth - 1);
		}

		public static float Altitude(int depth)
		{
			return 4000f - (float)(Math.Max(2, depth) - 2) * 150f;
		}

		public static bool HasStairsDown(int depth)
		{
			return depth < 5;
		}

		public static int LevelSeed(int rootX, int rootZ, int depth)
		{
			return (rootX * 73856093) ^ (rootZ * 19349663) ^ (depth * 83492791);
		}

		public static IEnumerable<(float X, float Z)> RingCandidates(int seed)
		{
			double start = (double)(Mix(seed) % 3600) / 10.0;
			for (int i = 0; i < 64; i++)
			{
				double num = (start + (double)i * 360.0 / 64.0) * Math.PI / 180.0;
				yield return (X: (float)(Math.Cos(num) * 9200.0), Z: (float)(Math.Sin(num) * 9200.0));
			}
		}

		public static string ZoneKey(int x, int y)
		{
			return "cc_workshop_zone_" + x.ToString(CultureInfo.InvariantCulture) + "_" + y.ToString(CultureInfo.InvariantCulture);
		}

		public static string RewardPrefab(WorkshopTheme theme, int seed)
		{
			return theme.Rewards[(int)(Mix(seed) % (uint)theme.Rewards.Count)];
		}

		private static uint Mix(int value)
		{
			int num = (value ^ (value >>> 16)) * -2048144789;
			int num2 = (num ^ (num >>> 13)) * -1028477387;
			return (uint)(num2 ^ (num2 >>> 16));
		}
	}
	[HarmonyPatch(typeof(CreatureSpawner), "Spawn")]
	internal static class WorkshopSpawns
	{
		private static void Postfix(CreatureSpawner __instance, ZNetView __result)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			Character val = default(Character);
			if ((Object)(object)__result == (Object)null || SpawnSystem.m_nospawn || !LevelRegistry.TryGet(((Component)__instance).transform.position, out int depth, out WorkshopTheme _) || !((Component)__result).TryGetComponent<Character>(ref val))
			{
				return;
			}
			int num = Mathf.Max(val.GetLevel(), WorkshopRules.Level(depth));
			if (num != val.GetLevel())
			{
				val.SetLevel(num);
			}
			if (!(Random.value >= WorkshopRules.ExtraSpawnChance(depth)))
			{
				Vector3 val2 = Quaternion.Euler(0f, Random.Range(0f, 360f), 0f) * (Vector3.forward * 1.5f);
				Character val3 = default(Character);
				if (Object.Instantiate<GameObject>(__instance.m_creaturePrefab, ((Component)__result).transform.position + val2, ((Component)__result).transform.rotation).TryGetComponent<Character>(ref val3) && num > 1)
				{
					val3.SetLevel(num);
				}
			}
		}
	}
	public sealed class WorkshopStairs : MonoBehaviour, Hoverable, Interactable
	{
		private const string CreateRpc = "cc_stairs_create";

		private const float WaitSeconds = 5f;

		private const string LoreTopic = "$cc_workshop_topic";

		private const string LoreText = "$cc_workshop_text";

		internal static readonly int KindKey = StringExtensionMethods.GetStableHashCode("cc_stairs_kind");

		internal static readonly int DepthKey = StringExtensionMethods.GetStableHashCode("cc_stairs_depth");

		internal static readonly int TargetKey = StringExtensionMethods.GetStableHashCode("cc_stairs_target");

		internal static readonly int RootKey = StringExtensionMethods.GetStableHashCode("cc_stairs_root");

		internal static readonly int ThemeKey = StringExtensionMethods.GetStableHashCode("cc_stairs_theme");

		internal const int Down = 0;

		internal const int Up = 1;

		private ZNetView? view;

		private bool creating;

		public static void Spawn(Vector3 position, Quaternion rotation, bool down, int depth, Vector3 target, Vector3 root, WorkshopTheme theme, bool ghost = false)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = WorkshopPrefabs.Prefab("CC_SigrunStairs");
			if (!((Object)(object)val == (Object)null))
			{
				if (ghost)
				{
					ZNetView.StartGhostInit();
				}
				GameObject val2 = Object.Instantiate<GameObject>(val, position, rotation);
				ZDO zDO = val2.GetComponent<ZNetView>().GetZDO();
				zDO.Set(KindKey, (!down) ? 1 : 0, false);
				zDO.Set(DepthKey, depth, false);
				zDO.Set(TargetKey, target);
				zDO.Set(RootKey, root);
				zDO.Set(ThemeKey, theme.GeneratorPrefix);
				if (ghost)
				{
					ZNetView.FinishGhostInit();
					Object.Destroy((Object)(object)val2);
				}
			}
		}

		private void Awake()
		{
			view = ((Component)this).GetComponent<ZNetView>();
			if (!((Object)(object)view == (Object)null) && view.IsValid())
			{
				view.Register("cc_stairs_create", (Action<long>)RPC_Create);
				if (view.GetZDO().GetInt(KindKey, 0) == 1)
				{
					AddEntranceWall();
				}
			}
		}

		public string GetHoverName()
		{
			return GameText.Localize("cc_stairs_name");
		}

		public float GetHoverOffset()
		{
			return 0f;
		}

		public string GetHoverText()
		{
			if ((Object)(object)view == (Object)null || !view.IsValid())
			{
				return "";
			}
			ZDO zDO = view.GetZDO();
			int num = zDO.GetInt(DepthKey, 0);
			return ((zDO.GetInt(KindKey, 0) == 0) ? GameText.Localize("cc_stairs_down", (num + 1).ToString(CultureInfo.InvariantCulture)) : GameText.Localize("cc_stairs_up", (num - 1).ToString(CultureInfo.InvariantCulture))) + "\n" + Localization.instance.Localize("[<color=yellow><b>$KEY_Use</b></color>] ") + GameText.Localize("cc_stairs_use");
		}

		public bool Interact(Humanoid user, bool hold, bool alt)
		{
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			if (hold || (Object)(object)user != (Object)(object)Player.m_localPlayer || (Object)(object)view == (Object)null || !view.IsValid())
			{
				return false;
			}
			ZDO zDO = view.GetZDO();
			bool isDown = zDO.GetInt(KindKey, 0) == 0;
			Player val = (Player)(object)((user is Player) ? user : null);
			if (val != null && StairsRequests.ShowsLore(isDown, zDO.GetInt(DepthKey, 0), val.GetKnownTexts().Any((KeyValuePair<string, string> t) => t.Key == "$cc_workshop_topic")))
			{
				if ((Object)(object)TextViewer.instance != (Object)null)
				{
					TextViewer.instance.ShowText((Style)0, "$cc_workshop_topic", "$cc_workshop_text", false);
				}
				val.AddKnownText("$cc_workshop_topic", "$cc_workshop_text");
				return true;
			}
			switch (StairsRequests.Decide(isDown, Target() != Vector3.zero, view.IsOwner(), creating))
			{
			case StairsAction.Teleport:
				Go(user);
				break;
			case StairsAction.Create:
				CreateNext();
				if (Target() != Vector3.zero)
				{
					Go(user);
				}
				else
				{
					((Character)user).Message((MessageType)2, GameText.Localize("cc_stairs_blocked"), 0, (Sprite)null, false);
				}
				break;
			case StairsAction.Wait:
				if (!view.IsOwner())
				{
					view.InvokeRPC("cc_stairs_create", Array.Empty<object>());
				}
				((MonoBehaviour)this).StartCoroutine(GoWhenCreated(user));
				break;
			default:
				((Character)user).Message((MessageType)2, GameText.Localize("cc_stairs_blocked"), 0, (Sprite)null, false);
				break;
			}
			return true;
		}

		public bool UseItem(Humanoid user, ItemData item)
		{
			return false;
		}

		private Vector3 Target()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)view != (Object)null) || !view.IsValid())
			{
				return Vector3.zero;
			}
			return view.GetZDO().GetVec3(TargetKey, Vector3.zero);
		}

		private void RPC_Create(long sender)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)view != (Object)null && view.IsOwner() && Target() == Vector3.zero && !creating)
			{
				CreateNext();
			}
		}

		private void CreateNext()
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//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_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: 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)
			ZDO zdo = view.GetZDO();
			WorkshopTheme workshopTheme = WorkshopRules.Themes.FirstOrDefault((WorkshopTheme t) => t.GeneratorPrefix == zdo.GetString(ThemeKey, ""));
			if (workshopTheme == null)
			{
				return;
			}
			creating = true;
			try
			{
				Vector3 returnPoint = WorkshopLevels.Floor(((Component)this).transform.position + ((Component)this).transform.forward * 1.5f) + Vector3.up * 0.3f;
				Vector3 val = WorkshopLevels.Create(workshopTheme, zdo.GetVec3(RootKey, ((Component)this).transform.position), zdo.GetInt(DepthKey, 0) + 1, returnPoint);
				if (val != Vector3.zero)
				{
					zdo.Set(TargetKey, val);
				}
			}
			finally
			{
				creating = false;
			}
		}

		private IEnumerator GoWhenCreated(Humanoid user)
		{
			float until = Time.time + 5f;
			while (Time.time < until)
			{
				if (Target() != Vector3.zero)
				{
					Go(user);
					yield break;
				}
				yield return null;
			}
			((Character)user).Message((MessageType)2, GameText.Localize("cc_stairs_blocked"), 0, (Sprite)null, false);
		}

		private void Go(Humanoid user)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			ZDO zDO = view.GetZDO();
			int num = zDO.GetInt(DepthKey, 0);
			StairsScreen.Show((zDO.GetInt(KindKey, 0) == 0) ? GameText.Localize("cc_stairs_descending", (num + 1).ToString(CultureInfo.InvariantCulture)) : GameText.Localize("cc_stairs_returning", (num - 1).ToString(CultureInfo.InvariantCulture)));
			((Character)user).TeleportTo(Target(), ((Component)user).transform.rotation, true);
		}

		private void AddEntranceWall()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: 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_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("CC_EntranceWall");
			val.transform.SetParent(((Component)this).transform, false);
			int num = LayerMask.NameToLayer("static_solid");
			val.layer = ((num >= 0) ? num : 0);
			Vector3 lossyScale = ((Component)this).transform.lossyScale;
			val.transform.localPosition = new Vector3(0f, 3f / lossyScale.y, -0.8f / lossyScale.z);
			val.AddComponent<BoxCollider>().size = new Vector3(8f / lossyScale.x, 8f / lossyScale.y, 0.4f / lossyScale.z);
		}
	}
}
namespace CreaturesCatch.Text
{
	internal static class GameText
	{
		public static string Localize(string key, params string[] words)
		{
			if (Localization.instance == null)
			{
				return Strings.Format(Strings.English, key, words);
			}
			return Strings.Insert(Localization.instance.Localize("$" + key), words);
		}

		public static string Name(string name)
		{
			if (Localization.instance == null)
			{
				return name;
			}
			return Localization.instance.Localize(name);
		}
	}
	public delegate string Localizer(string key, params string[] words);
	public static class Strings
	{
		public static IReadOnlyDictionary<string, string> English { get; } = new Dictionary<string, string>
		{
			["item_cc_captureball"] = "Capture Ball",
			["item_cc_captureball_desc"] = "Throw at a creature to catch it. Throw a full ball to release it.",
			["cc_tooltip_contains"] = "Contains: $1",
			["cc_tooltip_contains_named"] = "Contains: $1 ($2)",
			["cc_tooltip_stars"] = "Stars: $1",
			["cc_tooltip_health"] = "Health: $1%",
			["cc_tooltip_ready"] = "Ready in: $1 min",
			["cc_hover_resting"] = "Resting",
			["cc_hover_needs_warmth"] = "Needs warmth and a roof",
			["cc_msg_caught"] = "Caught $1",
			["cc_msg_packed"] = "Packed $1",
			["cc_msg_broke_free"] = "$1 broke free",
			["cc_msg_broke_free_shattered"] = "$1 broke free and the ball shattered",
			["cc_msg_too_healthy"] = "$1 is too strong to catch (weaken it below $2% health)",
			["cc_msg_boss"] = "Bosses cannot be caught",
			["cc_msg_player"] = "Players cannot be caught",
			["cc_msg_summoned"] = "Summoned creatures cannot be caught",
			["cc_msg_excluded"] = "$1 cannot be caught",
			["cc_msg_gone"] = "Someone else got there first",
			["cc_msg_refuses"] = "$1 refuses to leave the ball (ready in $2 min)",
			["cc_msg_guardian_limit"] = "Too many guardians nearby (max $1)",
			["item_cc_fragment1"] = "Sigrun's Journal, Fragment I",
			["item_cc_fragment2"] = "Sigrun's Journal, Fragment II",
			["item_cc_fragment3"] = "Sigrun's Journal, Fragment III",
			["item_cc_fragment4"] = "Sigrun's Journal, Fragment IV",
			["item_cc_fragment1_desc"] = "A scorched page of Sigrun's journal, covered in runes. Page 1 / 4; the entry breaks off mid-sentence. Use it to read.",
			["item_cc_fragment2_desc"] = "A scorched page of Sigrun's journal, covered in runes. Page 2 / 4; the entry breaks off mid-sentence. Use it to read.",
			["item_cc_fragment3_desc"] = "A scorched page of Sigrun's journal, covered in runes. Page 3 / 4; the entry breaks off mid-sentence. Use it to read.",
			["item_cc_fragment4_desc"] = "A scorched page of Sigrun's journal, covered in runes. Page 4 / 4, the last. Use it to read.",
			["cc_fragment1_text"] = "I write so I do not go mad. No one answers here, so I talk to this page. I was the Great Galdrmaster. I bound runes with song, and when I bound with them what must never be bound, the gods took my name and cast me down into the tenth world. I survived the first nights with a stick in my hand and my back to the fire. The beasts of the Forsaken came every dusk. When I had no strength left to fight, I sang the last binding rune I remembered and sealed in glass the thing that leapt at me. So the first orb was made. Every one since costs me a piece of my old power. I seal these pages with a rune of fire. No one should read them twice.",
			["cc_fragment2_text"] = "The orbs are fickle. Today a draugr laughed in my face and the glass burst in my hand. A weak soul yields easily; a strong one shatters the glass from within. Yesterday I saw a wolf, barely alive, walk into an orb on its own, like into a den. I write it down so I do not forget: a beast in full strength cannot be caught. First it must be worn down and wounded, brought to the edge. Only when its strength fades does the binding rune have something to hold. How many orbs have I lost? More than I have fingers. And I have fewer fingers every day.",
			["cc_fragment3_text"] = "I released Brunn, the troll I caught long ago among the pines. He stood where I freed him and did not give a single step, though the Fulings came in waves. Freed souls guard the place where they were released, but outside the orb they cannot heal. Brunn bled for three nights and not one wound closed. I took him back into the orb and laid it by the fire, under the roof of my hut. By morning he was whole. Warmth and a roof do for an orb what a mother does for a child. I will tell no one, for there is no one to tell. Only Brunn listens.",
			["cc_fragment4_text"] = "I have met the Dvergr. They know more of runes than they will say, but for an orb with a wolf inside they showed me their black cores, heavy and warm as hearts. In a core the power of a rune does not escape; it circles like a held breath. At the Galdr table I joined a core, ooze and crystals, and an orb was born without a drop of my power. But a core without the binding rune is only a stone. Without the song from the first page, the patience from the second and the fire from the third, none of it would hold. I no longer have to pay with myself for every glass. And yet something is wrong. Every orb I have made whispers. Lately I hear my own name in them.",
			["cc_fragment_burned"] = "The page flares up and burns your fingers",
			["cc_stairs_name"] = "Sigrun's rune: the Great Galdrmaster's workshop",
			["cc_workshop_topic"] = "Sigrun's workshop",
			["cc_workshop_text"] = "Here the rock gave way. I did not dig: the power I bound in the orbs carved its own path down, level by level, like roots seeking water. The lower I go, the less this workshop resembles mine. The beasts come here on their own, drawn by what I left in the walls. At the very bottom I keep what I never dared to release.\n\n(carved into the rune by Sigrun's hand)",
			["cc_stairs_down"] = "Way down to level $1",
			["cc_stairs_up"] = "Way back to level $1",
			["cc_stairs_use"] = "Go",
			["cc_stairs_descending"] = "Descending to level $1…",
			["cc_stairs_returning"] = "Returning to level $1…",
			["cc_stairs_blocked"] = "The rune is silent.",
			["cc_hugin_topic"] = "Capture balls",
			["cc_hugin_label"] = "Sigrun's orbs",
			["cc_hugin_text"] = "Do you feel it trembling? This is an orb of the Great Galdrmaster Sigrun. Before you came, he bound the beasts of the Forsaken in them. Look in chests for the pages of his journal; they will tell you the rest."
		};

		public static IReadOnlyDictionary<string, string> Polish { get; } = new Dictionary<string, string>
		{
			["item_cc_captureball"] = "Kula do łapania",
			["item_cc_captureball_desc"] = "Rzuć w stworzenie, aby je złapać. Rzuć pełną kulą, aby je wypuścić.",
			["cc_tooltip_contains"] = "Zawiera: $1",
			["cc_tooltip_contains_named"] = "Zawiera: $1 ($2)",
			["cc_tooltip_stars"] = "Gwiazdki: $1",
			["cc_tooltip_health"] = "Zdrowie: $1%",
			["cc_tooltip_ready"] = "Gotowa za: $1 min",
			["cc_hover_resting"] = "Odpoczywa",
			["cc_hover_needs_warmth"] = "Potrzebuje ciepła i dachu",
			["cc_msg_caught"] = "Złapano: $1",
			["cc_msg_packed"] = "Spakowano: $1",
			["cc_msg_broke_free"] = "Ucieczka: $1",
			["cc_msg_broke_free_shattered"] = "Ucieczka: $1, kula pękła",
			["cc_msg_too_healthy"] = "Nie da się jeszcze złapać: $1 (osłab poniżej $2% zdrowia)",
			["cc_msg_boss"] = "Bossów nie da się złapać",
			["cc_msg_player"] = "Graczy nie da się złapać",
			["cc_msg_summoned"] = "Przywołanych stworzeń nie da się złapać",
			["cc_msg_excluded"] = "Nie da się złapać: $1",
			["cc_msg_gone"] = "Ktoś był szybszy",
			["cc_msg_refuses"] = "$1 nie chce opuścić kuli (gotowa za $2 min)",
			["cc_msg_guardian_limit"] = "Za dużo strażników w pobliżu (maks. $1)",
			["item_cc_fragment1"] = "Dziennik Sigruna, fragment I",
			["item_cc_fragment2"] = "Dziennik Sigruna, fragment II",
			["item_cc_fragment3"] = "Dziennik Sigruna, fragment III",
			["item_cc_fragment4"] = "Dziennik Sigruna, fragment IV",
			["item_cc_fragment1_desc"] = "Osmalona karta dziennika Sigruna pokryta runami. Strona 1 / 4; zapis urywa się w pół zdania. Użyj, aby przeczytać.",
			["item_cc_fragment2_desc"] = "Osmalona karta dziennika Sigruna pokryta runami. Strona 2 / 4; zapis urywa się w pół zdania. Użyj, aby przeczytać.",
			["item_cc_fragment3_desc"] = "Osmalona karta dziennika Sigruna pokryta runami. Strona 3 / 4; zapis urywa się w pół zdania. Użyj, aby przeczytać.",
			["item_cc_fragment4_desc"] = "Osmalona karta dziennika Sigruna pokryta runami. Strona 4 / 4, ostatnia. Użyj, aby przeczytać.",
			["cc_fragment1_text"] = "Piszę, żeby nie zwariować. Nikt tu nie odpowiada, więc mówię do tej karty. Byłem Wielkim Galdrmistrzem. Śpiewem wiązałem runy, a gdy związałem nimi to, czego wiązać nie wolno, bogowie odebrali mi imię i zrzucili mnie do dziesiątego świata. Pierwsze noce przetrwałem z kijem w ręku, plecami do ognia. Bestie Zapomnianych przychodziły co zmrok. Kiedy zabrakło mi sił do walki, zaśpiewałem ostatnią runę więzi, jaką pamiętałem, i zamknąłem w szkle to, co na mnie skoczyło. Tak powstała pierwsza kula. Każda następna kosztuje mnie kawałek dawnej mocy. Te karty pieczętuję runą ognia. Nikt nie powinien czytać ich dwa razy.",
			["cc_fragment2_text"] = "Kule są kapryśne. Dziś draugr roześmiał mi się w twarz, a szkło pękło mi w dłoni. Słaba dusza poddaje się łatwo, silna rozsadza szkło od środka. Wczoraj widziałem wilka, ledwo żywego, który sam wszedł do kuli jak do nory. Zapisuję, żeby nie zapomnieć: bestii w pełni sił się nie łapie. Najpierw trzeba ją zmęczyć i zranić, sprowadzić na skraj. Dopiero gdy jej siła gaśnie, runa więzi ma się czego uchwycić. Ile kul już straciłem? Więcej, niż mam palców. A palców mam coraz mniej.",
			["cc_fragment3_text"] = "Wypuściłem Brunna, trolla, którego złapałem dawno temu między sosnami. Stanął tam, gdzie go uwolniłem, i nie cofnął się ani o krok, choć fulingowie nadchodzili falami. Uwolnione dusze strzegą miejsca, w którym je wypuszczono, lecz poza kulą nie potrafią się leczyć. Brunn krwawił przez trzy noce i nie zagoiła się na nim ani jedna rana. Zabrałem go z powrotem do kuli i położyłem przy ogniu, pod dachem chaty. Rano był cały. Ciepło i dach robią z kulą to, co matka z dzieckiem. Nikomu o tym nie powiem, bo nie ma komu. Tylko Brunn słucha.",
			["cc_fragment4_text"] = "Spotkałem Dvergrów. Wiedzą o runach więcej, niż chcą powiedzieć, ale za kulę z wilkiem pokazali mi swoje czarne rdzenie, ciężkie i ciepłe jak serca. W rdzeniu moc runy nie ucieka, tylko krąży jak zamknięty oddech. Przy stole Galdr połączyłem rdzeń, śluz i kryształy, i kula powstała bez kropli mojej mocy. Ale rdzeń bez runy więzi to tylko kamień. Bez pieśni z pierwszej karty, cierpliwości z drugiej i ognia z trzeciej nic by z tego nie było. Nie muszę już płacić sobą za każde szkło. A jednak coś jest nie tak. Każda kula, którą zrobiłem, szepcze. Ostatnio słyszę w nich własne imię.",
			["cc_fragment_burned"] = "Karta buchnęła płomieniem i poparzyła ci palce",
			["cc_stairs_name"] = "Runa Sigruna: pracownia Wielkiego Galdrmistrza",
			["cc_workshop_topic"] = "Pracownia Sigruna",
			["cc_workshop_text"] = "Tu skała ustąpiła. Nie kopałem: moc, którą wiązałem w kulach, sama wyżłobiła drogę w dół, poziom po poziomie, jak korzenie szukające wody. Im niżej schodzę, tym mniej ta pracownia przypomina moją. Bestie przychodzą tu same, zwabione tym, co zostawiłem w ścianach. Na samym dnie trzymam to, czego nie odważyłem się wypuścić.\n\n(wyryte na runie, ręką Sigruna)",
			["cc_stairs_down"] = "Zejście na poziom $1",
			["cc_stairs_up"] = "Powrót na poziom $1",
			["cc_stairs_use"] = "Przejdź",
			["cc_stairs_descending"] = "Schodzisz na poziom $1…",
			["cc_stairs_returning"] = "Wracasz na poziom $1…",
			["cc_stairs_blocked"] = "Runa milczy.",
			["cc_hugin_topic"] = "Kule do łapania",
			["cc_hugin_label"] = "Kule Sigruna",
			["cc_hugin_text"] = "Czujesz to drżenie? To kula Wielkiego Galdrmistrza Sigruna. Zanim tu przybyłeś, więził w nich bestie Zapomnianych. Szukaj w skrzyniach stron jego dziennika, one opowiedzą ci resztę."
		};

		public static string Format(IReadOnlyDictionary<string, string> table, string key, params string[] words)
		{
			if (!table.TryGetValue(key, out string value))
			{
				return "[" + key + "]";
			}
			return Insert(value, words);
		}

		public static string Insert(string template, params string[] words)
		{
			StringBuilder stringBuilder = new StringBuilder(template.Length);
			for (int i = 0; i < template.Length; i++)
			{
				if (template[i] == '$' && i + 1 < template.Length && char.IsDigit(template[i + 1]))
				{
					int j;
					for (j = i + 1; j < template.Length && char.IsDigit(template[j]); j++)
					{
					}
					int num = int.Parse(template.Substring(i + 1, j - i - 1), CultureInfo.InvariantCulture) - 1;
					if (num >= 0 && num < words.Length)
					{
						stringBuilder.Append(words[num]);
						i = j - 1;
						continue;
					}
				}
				stringBuilder.Append(template[i]);
			}
			return stringBuilder.ToString();
		}
	}
}
namespace CreaturesCatch.Releasing
{
	public static class GuardianConfig
	{
		private const float DefaultMultiplier = 1f;

		private const float DefaultRoamRadius = 10f;

		private static ConfigEntry<float>? healthMultiplier;

		private static ConfigEntry<float>? damageMultiplier;

		private static ConfigEntry<float>? roamRadius;

		public static float HealthMultiplier => healthMultiplier?.Value ?? 1f;

		public static float DamageMultiplier => damageMultiplier?.Value ?? 1f;

		public static float RoamRadius => roamRadius?.Value ?? 10f;

		public static void Bind(ConfigFile config)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Expected O, but got Unknown
			//IL_00bc: 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_00c9: Expected O, but got Unknown
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Expected O, but got Unknown
			healthMultiplier = config.Bind<float>("Guardians", "HealthMultiplier", 1f, new ConfigDescription("Max health multiplier for guardians (released non-tameable creatures).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			damageMultiplier = config.Bind<float>("Guardians", "DamageMultiplier", 1f, new ConfigDescription("Damage multiplier for guardians.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			roamRadius = config.Bind<float>("Guardians", "RoamRadius", 10f, new ConfigDescription("Meters a guardian wanders around its release point when idle.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 50f), new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
		}
	}
	[HarmonyPatch(typeof(Character), "Awake")]
	internal static class GuardianAwake
	{
		private static void Postfix(Character __instance)
		{
			if (Guardians.HasMarker(__instance))
			{
				Guardians.Setup(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(Character), "SetupMaxHealth")]
	internal static class GuardianMaxHealth
	{
		private static void Prefix(Character __instance, out bool __state)
		{
			__state = __instance.GetHealth() >= __instance.GetMaxHealth();
		}

		private static void Postfix(Character __instance, bool __state)
		{
			if (Guardians.HasMarker(__instance))
			{
				__instance.SetMaxHealth(GuardianRules.MaxHealth(__instance.GetMaxHealth(), GuardianConfig.HealthMultiplier));
				__instance.SetHealth(GuardianRules.HealthAfterScaling(__state, __instance.GetHealth(), __instance.GetMaxHealth()));
			}
		}
	}
	[HarmonyPatch(typeof(BaseAI), "UpdateRegeneration")]
	internal static class GuardianNoRegeneration
	{
		private static bool Prefix(Character ___m_character)
		{
			return !Guardians.IsGuardian(___m_character);
		}
	}
	[HarmonyPatch(typeof(BaseAI), "IsEnemy", new Type[]
	{
		typeof(Character),
		typeof(Character)
	})]
	internal static class GuardianNotEnemyOfPlayers
	{
		private static void Postfix(Character a, Character b, ref bool __result)
		{
			if (__result && !((Object)(object)a == (Object)null) && !((Object)(object)b == (Object)null))
			{
				__result = GuardianRules.IsEnemy(__result, Guardians.IsGuardian(a), a.IsPlayer(), Guardians.IsGuardian(b), b.IsPlayer());
			}
		}
	}
	[HarmonyPatch(typeof(Character), "Damage")]
	internal static class GuardianDamage
	{
		private static void Prefix(HitData hit)
		{
			if (hit != null && Guardians.IsGuardian(hit.GetAttacker()))
			{
				hit.ApplyModifier(GuardianRules.Multiplier(GuardianConfig.DamageMultiplier));
			}
		}
	}
	public static class GuardianRules
	{
		public const float MinGuardRange = 20f;

		public const float MinSenseRange = 30f;

		public static bool IsEnemy(bool vanilla, bool aIsGuardian, bool aIsPlayer, bool bIsGuardian, bool bIsPlayer)
		{
			if ((aIsGuardian && bIsPlayer) || (bIsGuardian && aIsPlayer))
			{
				return false;
			}
			return vanilla;
		}

		public static float Multiplier(float configured)
		{
			if (!(configured > 0f) || float.IsInfinity(configured))
			{
				return 1f;
			}
			return configured;
		}

		public static float MaxHealth(float freshMaxHealth, float configuredMultiplier)
		{
			return freshMaxHealth * Multiplier(configuredMultiplier);
		}

		public static float GuardRange(float prefabAlertRange)
		{
			if (!(prefabAlertRange > 20f))
			{
				return 20f;
			}
			return prefabAlertRange;
		}

		public static float SenseRange(float prefabRange)
		{
			if (!(prefabRange > 30f))
			{
				return 30f;
			}
			return prefabRange;
		}

		public static float RoamRange(float prefabRange, float roamRadius)
		{
			if (!(prefabRange > 0f))
			{
				return roamRadius;
			}
			return Math.Min(prefabRange, roamRadius);
		}

		public static float HealthAfterScaling(bool wasFull, float health, float scaledMaxHealth)
		{
			if (!wasFull)
			{
				return Math.Min(health, scaledMaxHealth);
			}
			return scaledMaxHealth;
		}

		public static float ReleaseHealth(float storedHealth, float? storedMaxHealth, float maxHealth)
		{
			float val;
			if (storedMaxHealth.HasValue)
			{
				float valueOrDefault = storedMaxHealth.GetValueOrDefault();
				if (valueOrDefault > 0f)
				{
					val = storedHealth / valueOrDefault * maxHealth;
					goto IL_0021;
				}
			}
			val = storedHealth;
			goto IL_0021;
			IL_0021:
			return Math.Min(val, maxHealth);
		}
	}
	public static class Guardians
	{
		private static readonly int MarkerHash = StringExtensionMethods.GetStableHashCode("creaturescatch.guardian");

		public static void Mark(Character character)
		{
			ZNetView component = ((Component)character).GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.IsValid())
			{
				component.GetZDO().Set(MarkerHash, true);
				Setup(character);
			}
		}

		public static bool HasMarker(Character character)
		{
			ZNetView component = ((Component)character).GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.IsValid())
			{
				return component.GetZDO().GetBool(MarkerHash, false);
			}
			return false;
		}

		public static bool IsGuardian(Character? character)
		{
			GuardianTag guardianTag = default(GuardianTag);
			if ((Object)(object)character != (Object)null)
			{
				return ((Component)character).TryGetComponent<GuardianTag>(ref guardianTag);
			}
			return false;
		}

		public static void Setup(Character character)
		{
			GuardianTag guardianTag = default(GuardianTag);
			if (!((Component)character).TryGetComponent<GuardianTag>(ref guardianTag))
			{
				((Component)character).gameObject.AddComponent<GuardianTag>();
			}
			BaseAI baseAI = character.GetBaseAI();
			if ((Object)(object)baseAI != (Object)null)
			{
				baseAI.m_randomMoveRange = GuardianRules.RoamRange(baseAI.m_randomMoveRange, GuardianConfig.RoamRadius);
				MonsterAI val = (MonsterAI)(object)((baseAI is MonsterAI) ? baseAI : null);
				if (val != null)
				{
					val.m_alertRange = GuardianRules.GuardRange(val.m_alertRange);
					((BaseAI)val).m_viewRange = GuardianRules.SenseRange(((BaseAI)val).m_viewRange);
					((BaseAI)val).m_hearRange = GuardianRules.SenseRange(((BaseAI)val).m_hearRange);
					val.m_circleTargetInterval = 0f;
				}
				ZNetView component = ((Component)character).GetComponent<ZNetView>();
				if ((Object)(object)component != (Object)null && component.IsValid() && component.IsOwner() && !component.GetZDO().GetBool(ZDOVars.s_patrol, false))
				{
					baseAI.SetPatrolPoint();
				}
			}
		}

		public static int CountNear(Vector3 point, float radius)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			foreach (Character allCharacter in Character.GetAllCharacters())
			{
				if ((Object)(object)allCharacter != (Object)null && !allCharacter.IsDead() && IsGuardian(allCharacter) && Vector3.Distance(((Component)allCharacter).transform.position, point) <= radius)
				{
					num++;
				}
			}
			return num;
		}
	}
	public sealed class GuardianTag : MonoBehaviour
	{
	}
	public static class ReleaseConfig
	{
		private const float DefaultCooldownMinutes = 10f;

		private const int DefaultGuardianLimit = 3;

		private const float DefaultGuardianRadius = 30f;

		private static ConfigEntry<float>? cooldownMinutes;

		private static ConfigEntry<int>? guardianLimit;

		private static ConfigEntry<float>? guardianRadius;

		public static double CooldownSeconds => (double)(cooldownMinutes?.Value ?? 10f) * 60.0;

		public static int GuardianLimit => guardianLimit?.Value ?? 3;

		public static float GuardianRadius => guardianRadius?.Value ?? 30f;

		public static void Bind(ConfigFile config)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Expected O, but got Unknown
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: 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_00be: Expected O, but got Unknown
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Expected O, but got Unknown
			cooldownMinutes = config.Bind<float>("Releasing", "CooldownMinutes", 10f, new ConfigDescription("World-time minutes after a ball is filled before the creature agrees to leave it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1440f), new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			guardianLimit = config.Bind<int>("Releasing", "GuardianLimit", 3, new ConfigDescription("Most guardians (released non-tameable creatures) allowed within GuardianRadius of a release.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			guardianRadius = config.Bind<float>("Releasing", "GuardianRadius", 30f, new ConfigDescription("Radius in meters for GuardianLimit.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 200f), new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
		}
	}
	public enum ReleaseBlock
	{
		None,
		Cooldown,
		GuardianLimit
	}
	public readonly record struct ReleaseDecision(ReleaseBlock Block, double RemainingSeconds);
	public static class ReleaseRules
	{
		public static double CooldownRemaining(double? filledAt, double now, double cooldownSeconds)
		{
			if (filledAt.HasValue)
			{
				double valueOrDefault = filledAt.GetValueOrDefault();
				if (cooldownSeconds > 0.0)
				{
					double num = now - valueOrDefault;
					if (!(num >= 0.0))
					{
						return cooldownSeconds;
					}
					return Math.Max(0.0, cooldownSeconds - num);
				}
			}
			return 0.0;
		}

		public static double? Reanchor(double? filledAt, double now)
		{
			if (!(filledAt > now))
			{
				return filledAt;
			}
			return now;
		}

		public static ReleaseDecision Decide(double? filledAt, double now, double cooldownSeconds, bool becomesGuardian, int guardiansNearby, int guardianLimit)
		{
			double num = CooldownRemaining(filledAt, now, cooldownSeconds);
			if (num > 0.0)
			{
				return new ReleaseDecision(ReleaseBlock.Cooldown, num);
			}
			if (!becomesGuardian || guardiansNearby < guardianLimit)
			{
				return new ReleaseDecision(ReleaseBlock.None, 0.0);
			}
			return new ReleaseDecision(ReleaseBlock.GuardianLimit, 0.0);
		}
	}
	internal static class SummonAttacks
	{
		private static readonly Dictionary<SharedData, bool> Cache = new Dictionary<SharedData, bool>();

		public static bool Summons(ItemData item)
		{
			SharedData shared = item.m_shared;
			if (!Cache.TryGetValue(shared, out var value))
			{
				value = Spawns(shared.m_spawnOnHit, 0) || Spawns(shared.m_spawnOnHitTerrain, 0) || Spawns(shared.m_attack, 0) || Spawns(shared.m_secondaryAttack, 0);
				Cache[shared] = value;
			}
			return value;
		}

		private static bool Spawns(Attack? attack, int depth)
		{
			if (attack != null)
			{
				if (!Spawns(attack.m_attackProjectile, depth) && !Spawns(attack.m_spawnOnTrigger, depth))
				{
					return Spawns(attack.m_spawnOnHit, depth);
				}
				return true;
			}
			return false;
		}

		private static bool Spawns(GameObject? prefab, int depth)
		{
			if ((Object)(object)prefab == (Object)null || depth > 2)
			{
				return false;
			}
			SpawnAbility[] componentsInChildren = prefab.GetComponentsInChildren<SpawnAbility>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				GameObject[] array = componentsInChildren[i].m_spawnPrefab ?? Array.Empty<GameObject>();
				foreach (GameObject val in array)
				{
					if ((Object)(object)val != (Object)null && ((Object)(object)val.GetComponent<Character>() != (Object)null || Spawns(val, depth + 1)))
					{
						return true;
					}
				}
			}
			Projectile[] componentsInChildren2 = prefab.GetComponentsInChildren<Projectile>(true);
			foreach (Projectile val2 in componentsInChildren2)
			{
				if (Spawns(val2.m_spawnOnHit, depth + 1))
				{
					return true;
				}
				foreach (GameObject item in val2.m_randomSpawnOnHit)
				{
					if (Spawns(item, depth + 1))
					{
						return true;
					}
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(BaseAI), "CanUseAttack")]
	internal static class TamedNoSummoning
	{
		private static void Postfix(Character ___m_character, ItemData item, ref bool __result)
		{
			if (__result && item != null && !((Object)(object)___m_character == (Object)null) && ___m_character.IsTamed())
			{
				__result = SummonRules.CanUseAttack(__result, isTamed: true, SummonAttacks.Summons(item));
			}
		}
	}
	public static class SummonRules
	{
		public static bool CanUseAttack(bool vanilla, bool isTamed, bool summons)
		{
			if (vanilla)
			{
				return !(isTamed && summons);
			}
			return false;
		}
	}
}
namespace CreaturesCatch.Lore
{
	[HarmonyPatch(typeof(Container), "RPC_OpenResponse")]
	internal static class FragmentChests
	{
		public static readonly int FlagHash = StringExtensionMethods.GetStableHashCode("creaturescatch.fragment");

		private const float OwnershipWait = 2f;

		private static void Prefix(Container __instance, bool granted, ZNetView ___m_nview, Inventory ___m_inventory)
		{
			if (granted && !((Object)(object)Player.m_localPlayer == (Object)null) && !((Object)(object)___m_nview == (Object)null) && ___m_nview.IsValid() && ___m_inventory != null && ___m_nview.GetZDO().GetBool(FlagHash, false))
			{
				if (___m_nview.IsOwner())
				{
					TryInsert(__instance, ___m_nview, ___m_inventory);
				}
				else
				{
					((MonoBehaviour)__instance).StartCoroutine(InsertWhenOwner(__instance, ___m_nview, ___m_inventory));
				}
			}
		}

		private static IEnumerator InsertWhenOwner(Container container, ZNetView view, Inventory inventory)
		{
			float deadline = Time.time + 2f;
			while (Time.time < deadline && (Object)(object)view != (Object)null && view.IsValid() && !view.IsOwner())
			{
				yield return null;
			}
			if ((Object)(object)view != (Object)null && view.IsValid() && view.IsOwner())
			{
				TryInsert(container, view, inventory);
			}
		}

		private static void TryInsert(Container container, ZNetView view, Inventory inventory)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			Player player = Player.m_localPlayer;
			ZDO zDO = view.GetZDO();
			if (!((Object)(object)player == (Object)null) && WorldGenerator.instance != null && zDO.GetBool(FlagHash, false))
			{
				string text = WorkshopLoot.Biome(((Component)container).transform.position);
				int? num = FragmentRules.Next((int n) => player.IsKnownMaterial(FragmentRules.TokenName(n)), text);
				object obj;
				if (num.HasValue)
				{
					int valueOrDefault = num.GetValueOrDefault();
					obj = FragmentItems.Prefab(valueOrDefault);
				}
				else
				{
					obj = null;
				}
				GameObject val = (GameObject)obj;
				if ((Object)(object)val != (Object)null && inventory.AddItem(val, 1))
				{
					zDO.Set(FlagHash, false);
					Logger.LogInfo((object)$"Chest loot: journal fragment {num} in {text}");
				}
			}
		}
	}
	internal static class FragmentEffects
	{
		private const string FlareSound = "sfx_FireAddFuel";

		private const string SizzleSound = "sfx_oven_burnt";

		private const string FlareSparks = "vfx_bonfire_AddFuel";

		private const string HandFlames = "vfx_Burning";

		private const float HandFlamesSeconds = 1.5f;

		public static void Burn(Player player)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			VisEquipment val2 = default(VisEquipment);
			Transform val = ((((Component)player).TryGetComponent<VisEquipment>(ref val2) && (Object)(object)val2.m_rightHand != (Object)null) ? val2.m_rightHand : ((Component)player).transform);
			Spawn("sfx_FireAddFuel", val.position, null);
			Spawn("sfx_oven_burnt", val.position, null);
			Spawn("vfx_bonfire_AddFuel", val.position, null);
			GameObject val3 = Spawn("vfx_Burning", val.position, val);
			if ((Object)(object)val3 != (Object)null)
			{
				Object.Destroy((Object)(object)val3, 1.5f);
			}
			((Character)player).m_hitEffects.Create(((Character)player).GetCenterPoint(), Quaternion.identity, ((Component)player).transform, 1f, -1, default(ZDOID));
		}

		private static GameObject? Spawn(string name, Vector3 position, Transform? parent)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			GameObject prefab = Cache.GetPrefab<GameObject>(name);
			if ((Object)(object)prefab == (Object)null)
			{
				Logger.LogWarning((object)("Missing effect " + name));
				return null;
			}
			GameObject val = Object.Instantiate<GameObject>(prefab, position, Quaternion.identity);
			if ((Object)(object)parent != (Object)null)
			{
				val.transform.SetParent(parent, true);
			}
			return val;
		}
	}
	public static class FragmentItems
	{
		public static void Register()
		{
			PrefabManager.OnVanillaPrefabsAvailable += AddItems;
		}

		public static bool TryGetNumber(ItemData? item, out int n)
		{
			string text = item?.m_shared?.m_name;
			for (n = 1; n <= 4; n++)
			{
				if (text == FragmentRules.TokenName(n))
				{
					return true;
				}
			}
			n = 0;
			return false;
		}

		public static GameObject? Prefab(int n)
		{
			if (!((Object)(object)ZNetScene.instance != (Object)null))
			{
				return null;
			}
			return ZNetScene.instance.GetPrefab(FragmentRules.ItemName(n));
		}

		private static void AddItems()
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: 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_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Expected O, but got Unknown
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			PrefabManager.OnVanillaPrefabsAvailable -= AddItems;
			Texture2D val = LoadTexture("CreaturesCatch.fragment.png");
			Texture2D val2 = LoadTexture("CreaturesCatch.fragment_texture.jpg");
			Sprite val3 = (((Object)(object)val != (Object)null) ? Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f)) : null);
			for (int i = 1; i <= 4; i++)
			{
				ItemConfig val4 = new ItemConfig
				{
					Name = FragmentRules.TokenName(i),
					Description = FragmentRules.DescriptionToken(i)
				};
				if ((Object)(object)val3 != (Object)null)
				{
					val4.Icon = val3;
				}
				CustomItem val5 = new CustomItem(FragmentRules.ItemName(i), "LeatherScraps", val4);
				SharedData shared = val5.ItemDrop.m_itemData.m_shared;
				shared.m_itemType = (ItemType)2;
				shared.m_maxStackSize = 1;
				shared.m_weight = 0.1f;
				shared.m_food = 0f;
				shared.m_foodStamina = 0f;
				shared.m_foodEitr = 0f;
				shared.m_consumeStatusEffect = null;
				shared.m_teleportable = true;
				if ((Object)(object)val2 != (Object)null)
				{
					Retexture(val5.ItemPrefab, val2);
				}
				ItemManager.Instance.AddItem(val5);
			}
		}

		private static void Retexture(GameObject prefab, Texture2D texture)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			Renderer[] componentsInChildren = prefab.GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if (!(val is MeshRenderer) && !(val is SkinnedMeshRenderer))
				{
					continue;
				}
				Material[] sharedMaterials = val.sharedMaterials;
				for (int j = 0; j < sharedMaterials.Length; j++)
				{
					if ((Object)(object)sharedMaterials[j] != (Object)null)
					{
						sharedMaterials[j] = new Material(sharedMaterials[j])
						{
							mainTexture = (Texture)(object)texture
						};
					}
				}
				val.sharedMaterials = sharedMaterials;
			}
		}

		internal static Texture2D? LoadTexture(string resource)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			using Stream stream = typeof(FragmentItems).Assembly.GetManifestResourceStream(resource);
			if (stream == null)
			{
				Logger.LogWarning((object)("Missing embedded resource " + resource));
				return null;
			}
			using MemoryStream memoryStream = new MemoryStream();
			stream.CopyTo(memoryStream);
			Texture2D val = new Texture2D(2, 2);
			return ImageConversion.LoadImage(val, memoryStream.ToArray()) ? val : null;
		}
	}
	[HarmonyPatch(typeof(Player), "ConsumeItem")]
	internal static class FragmentReading
	{
		private static readonly Action<Player, Recipe>? AddKnownRecipe = CreateAddKnownRecipe();

		private static void Postfix(Player __instance, ItemData item, bool __result)
		{
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Expected O, but got Unknown
			if (__result && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && FragmentItems.TryGetNumber(item, out var n))
			{
				string text = FragmentRules.TokenName(n);
				string text2 = $"$cc_fragment{n}_text";
				if ((Object)(object)TextViewer.instance != (Object)null)
				{
					TextViewer.instance.ShowText((Style)0, text, text2, false);
				}
				__instance.AddKnownText(text, text2);
				if (FragmentRules.TeachesIngredients(n))
				{
					LearnIngredients(__instance);
				}
				List<string> read = (from known in __instance.GetKnownTexts()
					select known.Key).ToList();
				if ((Object)(object)CaptureBallItem.Recipe != (Object)null && FragmentRules.UnlocksRecipe((int i) => read.Contains(FragmentRules.TokenName(i))))
				{
					AddKnownRecipe?.Invoke(__instance, CaptureBallItem.Recipe);
				}
				((Character)__instance).Message((MessageType)2, "$cc_fragment_burned", 0, (Sprite)null, false);
				FragmentEffects.Burn(__instance);
				float num = FragmentRules.BurnDamage(((Character)__instance).GetHealth(), Game.m_localDamgeTakenRate);
				if (num > 0f)
				{
					HitData val = new HitData
					{
						m_point = ((Character)__instance).GetCenterPoint()
					};
					val.m_damage.m_fire = num;
					((Character)__instance).ApplyDamage(val, true, true, (DamageModifier)0);
				}
			}
		}

		private static void LearnIngredients(Player player)
		{
			if ((Object)(object)ObjectDB.instance == (Object)null)
			{
				return;
			}
			ItemDrop val = default(ItemDrop);
			foreach (var requirement in BallRecipe.Requirements)
			{
				string item = requirement.Prefab;
				GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(item);
				if ((Object)(object)itemPrefab != (Object)null && itemPrefab.TryGetComponent<ItemDrop>(ref val))
				{
					player.AddKnownItem(val.m_itemData);
				}
			}
		}

		private static Action<Player, Recipe>? CreateAddKnownRecipe()
		{
			MethodInfo methodInfo = AccessTools.Method(typeof(Player), "AddKnownRecipe", new Type[1] { typeof(Recipe) }, (Type[])null);
			if (!(methodInfo != null))
			{
				return null;
			}
			return AccessTools.MethodDelegate<Action<Player, Recipe>>(methodInfo, (object)null, true);
		}
	}
	[HarmonyPatch(typeof(Humanoid), "UseItem")]
	internal static class FragmentKneel
	{
		private static bool Prefix(Humanoid __instance, Inventory inventory, ItemData item)
		{
			Player val = (Player)(object)((__instance is Player) ? __instance : null);
			if (val == null || (Object)(object)val != (Object)(object)Player.m_localPlayer || !FragmentItems.TryGetNumber(item, out var _))
			{
				return true;
			}
			if (inventory == null)
			{
				inventory = ((Humanoid)val).GetInventory();
			}
			if (inventory.ContainsItem(item) && ((Humanoid)val).ConsumeItem(inventory, item, true))
			{
				val.StartEmote("kneel", true);
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Player), "HaveRequirements", new Type[]
	{
		typeof(Recipe),
		typeof(bool),
		typeof(int),
		typeof(int)
	})]
	internal static class NoBallRecipeDiscovery
	{
		private static void Postfix(Recipe recipe, bool discover, ref bool __result)
		{
			if ((discover & __result) && (Object)(object)recipe != (Object)null && (Object)(object)recipe == (Object)(object)CaptureBallItem.Recipe)
			{
				__result = false;
			}
		}
	}
	public static class FragmentRules
	{
		public const int Count = 4;

		public const float MaxBurn = 5f;

		private static readonly Dictionary<string, int> MaxByBiome = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
		{
			["Meadows"] = 1,
			["BlackForest"] = 1,
			["Swamp"] = 2,
			["Mountain"] = 2,
			["Plains"] = 3,
			["Mistlands"] = 4,
			["AshLands"] = 4,
			["DeepNorth"] = 4
		};

		public static int MaxFragment(string biome)
		{
			if (!MaxByBiome.TryGetValue(biome, out var value))
			{
				return 0;
			}
			return value;
		}

		public static int? Next(Func<int, bool> owned, string biome)
		{
			int num = MaxFragment(biome);
			for (int i = 1; i <= num; i++)
			{
				if (!owned(i))
				{
					return i;
				}
			}
			return null;
		}

		public static bool UnlocksRecipe(Func<int, bool> read)
		{
			for (int i = 1; i <= 4; i++)
			{
				if (!read(i))
				{
					return false;
				}
			}
			return true;
		}

		public static bool TeachesIngredients(int n)
		{
			return n == 4;
		}

		public static float ChestChance(float percent)
		{
			if (!float.IsNaN(percent))
			{
				return Math.Clamp(percent / 100f, 0f, 1f);
			}
			return 0f;
		}

		public static float BurnDamage(float health, float damageTakenRate = 1f)
		{
			if (!(damageTakenRate > 0f))
			{
				return 0f;
			}
			return Math.Max(0f, Math.Min(5f, health - 1f)) / damageTakenRate;
		}

		public static string ItemName(int n)
		{
			return "CC_Fragment" + n;
		}

		public static string TokenName(int n)
		{
			return "$item_cc_fragment" + n;
		}

		public static string DescriptionToken(int n)
		{
			return "$item_cc_fragment" + n + "_desc";
		}
	}
	public static class HuginBall
	{
		public const string TutorialName = "cc_hugin_ball";
	}
	[HarmonyPatch(typeof(Tutorial), "Awake")]
	internal static class HuginBallText
	{
		private static void Postfix(Tutorial __instance)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Expected O, but got Unknown
			if (!__instance.m_texts.Exists((TutorialText text) => text.m_name == "cc_hugin_ball"))
			{
				__instance.m_texts.Add(new TutorialText
				{
					m_name = "cc_hugin_ball",
					m_topic = "$cc_hugin_topic",
					m_label = "$cc_hugin_label",
					m_text = "$cc_hugin_text"
				});
			}
		}
	}
	[HarmonyPatch(typeof(Player), "AddKnownItem")]
	internal static class HuginBallTrigger
	{
		private static void Postfix(Player __instance, ItemData item)
		{
			if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && CaptureBallItem.IsBall(item))
			{
				__instance.ShowTutorial("cc_hugin_ball", false);
			}
		}
	}
}
namespace CreaturesCatch.Loot
{
	public static class LootConfig
	{
		private const float DefaultStarDropChancePerStar = 2f;

		private const float DefaultBossDropChance = 90f;

		private const float DefaultFragmentChestChance = 10f;

		private static ConfigEntry<string>? chestChances;

		private static ConfigEntry<float>? starDropChancePerStar;

		private static ConfigEntry<float>? bossDropChance;

		private static ConfigEntry<float