Decompiled source of RuneStones v0.1.3

plugins/RuneStones.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using RuneStones.Core;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("RuneStones")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.3.0")]
[assembly: AssemblyInformationalVersion("0.1.3+9f5165e1ce4cf902862f02c69ea1f4daf4c1d493")]
[assembly: AssemblyProduct("RuneStones")]
[assembly: AssemblyTitle("RuneStones")]
[assembly: AssemblyVersion("0.1.3.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace RuneStones
{
	internal static class CalmField
	{
		private struct Entry
		{
			public float X;

			public float Z;

			public float Radius;
		}

		private static readonly List<RuneStone> s_stones = new List<RuneStone>();

		private static Entry[] s_entries = new Entry[0];

		private static float s_edge;

		private static float s_strength;

		private static float s_visualRadius;

		public static int Count => s_entries.Length;

		public static void Register(RuneStone stone)
		{
			if (!s_stones.Contains(stone))
			{
				s_stones.Add(stone);
			}
			Rebuild();
		}

		public static void Unregister(RuneStone stone)
		{
			if (s_stones.Remove(stone))
			{
				Rebuild();
			}
		}

		public static void Rebuild()
		{
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			s_stones.RemoveAll((RuneStone s) => (Object)(object)s == (Object)null);
			float num = Settings.Radius(RuneKind.Calm);
			s_edge = Settings.CalmEdgeWidth.Value;
			s_strength = Settings.CalmStrength.Value;
			s_visualRadius = Settings.CalmVisualRadius.Value;
			if (!Settings.Enabled(RuneKind.Calm) || num <= 0f || s_strength <= 0f || s_stones.Count == 0)
			{
				s_entries = new Entry[0];
			}
			else
			{
				Entry[] array = new Entry[s_stones.Count];
				for (int num2 = 0; num2 < array.Length; num2++)
				{
					Vector3 position = ((Component)s_stones[num2]).transform.position;
					array[num2] = new Entry
					{
						X = position.x,
						Z = position.z,
						Radius = num
					};
				}
				s_entries = array;
			}
			CalmWater.ApplyAll();
		}

		public static float VisualFactor(float x, float z)
		{
			float num = 1f;
			if (!(s_visualRadius > 0f))
			{
				return num;
			}
			Entry[] array = s_entries;
			for (int i = 0; i < array.Length; i++)
			{
				float num2 = x - array[i].X;
				float num3 = z - array[i].Z;
				num = CalmMath.Combine(num, CalmMath.FactorSqr(num2 * num2 + num3 * num3, s_visualRadius, s_edge, s_strength));
			}
			return num;
		}

		public static float Factor(float x, float z)
		{
			Entry[] array = s_entries;
			float num = 1f;
			for (int i = 0; i < array.Length; i++)
			{
				float num2 = x - array[i].X;
				float num3 = z - array[i].Z;
				num = CalmMath.Combine(num, CalmMath.FactorSqr(num2 * num2 + num3 * num3, array[i].Radius, s_edge, s_strength));
			}
			return num;
		}
	}
	[HarmonyPatch(typeof(WaterVolume), "CalcWave", new Type[]
	{
		typeof(Vector3),
		typeof(float),
		typeof(float),
		typeof(float),
		typeof(float)
	})]
	internal static class CalcWavePatch
	{
		private static void Postfix(Vector3 worldPos, ref float __result)
		{
			//IL_000a: 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)
			if (CalmField.Count != 0)
			{
				__result *= CalmField.Factor(worldPos.x, worldPos.z);
			}
		}
	}
	internal static class CalmWater
	{
		private sealed class Tile
		{
			public float[] Live;

			public float[] Original;

			public Collider Collider;

			public bool Changed;
		}

		private const int SweepEvery = 64;

		private static readonly Dictionary<WaterVolume, Tile> s_tiles = new Dictionary<WaterVolume, Tile>();

		private static readonly List<WaterVolume> s_dead = new List<WaterVolume>();

		private static readonly float[] s_factors = new float[4];

		private static readonly FieldRef<WaterVolume, float> s_oneDepth = AccessTools.FieldRefAccess<WaterVolume, float>("m_oneDepth");

		private static readonly int s_shaderDepth = Shader.PropertyToID("_depth");

		private static int s_sinceSweep;

		private static bool Headless => (int)SystemInfo.graphicsDeviceType == 4;

		public static void Track(WaterVolume volume, float[] depths, Collider collider)
		{
			if (!((Object)(object)volume == (Object)null) && depths != null && depths.Length == 4 && CalmDepth.Tracks(Object.op_Implicit((Object)(object)volume.m_heightmap), volume.m_forceDepth) && !s_tiles.ContainsKey(volume))
			{
				if (++s_sinceSweep >= 64)
				{
					Sweep();
				}
				Tile tile = new Tile
				{
					Live = depths,
					Original = (float[])depths.Clone(),
					Collider = collider
				};
				s_tiles[volume] = tile;
				if (CalmField.Count != 0)
				{
					Apply(volume, tile);
				}
			}
		}

		public static void ApplyAll()
		{
			Sweep();
			foreach (KeyValuePair<WaterVolume, Tile> s_tile in s_tiles)
			{
				Apply(s_tile.Key, s_tile.Value);
			}
		}

		private static void Apply(WaterVolume volume, Tile tile)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//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_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			bool flag = true;
			if (CalmField.Count != 0 && (Object)(object)tile.Collider != (Object)null)
			{
				Bounds bounds = tile.Collider.bounds;
				Vector3 size = ((Bounds)(ref bounds)).size;
				Transform transform = ((Component)volume).transform;
				for (int i = 0; i < 4; i++)
				{
					Vector3 val = transform.TransformPoint(new Vector3((float)CalmDepth.SignX(i) * size.x * 0.5f, 0f, (float)CalmDepth.SignZ(i) * size.z * 0.5f));
					s_factors[i] = CalmField.VisualFactor(val.x, val.z);
				}
				flag = CalmDepth.IsIdentity(s_factors);
			}
			if (flag)
			{
				if (!tile.Changed)
				{
					return;
				}
				for (int j = 0; j < 4; j++)
				{
					s_factors[j] = 1f;
				}
			}
			CalmDepth.Apply(tile.Original, s_factors, tile.Live);
			s_oneDepth.Invoke(volume) = CalmDepth.OneDepth(tile.Live);
			tile.Changed = !flag;
			if (!Headless && (Object)(object)volume.m_waterSurface != (Object)null)
			{
				((Renderer)volume.m_waterSurface).material.SetFloatArray(s_shaderDepth, tile.Live);
			}
		}

		private static void Sweep()
		{
			s_sinceSweep = 0;
			s_dead.Clear();
			foreach (KeyValuePair<WaterVolume, Tile> s_tile in s_tiles)
			{
				if ((Object)(object)s_tile.Key == (Object)null)
				{
					s_dead.Add(s_tile.Key);
				}
			}
			for (int i = 0; i < s_dead.Count; i++)
			{
				s_tiles.Remove(s_dead[i]);
			}
			s_dead.Clear();
		}
	}
	[HarmonyPatch(typeof(WaterVolume), "Start")]
	internal static class WaterVolumeStartPatch
	{
		private static void Postfix(WaterVolume __instance, float[] ___m_normalizedDepth, Collider ___m_collider)
		{
			CalmWater.Track(__instance, ___m_normalizedDepth, ___m_collider);
		}
	}
	[BepInPlugin("sansara.RuneStones", "Rune Stones", "0.1.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Guid = "sansara.RuneStones";

		public const string Name = "Rune Stones";

		public const string Version = "0.1.3";

		internal static ManualLogSource Log;

		private static bool s_applyPending;

		private static string s_applyReason;

		private void Awake()
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Settings.Bind(((BaseUnityPlugin)this).Config);
			AddLocalization();
			((BaseUnityPlugin)this).Config.SettingChanged += delegate
			{
				RequestApply("настройки изменены");
			};
			SynchronizationManager.OnConfigurationSynchronized += delegate(object _, ConfigurationSynchronizationEventArgs e)
			{
				RequestApply(e.InitialSynchronization ? "получены настройки сервера" : "обновлены настройки сервера");
			};
			PrefabManager.OnVanillaPrefabsAvailable += Prefabs.Create;
			new Harmony("sansara.RuneStones").PatchAll();
			bool flag = HasPostfix(AccessTools.Method(typeof(WaterVolume), "CalcWave", new Type[5]
			{
				typeof(Vector3),
				typeof(float),
				typeof(float),
				typeof(float),
				typeof(float)
			}, (Type[])null));
			bool flag2 = HasPostfix(AccessTools.Method(typeof(WaterVolume), "Start", (Type[])null, (Type[])null));
			bool flag3 = HasPostfix(AccessTools.Method(typeof(SpawnSystem), "IsSpawnPointGood", (Type[])null, (Type[])null));
			bool flag4 = HasPostfix(AccessTools.Method(typeof(WearNTear), "Awake", (Type[])null, (Type[])null));
			if (flag && flag2 && flag3 && flag4)
			{
				Log.LogInfo((object)"Rune Stones 0.1.3 загружен, патчи WaterVolume.CalcWave, WaterVolume.Start, SpawnSystem.IsSpawnPointGood и WearNTear.Awake применены.");
				return;
			}
			if (!flag4)
			{
				Log.LogError((object)"Rune Stones 0.1.3: патч WearNTear.Awake не применён, «Починка» не чинит.");
			}
			if (!flag)
			{
				Log.LogError((object)"Rune Stones 0.1.3: патч WaterVolume.CalcWave не применён, «Штиль» не успокаивает физику в точном радиусе.");
			}
			if (!flag2)
			{
				Log.LogError((object)"Rune Stones 0.1.3: патч WaterVolume.Start не применён, видимого штиля не будет.");
			}
			if (!flag3)
			{
				Log.LogError((object)"Rune Stones 0.1.3: патч SpawnSystem.IsSpawnPointGood не применён, «Оберег» не запрещает появление монстров.");
			}
		}

		private static bool HasPostfix(MethodBase target)
		{
			return ((target == null) ? null : Harmony.GetPatchInfo(target))?.Postfixes.Any((Patch p) => p.owner == "sansara.RuneStones") ?? false;
		}

		private void Update()
		{
			if (s_applyPending)
			{
				s_applyPending = false;
				Prefabs.ApplySettings(log: true);
				RuneStone.ApplyAll();
				Log.LogInfo((object)("Рунные камни: " + s_applyReason + ". " + Summary()));
			}
		}

		private static void RequestApply(string reason)
		{
			if (!s_applyPending || reason != "настройки изменены")
			{
				s_applyReason = reason;
			}
			s_applyPending = true;
		}

		private static string Summary()
		{
			return string.Join(", ", RuneCatalog.All.Select((RuneDef r) => r.Key + ((!Settings.Enabled(r.Kind)) ? " выкл" : (r.HasRadius ? (" " + Settings.Radius(r.Kind).ToString("0.#") + " м") : (" +" + Settings.ComfortBonus.Value)))));
		}

		private static void AddLocalization()
		{
			CustomLocalization localization = LocalizationManager.Instance.GetLocalization();
			string text;
			string text2;
			foreach (RuneDef item in RuneCatalog.All)
			{
				text = "Russian";
				text2 = item.NameToken.Substring(1);
				localization.AddTranslation(ref text, ref text2, item.NameRu);
				text = "Russian";
				text2 = item.DescriptionToken.Substring(1);
				localization.AddTranslation(ref text, ref text2, item.DescriptionRu);
				text = "English";
				text2 = item.NameToken.Substring(1);
				localization.AddTranslation(ref text, ref text2, item.NameEn);
				text = "English";
				text2 = item.DescriptionToken.Substring(1);
				localization.AddTranslation(ref text, ref text2, item.DescriptionEn);
			}
			text = "Russian";
			text2 = "sansara_runestone_off";
			localization.AddTranslation(ref text, ref text2, "Руна отключена на сервере");
			text = "English";
			text2 = "sansara_runestone_off";
			localization.AddTranslation(ref text, ref text2, "The rune is disabled on the server");
		}
	}
	internal static class Prefabs
	{
		private sealed class GlowBase
		{
			public Color Color;

			public float[] LightIntensity = new float[0];

			public float[] ParticleAlpha = new float[0];

			public readonly List<Material> RuneMaterials = new List<Material>();
		}

		private const string BasePrefab = "guard_stone";

		private const string DemisterSource = "dverger_demister";

		private const string DemisterSourcePath = "_enabled/Particle System Force Field";

		private const float ModelScale = 1.5f;

		private const float EmissionBoost = 2f;

		private static readonly Dictionary<RuneKind, GameObject> s_prefabs = new Dictionary<RuneKind, GameObject>();

		private static bool s_created;

		private static readonly Dictionary<RuneKind, GlowBase> s_glow = new Dictionary<RuneKind, GlowBase>();

		private static bool Headless => (int)SystemInfo.graphicsDeviceType == 4;

		public static int Count => s_prefabs.Count;

		public static void Create()
		{
			//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)
			//IL_0047: 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_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			if (s_created)
			{
				return;
			}
			s_created = true;
			List<string> list = new List<string>();
			foreach (RuneDef item in RuneCatalog.All)
			{
				try
				{
					CustomPiece val = new CustomPiece(item.Prefab, "guard_stone", new PieceConfig
					{
						Name = item.NameToken,
						Description = item.DescriptionToken,
						PieceTable = "Hammer",
						Category = "Misc"
					});
					if ((Object)(object)val.PiecePrefab == (Object)null)
					{
						Plugin.Log.LogError((object)("Рунные камни: основа guard_stone не найдена, «" + item.NameRu + "» не создан."));
						continue;
					}
					Shape(val.PiecePrefab, item);
					if (!PieceManager.Instance.AddPiece(val))
					{
						Plugin.Log.LogError((object)("Рунные камни: Jotunn не принял постройку " + item.Prefab + "."));
						continue;
					}
					s_prefabs[item.Kind] = val.PiecePrefab;
					list.Add(item.Prefab);
				}
				catch (Exception arg)
				{
					Plugin.Log.LogError((object)$"Рунные камни: «{item.NameRu}» ({item.Prefab}) не создан: {arg}");
				}
			}
			ApplySettings(log: true);
			Plugin.Log.LogInfo((object)($"Рунные камни: зарегистрировано построек {list.Count} из {RuneCatalog.All.Count}: " + string.Join(", ", list) + "."));
		}

		public static void ApplySettings(bool log)
		{
			foreach (KeyValuePair<RuneKind, GameObject> s_prefab in s_prefabs)
			{
				RuneDef rune = RuneCatalog.Get(s_prefab.Key);
				RuneSettings runeSettings = Settings.Of(s_prefab.Key);
				GameObject value = s_prefab.Value;
				Piece component = value.GetComponent<Piece>();
				if ((Object)(object)component == (Object)null)
				{
					continue;
				}
				component.m_enabled = runeSettings.Enabled.Value;
				component.m_craftingStation = FindStation(rune, runeSettings.Station.Value);
				component.m_resources = BuildRequirements(rune, runeSettings.Recipe.Value, log);
				float num = Settings.Radius(s_prefab.Key);
				switch (s_prefab.Key)
				{
				case RuneKind.Hearth:
				{
					Transform obj2 = value.transform.Find("RuneArea");
					SphereCollider val2 = ((obj2 != null) ? ((Component)obj2).GetComponent<SphereCollider>() : null);
					if ((Object)(object)val2 != (Object)null)
					{
						val2.radius = num;
					}
					break;
				}
				case RuneKind.Clarity:
				{
					Transform obj = value.transform.Find("RuneDemister");
					ParticleSystemForceField val = ((obj != null) ? ((Component)obj).GetComponent<ParticleSystemForceField>() : null);
					if ((Object)(object)val != (Object)null)
					{
						val.endRange = num;
					}
					break;
				}
				case RuneKind.Comfort:
					component.m_comfort = (runeSettings.Enabled.Value ? Settings.ComfortBonus.Value : 0);
					break;
				}
				ApplyGlow(value, s_prefab.Key);
			}
		}

		public static void ApplyGlow(GameObject root, RuneKind kind)
		{
			//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_00ac: 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)
			//IL_00fe: 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)
			if ((Object)(object)root == (Object)null || !s_glow.TryGetValue(kind, out var value))
			{
				return;
			}
			float value2 = Settings.GlowIntensity.Value;
			Light[] componentsInChildren = root.GetComponentsInChildren<Light>(true);
			for (int i = 0; i < componentsInChildren.Length && i < value.LightIntensity.Length; i++)
			{
				componentsInChildren[i].intensity = GlowMath.Scale(value.LightIntensity[i], value2);
			}
			ParticleSystem[] componentsInChildren2 = root.GetComponentsInChildren<ParticleSystem>(true);
			for (int j = 0; j < componentsInChildren2.Length && j < value.ParticleAlpha.Length; j++)
			{
				MainModule main = componentsInChildren2[j].main;
				((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(new Color(value.Color.r, value.Color.g, value.Color.b, GlowMath.Scale(value.ParticleAlpha[j], value2)));
			}
			foreach (Material runeMaterial in value.RuneMaterials)
			{
				if ((Object)(object)runeMaterial != (Object)null)
				{
					runeMaterial.SetColor("_EmissionColor", value.Color * GlowMath.Scale(2f, value2));
				}
			}
		}

		private static void Shape(GameObject prefab, RuneDef rune)
		{
			//IL_004c: 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_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: 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_0162: Unknown result type (might be due to invalid IL or missing references)
			PrivateArea component = prefab.GetComponent<PrivateArea>();
			if ((Object)(object)component != (Object)null)
			{
				Object.DestroyImmediate((Object)(object)component);
			}
			DestroyChild(prefab, "AreaMarker");
			DestroyChild(prefab, "GuidePoint");
			Piece component2 = prefab.GetComponent<Piece>();
			component2.m_name = rune.NameToken;
			component2.m_description = rune.DescriptionToken;
			component2.m_category = (PieceCategory)0;
			((StaticTarget)component2).m_primaryTarget = false;
			((StaticTarget)component2).m_randomTarget = true;
			component2.m_comfort = 0;
			component2.m_comfortGroup = (ComfortGroup)0;
			component2.m_comfortObject = null;
			DestroyChild(prefab, "PlayerBase");
			EffectArea[] componentsInChildren = prefab.GetComponentsInChildren<EffectArea>(true);
			foreach (EffectArea val in componentsInChildren)
			{
				Plugin.Log.LogWarning((object)("Рунные камни: у основы guard_stone найдена ещё одна зона EffectArea " + $"({((Object)val).name}, {val.m_type}) — убрана с «{rune.NameRu}»."));
				Object.DestroyImmediate((Object)(object)val);
			}
			if (rune.Kind == RuneKind.Hearth)
			{
				AddArea(prefab, (Type)1);
			}
			if (rune.Kind == RuneKind.Clarity)
			{
				AddDemister(prefab);
			}
			prefab.AddComponent<RuneStone>().m_kind = (int)rune.Kind;
			Transform val2 = prefab.transform.Find("new");
			if ((Object)(object)val2 != (Object)null)
			{
				val2.localScale *= 1.5f;
			}
			Transform val3 = prefab.transform.Find("WayEffect");
			if ((Object)(object)val3 != (Object)null)
			{
				val3.localScale *= 1.5f;
				((Component)val3).gameObject.SetActive(true);
			}
			if (!Headless)
			{
				try
				{
					Paint(prefab, rune);
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Рунные камни: цвет «" + rune.NameRu + "» не применён: " + ex.Message));
				}
			}
		}

		private static void AddArea(GameObject prefab, Type type)
		{
			//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_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("RuneArea");
			val.transform.SetParent(prefab.transform, false);
			val.layer = LayerMask.NameToLayer("character_trigger");
			SphereCollider obj = val.AddComponent<SphereCollider>();
			((Collider)obj).isTrigger = true;
			obj.radius = 1f;
			val.AddComponent<EffectArea>().m_type = type;
		}

		private static void AddDemister(GameObject prefab)
		{
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			GameObject prefab2 = PrefabManager.Instance.GetPrefab("dverger_demister");
			Transform val = (((Object)(object)prefab2 != (Object)null) ? prefab2.transform.Find("_enabled/Particle System Force Field") : null);
			if ((Object)(object)val == (Object)null || (Object)(object)((Component)val).GetComponent<Demister>() == (Object)null || (Object)(object)((Component)val).GetComponent<ParticleSystemForceField>() == (Object)null)
			{
				Plugin.Log.LogError((object)"Рунные камни: рассеиватель dverger_demister/_enabled/Particle System Force Field не найден, «Ясность» не будет рассеивать туман.");
				return;
			}
			GameObject obj = Object.Instantiate<GameObject>(((Component)val).gameObject, prefab.transform);
			((Object)obj).name = "RuneDemister";
			obj.transform.localPosition = new Vector3(0f, 1f, 0f);
			obj.transform.localRotation = Quaternion.identity;
			obj.SetActive(true);
		}

		private static void Paint(GameObject prefab, RuneDef rune)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: 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_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			//IL_022e: Unknown result type (might be due to invalid IL or missing references)
			//IL_022f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Expected O, but got Unknown
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Expected O, but got Unknown
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			if (!RuneCatalog.TryParseColor(rune.ColorHex, out var r, out var g, out var b))
			{
				return;
			}
			Color val = default(Color);
			((Color)(ref val))..ctor(r, g, b, 1f);
			GlowBase glowBase = new GlowBase
			{
				Color = val
			};
			Light[] componentsInChildren = prefab.GetComponentsInChildren<Light>(true);
			glowBase.LightIntensity = new float[componentsInChildren.Length];
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				componentsInChildren[i].color = val;
				componentsInChildren[i].range = Mathf.Max(componentsInChildren[i].range, 6f);
				glowBase.LightIntensity[i] = componentsInChildren[i].intensity;
			}
			ParticleSystem[] componentsInChildren2 = prefab.GetComponentsInChildren<ParticleSystem>(true);
			glowBase.ParticleAlpha = new float[componentsInChildren2.Length];
			for (int j = 0; j < componentsInChildren2.Length; j++)
			{
				MainModule main = componentsInChildren2[j].main;
				MinMaxGradient startColor = ((MainModule)(ref main)).startColor;
				float num = (((int)((MinMaxGradient)(ref startColor)).mode == 0) ? ((MinMaxGradient)(ref startColor)).color.a : 1f);
				((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(new Color(r, g, b, num));
				glowBase.ParticleAlpha[j] = num;
			}
			MeshRenderer[] componentsInChildren3 = prefab.GetComponentsInChildren<MeshRenderer>(true);
			foreach (MeshRenderer val2 in componentsInChildren3)
			{
				Material[] sharedMaterials = ((Renderer)val2).sharedMaterials;
				bool flag = false;
				for (int l = 0; l < sharedMaterials.Length; l++)
				{
					Material val3 = sharedMaterials[l];
					if (!((Object)(object)val3 == (Object)null) && ((Object)val3).name.IndexOf("Glow", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						Material val4 = new Material(val3)
						{
							name = ((Object)val3).name + "_" + rune.Key
						};
						val4.EnableKeyword("_EMISSION");
						val4.SetColor("_EmissionColor", val * 2f);
						if (val4.HasProperty("_Color"))
						{
							val4.SetColor("_Color", val);
						}
						sharedMaterials[l] = val4;
						glowBase.RuneMaterials.Add(val4);
						flag = true;
					}
				}
				if (flag)
				{
					((Renderer)val2).sharedMaterials = sharedMaterials;
				}
			}
			Piece component = prefab.GetComponent<Piece>();
			Sprite val5 = RenderManager.Instance.Render(new RenderRequest(prefab)
			{
				Rotation = RenderManager.IsometricRotation,
				ParticleSimulationTime = -1f
			});
			if ((Object)(object)val5 != (Object)null)
			{
				component.m_icon = val5;
			}
			s_glow[rune.Kind] = glowBase;
		}

		private static void DestroyChild(GameObject prefab, string name)
		{
			Transform val = prefab.transform.Find(name);
			if ((Object)(object)val != (Object)null)
			{
				Object.DestroyImmediate((Object)(object)((Component)val).gameObject);
			}
		}

		private static CraftingStation FindStation(RuneDef rune, string name)
		{
			if (string.IsNullOrWhiteSpace(name))
			{
				return null;
			}
			CraftingStation prefab = Cache.GetPrefab<CraftingStation>(name.Trim());
			if ((Object)(object)prefab == (Object)null)
			{
				Plugin.Log.LogWarning((object)("Рунные камни: станка " + name + " нет в игре — «" + rune.NameRu + "» строится у " + rune.DefaultStation + "."));
				prefab = Cache.GetPrefab<CraftingStation>(rune.DefaultStation);
			}
			return prefab;
		}

		private static Requirement[] BuildRequirements(RuneDef rune, string recipe, bool log)
		{
			List<string> list = new List<string>();
			List<Requirement> list2 = Resolve(RecipeParser.Parse(recipe, list), list);
			if (list2.Count == 0)
			{
				list.Add("взят рецепт по умолчанию");
				list2 = Resolve(RecipeParser.Parse(rune.DefaultRecipe, list), list);
			}
			if (log)
			{
				foreach (string item in list)
				{
					Plugin.Log.LogWarning((object)("Рунные камни: рецепт «" + rune.NameRu + "» — " + item + "."));
				}
			}
			return list2.ToArray();
		}

		private static List<Requirement> Resolve(List<Cost> costs, List<string> errors)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			List<Requirement> list = new List<Requirement>();
			foreach (Cost cost in costs)
			{
				ItemDrop prefab = Cache.GetPrefab<ItemDrop>(cost.Item);
				if ((Object)(object)prefab == (Object)null)
				{
					errors.Add("предмета " + cost.Item + " нет в игре");
					continue;
				}
				list.Add(new Requirement
				{
					m_resItem = prefab,
					m_amount = cost.Amount,
					m_recover = true
				});
			}
			return list;
		}
	}
	[HarmonyPatch(typeof(WearNTear), "Awake")]
	internal static class RepairRpc
	{
		public const string RpcName = "SansaraRuneStones_Heal";

		private static readonly FieldRef<WearNTear, ZNetView> s_nview = AccessTools.FieldRefAccess<WearNTear, ZNetView>("m_nview");

		private static void Postfix(WearNTear __instance, ZNetView ___m_nview)
		{
			if (!((Object)(object)___m_nview == (Object)null) && ___m_nview.GetZDO() != null)
			{
				WearNTear piece = __instance;
				ZNetView nview = ___m_nview;
				nview.Register<float>("SansaraRuneStones_Heal", (Action<long, float>)delegate(long sender, float fraction)
				{
					Heal(piece, nview, fraction);
				});
			}
		}

		public static void Send(WearNTear piece, float fraction)
		{
			ZNetView val = s_nview.Invoke(piece);
			if ((Object)(object)val != (Object)null && val.IsValid())
			{
				val.InvokeRPC("SansaraRuneStones_Heal", new object[1] { fraction });
			}
		}

		private static void Heal(WearNTear piece, ZNetView nview, float fraction)
		{
			if (!((Object)(object)piece == (Object)null) && !((Object)(object)nview == (Object)null) && nview.IsValid() && nview.IsOwner() && Settings.Enabled(RuneKind.Repair))
			{
				ZDO zDO = nview.GetZDO();
				float health = piece.m_health;
				float num = zDO.GetFloat(ZDOVars.s_health, health);
				float num2 = RepairMath.Heal(num, health, fraction, RepairMath.Fraction(Settings.RepairHealPercent.Value));
				if (num2 > num)
				{
					zDO.Set(ZDOVars.s_health, num2);
					nview.InvokeRPC(ZNetView.Everybody, "RPC_HealthChanged", new object[1] { num2 });
				}
			}
		}
	}
	public sealed class RuneStone : MonoBehaviour, Hoverable
	{
		public const string AreaChild = "RuneArea";

		public const string DemisterChild = "RuneDemister";

		public int m_kind;

		private static readonly List<RuneStone> s_instances = new List<RuneStone>();

		private static readonly List<RepairCandidate> s_candidates = new List<RepairCandidate>();

		private static readonly List<WearNTear> s_candidatePieces = new List<WearNTear>();

		private static readonly List<int> s_picked = new List<int>();

		private static readonly FieldRef<HashSet<Piece>> s_comfortPieces = AccessTools.StaticFieldRefAccess<HashSet<Piece>>(AccessTools.Field(typeof(Piece), "s_allComfortPieces"));

		private ZNetView m_nview;

		private Piece m_piece;

		private RuneDef m_rune;

		private float m_repairElapsed;

		private bool m_live;

		private void Awake()
		{
			m_nview = ((Component)this).GetComponent<ZNetView>();
			m_piece = ((Component)this).GetComponent<Piece>();
			m_rune = RuneCatalog.Get(m_kind);
			if (m_rune != null && !((Object)(object)m_nview == (Object)null) && m_nview.IsValid())
			{
				m_live = true;
				s_instances.Add(this);
				if (m_rune.Kind == RuneKind.Calm)
				{
					CalmField.Register(this);
				}
				if (m_rune.Kind == RuneKind.Ward)
				{
					WardField.Register(this);
				}
				if (m_rune.Kind == RuneKind.Repair)
				{
					((MonoBehaviour)this).InvokeRepeating("RepairTick", Random.Range(1f, 2f), 1f);
				}
				Apply();
			}
		}

		private void OnDestroy()
		{
			if (m_live)
			{
				s_instances.Remove(this);
				if (m_rune.Kind == RuneKind.Calm)
				{
					CalmField.Unregister(this);
				}
				if (m_rune.Kind == RuneKind.Ward)
				{
					WardField.Unregister(this);
				}
				if (m_rune.Kind == RuneKind.Comfort && (Object)(object)m_piece != (Object)null)
				{
					s_comfortPieces.Invoke().Remove(m_piece);
				}
			}
		}

		public static void ApplyAll()
		{
			s_instances.RemoveAll((RuneStone s) => (Object)(object)s == (Object)null);
			foreach (RuneStone s_instance in s_instances)
			{
				s_instance.Apply();
			}
			CalmField.Rebuild();
			WardField.Rebuild();
		}

		private void Apply()
		{
			bool flag = Settings.Enabled(m_rune.Kind);
			float num = Settings.Radius(m_rune.Kind);
			Prefabs.ApplyGlow(((Component)this).gameObject, m_rune.Kind);
			switch (m_rune.Kind)
			{
			case RuneKind.Hearth:
			{
				Transform val = ((Component)this).transform.Find("RuneArea");
				if ((Object)(object)val != (Object)null)
				{
					SphereCollider component = ((Component)val).GetComponent<SphereCollider>();
					if ((Object)(object)component != (Object)null)
					{
						component.radius = num;
					}
					((Component)val).gameObject.SetActive(flag);
				}
				break;
			}
			case RuneKind.Clarity:
			{
				Transform val2 = ((Component)this).transform.Find("RuneDemister");
				if ((Object)(object)val2 != (Object)null)
				{
					ParticleSystemForceField component2 = ((Component)val2).GetComponent<ParticleSystemForceField>();
					if ((Object)(object)component2 != (Object)null)
					{
						component2.endRange = num;
					}
					((Component)val2).gameObject.SetActive(flag);
				}
				break;
			}
			case RuneKind.Comfort:
				if ((Object)(object)m_piece != (Object)null)
				{
					m_piece.m_comfort = (flag ? Settings.ComfortBonus.Value : 0);
					if (m_piece.m_comfort > 0)
					{
						s_comfortPieces.Invoke().Add(m_piece);
					}
					else
					{
						s_comfortPieces.Invoke().Remove(m_piece);
					}
				}
				break;
			}
		}

		private void RepairTick()
		{
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			if (!Settings.Enabled(RuneKind.Repair) || (Object)(object)m_nview == (Object)null || !m_nview.IsValid() || !m_nview.IsOwner())
			{
				m_repairElapsed = 0f;
				return;
			}
			m_repairElapsed += 1f;
			if (!RepairPicker.IsDue(m_repairElapsed, Settings.RepairInterval.Value))
			{
				return;
			}
			m_repairElapsed = 0f;
			float num = RepairMath.Fraction(Settings.RepairHealPercent.Value);
			if (!(num > 0f))
			{
				return;
			}
			float num2 = Settings.Radius(RuneKind.Repair);
			float num3 = num2 * num2;
			Vector3 position = ((Component)this).transform.position;
			s_candidates.Clear();
			s_candidatePieces.Clear();
			List<WearNTear> allInstances = WearNTear.GetAllInstances();
			for (int i = 0; i < allInstances.Count; i++)
			{
				WearNTear val = allInstances[i];
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Vector3 val2 = ((Component)val).transform.position - position;
				float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude;
				if (!(sqrMagnitude > num3))
				{
					float healthPercentage = val.GetHealthPercentage();
					if (!(healthPercentage >= 1f) && !(healthPercentage <= 0f))
					{
						s_candidates.Add(new RepairCandidate(s_candidatePieces.Count, healthPercentage, Mathf.Sqrt(sqrMagnitude)));
						s_candidatePieces.Add(val);
					}
				}
			}
			if (s_candidates.Count != 0)
			{
				RepairPicker.Pick(s_candidates, num2, Settings.RepairMaxPieces.Value, s_picked);
				for (int j = 0; j < s_picked.Count; j++)
				{
					RepairRpc.Send(s_candidatePieces[s_picked[j]], num);
				}
				s_candidatePieces.Clear();
			}
		}

		public string GetHoverText()
		{
			if (m_rune == null)
			{
				return "";
			}
			string text = Localization.instance.Localize(m_rune.NameToken);
			if (m_live && !Settings.Enabled(m_rune.Kind))
			{
				text = text + "\n<color=#A0A0A0>" + Localization.instance.Localize("$sansara_runestone_off") + "</color>";
			}
			return text;
		}

		public string GetHoverName()
		{
			if (m_rune != null)
			{
				return Localization.instance.Localize(m_rune.NameToken);
			}
			return "";
		}

		public float GetHoverOffset()
		{
			return 0f;
		}
	}
	internal sealed class RuneSettings
	{
		public ConfigEntry<bool> Enabled;

		public ConfigEntry<string> Station;

		public ConfigEntry<string> Recipe;

		public ConfigEntry<float> Radius;
	}
	internal static class Settings
	{
		private static readonly Dictionary<RuneKind, RuneSettings> s_runes = new Dictionary<RuneKind, RuneSettings>();

		public static ConfigEntry<float> RepairInterval;

		public static ConfigEntry<float> RepairHealPercent;

		public static ConfigEntry<int> RepairMaxPieces;

		public static ConfigEntry<float> CalmEdgeWidth;

		public static ConfigEntry<float> CalmStrength;

		public static ConfigEntry<int> ComfortBonus;

		public static ConfigEntry<float> CalmVisualRadius;

		public static ConfigEntry<float> GlowIntensity;

		public static void Bind(ConfigFile config)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			GlowIntensity = config.Bind<float>("Visual", "GlowIntensity", 0.15f, new ConfigDescription("Яркость рунных камней на этом клиенте (настройка клиента, сервер её не задаёт): множитель 0–1 к свету камня, свечению вырезанных рун и частицам. 1 — вид версии 0.1.0, 0 — камень не светится. Применяется сразу ко всем шести камням, включая стоящие.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			foreach (RuneDef item in RuneCatalog.All)
			{
				RuneSettings runeSettings = new RuneSettings
				{
					Enabled = config.Bind<bool>(item.Key, "Enabled", true, Admin("«" + item.NameRu + "»: можно строить, а стоящие камни действуют. false — камень убран из молота, стоящие камни остаются, но не действуют.")),
					Station = config.Bind<string>(item.Key, "Station", item.DefaultStation, Admin("Префаб станка, рядом с которым строится камень (piece_workbench, piece_stonecutter, forge…). Пусто — станок не нужен.")),
					Recipe = config.Bind<string>(item.Key, "Recipe", item.DefaultRecipe, Admin($"Стоимость: «Предмет:количество» через запятую, не больше {4} предметов " + "(имена префабов предметов). При разборе камня материалы возвращаются. Нераспознанный рецепт заменяется рецептом по умолчанию."))
				};
				if (item.HasRadius)
				{
					runeSettings.Radius = config.Bind<float>(item.Key, "Radius", item.DefaultRadius, Admin(RadiusText(item.Kind), (AcceptableValueBase)(object)new AcceptableValueRange<float>(item.MinRadius, item.MaxRadius)));
				}
				s_runes[item.Kind] = runeSettings;
				switch (item.Kind)
				{
				case RuneKind.Repair:
					RepairInterval = config.Bind<float>(item.Key, "Interval", 10f, Admin("Шаг починки, с: раз во столько секунд каждая повреждённая постройка и корабль в радиусе получают HealPercent своей полной прочности.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 600f)));
					RepairHealPercent = config.Bind<float>(item.Key, "HealPercent", 2f, Admin("Сколько процентов полной прочности часть получает за один шаг. 2 при шаге 10 с — около 12 % в минуту, полностью разбитая часть восстанавливается за ~8 минут. 100 — сразу до полной, как молотом. Это же значение — верхний предел для запросов починки от клиентов.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 100f)));
					RepairMaxPieces = config.Bind<int>(item.Key, "MaxPiecesPerTick", 20, Admin("Не больше скольких частей один камень чинит за шаг (ограничение сетевого трафика: одно сообщение на часть). Если повреждённых больше — самые повреждённые первыми, остальные ждут. Заменяет ключ PiecesPerTick версий 0.1.0–0.1.2 (он больше не читается).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100)));
					break;
				case RuneKind.Calm:
					CalmEdgeWidth = config.Bind<float>(item.Key, "EdgeWidth", 10f, Admin("Ширина переходной полосы у границы радиуса, м: в ней волна плавно растёт от спокойной до обычной. Больше радиуса не бывает.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f)));
					CalmStrength = config.Bind<float>(item.Key, "Strength", 1f, Admin("Доля высоты волны, которую камень убирает внутри радиуса: 1 — полный штиль, 0.5 — волна вдвое ниже, 0 — без действия.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f)));
					CalmVisualRadius = config.Bind<float>(item.Key, "VisualRadius", 70f, Admin("Радиус видимого штиля, м: в нём гасятся и нарисованные волны (через глубины углов плиток воды, сетка 64 м — зона выходит крупнее и грубее, чем Radius; подробности в README). Меньше ~46 м камень в середине плитки ничего не изменит. 0 — нарисованная вода не меняется, спокойна только физика в Radius.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 200f)));
					break;
				case RuneKind.Comfort:
					ComfortBonus = config.Bind<int>(item.Key, "Bonus", 2, Admin("Сколько комфорта даёт камень. Считается игрой: под крышей, в 10 м от игрока, несколько таких камней не складываются.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 5)));
					break;
				}
			}
		}

		public static RuneSettings Of(RuneKind kind)
		{
			return s_runes[kind];
		}

		public static bool Enabled(RuneKind kind)
		{
			if (s_runes.TryGetValue(kind, out var value))
			{
				return value.Enabled.Value;
			}
			return false;
		}

		public static float Radius(RuneKind kind)
		{
			if (!s_runes.TryGetValue(kind, out var value) || value.Radius == null)
			{
				return 0f;
			}
			return value.Radius.Value;
		}

		private static string RadiusText(RuneKind kind)
		{
			return kind switch
			{
				RuneKind.Repair => "Радиус, м: постройки и корабли ближе этого расстояния понемногу чинятся.", 
				RuneKind.Calm => "Радиус, м (по горизонтали): за ним волны обычные.", 
				RuneKind.Hearth => "Радиус тепла, м (у костра в игре 8 м).", 
				RuneKind.Clarity => "Радиус без тумана, м. Большой радиус тратит больше частиц тумана на клиенте.", 
				RuneKind.Ward => "Радиус, м (по горизонтали), в котором не появляются монстры биома и участники набегов. Обитателей локаций, гнёзда и призывы камень не останавливает; зоны базы у него нет.", 
				_ => "Радиус, м.", 
			};
		}

		private static ConfigDescription Admin(string text, AcceptableValueBase range = null)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			return new ConfigDescription(text, range, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} });
		}
	}
	internal static class WardField
	{
		private static readonly List<RuneStone> s_stones = new List<RuneStone>();

		private static readonly float[] s_none = new float[0];

		private static float[] s_xz = s_none;

		private static float s_radius;

		public static int Count => s_xz.Length;

		public static void Register(RuneStone stone)
		{
			if (!s_stones.Contains(stone))
			{
				s_stones.Add(stone);
			}
			Rebuild();
		}

		public static void Unregister(RuneStone stone)
		{
			if (s_stones.Remove(stone))
			{
				Rebuild();
			}
		}

		public static void Rebuild()
		{
			//IL_0086: 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_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			s_stones.RemoveAll((RuneStone s) => (Object)(object)s == (Object)null);
			s_radius = Settings.Radius(RuneKind.Ward);
			if (!Settings.Enabled(RuneKind.Ward) || !(s_radius > 0f) || s_stones.Count == 0)
			{
				s_xz = s_none;
				return;
			}
			float[] array = new float[s_stones.Count * 2];
			for (int num = 0; num < s_stones.Count; num++)
			{
				Vector3 position = ((Component)s_stones[num]).transform.position;
				array[num * 2] = position.x;
				array[num * 2 + 1] = position.z;
			}
			s_xz = array;
		}

		public static bool Covers(float x, float z)
		{
			return WardMath.Covers(s_xz, s_radius, x, z);
		}
	}
	[HarmonyPatch(typeof(SpawnSystem), "IsSpawnPointGood")]
	internal static class SpawnPointPatch
	{
		private static void Postfix(Vector3 spawnPoint, ref bool __result)
		{
			//IL_000b: 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)
			if (__result && WardField.Count != 0 && WardField.Covers(spawnPoint.x, spawnPoint.z))
			{
				__result = false;
			}
		}
	}
}
namespace RuneStones.Core
{
	public static class CalmDepth
	{
		public const int Corners = 4;

		public const float NoSingleDepth = -1f;

		public static int SignX(int corner)
		{
			if (corner != 1 && corner != 2)
			{
				return -1;
			}
			return 1;
		}

		public static int SignZ(int corner)
		{
			if (corner != 0 && corner != 1)
			{
				return -1;
			}
			return 1;
		}

		public static bool Tracks(bool hasHeightmap, float forceDepth)
		{
			if (hasHeightmap)
			{
				return forceDepth < 0f;
			}
			return false;
		}

		public static void Apply(float[] original, float[] factors, float[] target)
		{
			for (int i = 0; i < 4; i++)
			{
				float num = factors[i];
				if (float.IsNaN(num) || num >= 1f)
				{
					target[i] = original[i];
				}
				else if (num <= 0f)
				{
					target[i] = 0f;
				}
				else
				{
					target[i] = original[i] * num;
				}
			}
		}

		public static bool IsIdentity(float[] factors)
		{
			for (int i = 0; i < 4; i++)
			{
				if (factors[i] < 1f)
				{
					return false;
				}
			}
			return true;
		}

		public static float OneDepth(float[] depths)
		{
			if (!depths[0].Equals(depths[2]) || !depths[1].Equals(depths[3]) || !depths[0].Equals(depths[1]))
			{
				return -1f;
			}
			return depths[0];
		}
	}
	public static class GlowMath
	{
		public const float Default = 0.15f;

		public static float Scale(float value, float glow)
		{
			if (float.IsNaN(glow) || glow >= 1f)
			{
				return value;
			}
			if (!(glow <= 0f))
			{
				return value * glow;
			}
			return 0f;
		}
	}
	public static class CalmMath
	{
		public static float Factor(float distance, float radius, float edge, float strength)
		{
			if (!(radius > 0f) || float.IsNaN(distance))
			{
				return 1f;
			}
			float num = 1f - Clamp01(strength);
			if (distance >= radius)
			{
				return 1f;
			}
			float num2 = ((float.IsNaN(edge) || edge < 0f) ? 0f : Math.Min(edge, radius));
			float num3 = radius - num2;
			if (distance <= num3 || num2 <= 0f)
			{
				return num;
			}
			float num4 = (distance - num3) / num2;
			float num5 = num4 * num4 * (3f - 2f * num4);
			return num + (1f - num) * num5;
		}

		public static float FactorSqr(float distanceSqr, float radius, float edge, float strength)
		{
			if (!(radius > 0f) || float.IsNaN(distanceSqr) || distanceSqr >= radius * radius)
			{
				return 1f;
			}
			return Factor((float)Math.Sqrt(Math.Max(0f, distanceSqr)), radius, edge, strength);
		}

		public static float Combine(float a, float b)
		{
			if (!(a < b))
			{
				return b;
			}
			return a;
		}

		private static float Clamp01(float value)
		{
			if (float.IsNaN(value) || value <= 0f)
			{
				return 0f;
			}
			if (!(value >= 1f))
			{
				return value;
			}
			return 1f;
		}
	}
	public sealed class Cost
	{
		public string Item { get; }

		public int Amount { get; }

		public Cost(string item, int amount)
		{
			Item = item;
			Amount = amount;
		}
	}
	public static class RecipeParser
	{
		public const int MaxEntries = 4;

		public static List<Cost> Parse(string text, List<string> errors)
		{
			List<Cost> list = new List<Cost>();
			if (string.IsNullOrWhiteSpace(text))
			{
				errors.Add("рецепт пуст");
				return list;
			}
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			bool flag = false;
			string[] array = text.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (text2.Length != 0)
				{
					string[] array2 = text2.Split(new char[1] { ':' });
					string text3 = ((array2.Length == 2) ? array2[0].Trim() : "");
					int result = 0;
					if (array2.Length != 2 || text3.Length <= 0 || !int.TryParse(array2[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out result) || result <= 0)
					{
						errors.Add("запись «" + text2 + "» не разобрана (нужно Предмет:количество, количество > 0)");
					}
					else if (!hashSet.Add(text3))
					{
						errors.Add("предмет " + text3 + " указан дважды, взято первое количество");
					}
					else if (list.Count >= 4)
					{
						flag = true;
					}
					else
					{
						list.Add(new Cost(text3, result));
					}
				}
			}
			if (flag)
			{
				errors.Add($"в рецепте больше {4} предметов, лишние отброшены");
			}
			if (list.Count == 0 && errors.Count == 0)
			{
				errors.Add("рецепт пуст");
			}
			return list;
		}

		public static string Format(IList<Cost> costs)
		{
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < costs.Count; i++)
			{
				if (i > 0)
				{
					stringBuilder.Append(", ");
				}
				stringBuilder.Append(costs[i].Item).Append(':').Append(costs[i].Amount.ToString(CultureInfo.InvariantCulture));
			}
			return stringBuilder.ToString();
		}
	}
	public static class RepairMath
	{
		public const float DefaultHealPercent = 2f;

		public const float MinHealPercent = 0.1f;

		public const float MaxHealPercent = 100f;

		public const int DefaultMaxPieces = 20;

		public const int MaxPiecesLimit = 100;

		public static float Fraction(float percent)
		{
			if (!(percent > 0f))
			{
				return 0f;
			}
			float num = percent / 100f;
			if (!(num < 1f))
			{
				return 1f;
			}
			return num;
		}

		public static float Heal(float current, float max, float fraction, float limit)
		{
			if (!(max > 0f) || float.IsInfinity(max))
			{
				return current;
			}
			if (!(current > 0f) || !(current < max))
			{
				return current;
			}
			if (!(fraction > 0f) || !(limit > 0f))
			{
				return current;
			}
			float num = ((fraction < limit) ? fraction : limit);
			if (num > 1f)
			{
				num = 1f;
			}
			float num2 = current + num * max;
			if (!(num2 < max))
			{
				return max;
			}
			return num2;
		}
	}
	public struct RepairCandidate
	{
		public int Id;

		public float HealthFraction;

		public float Distance;

		public RepairCandidate(int id, float healthFraction, float distance)
		{
			Id = id;
			HealthFraction = healthFraction;
			Distance = distance;
		}
	}
	public static class RepairPicker
	{
		public const float MinInterval = 1f;

		private static readonly Comparison<RepairCandidate> s_compare = Compare;

		private static readonly List<RepairCandidate> s_pool = new List<RepairCandidate>();

		public static List<int> Pick(IList<RepairCandidate> candidates, float radius, int count)
		{
			List<int> list = new List<int>();
			Pick(candidates, radius, count, list);
			return list;
		}

		public static void Pick(IList<RepairCandidate> candidates, float radius, int count, List<int> picked)
		{
			picked.Clear();
			if (candidates == null || count <= 0)
			{
				return;
			}
			lock (s_pool)
			{
				s_pool.Clear();
				for (int i = 0; i < candidates.Count; i++)
				{
					RepairCandidate item = candidates[i];
					if (item.HealthFraction > 0f && item.HealthFraction < 1f && item.Distance <= radius)
					{
						s_pool.Add(item);
					}
				}
				s_pool.Sort(s_compare);
				for (int j = 0; j < s_pool.Count && j < count; j++)
				{
					picked.Add(s_pool[j].Id);
				}
				s_pool.Clear();
			}
		}

		public static bool IsDue(float elapsed, float interval)
		{
			float num = ((interval > 1f) ? interval : 1f);
			return elapsed >= num;
		}

		private static int Compare(RepairCandidate a, RepairCandidate b)
		{
			int num = a.HealthFraction.CompareTo(b.HealthFraction);
			if (num != 0)
			{
				return num;
			}
			int num2 = a.Distance.CompareTo(b.Distance);
			if (num2 == 0)
			{
				return a.Id.CompareTo(b.Id);
			}
			return num2;
		}
	}
	public enum RuneKind
	{
		Repair,
		Calm,
		Hearth,
		Clarity,
		Comfort,
		Ward
	}
	public sealed class RuneDef
	{
		public RuneKind Kind;

		public string Key;

		public string Prefab;

		public string NameToken;

		public string DescriptionToken;

		public string NameRu;

		public string NameEn;

		public string DescriptionRu;

		public string DescriptionEn;

		public string ColorHex;

		public string DefaultStation;

		public string DefaultRecipe;

		public bool HasRadius;

		public float DefaultRadius;

		public float MinRadius;

		public float MaxRadius;
	}
	public static class RuneCatalog
	{
		public const string Workbench = "piece_workbench";

		public const string Stonecutter = "piece_stonecutter";

		public static readonly IReadOnlyList<RuneDef> All = new List<RuneDef>
		{
			Make(RuneKind.Repair, "Repair", "FF9A2E", "piece_stonecutter", "Stone:30, Iron:10, ElderBark:20, SurtlingCore:5", 20f, 1f, 60f, "Рунный камень: Починка", "Runestone: Repair", "Постройки и корабли рядом с камнем понемногу чинятся сами.", "Buildings and ships near the stone slowly mend themselves."),
			Make(RuneKind.Calm, "Calm", "2E9BFF", "piece_stonecutter", "Stone:30, Chitin:20, SerpentScale:5, Silver:5", 30f, 5f, 100f, "Рунный камень: Штиль", "Runestone: Calm", "Волны рядом с камнем не качают корабли и пловцов при любом ветре.", "Waves near the stone do not rock ships and swimmers in any wind."),
			Make(RuneKind.Hearth, "Hearth", "FF3B1F", "piece_workbench", "Stone:20, SurtlingCore:5, Coal:20, Resin:10", 10f, 1f, 30f, "Рунный камень: Очаг", "Runestone: Hearth", "Греет как костёр: рядом можно согреться, обсохнуть и отдохнуть.", "Warms like a campfire: get warm, dry and rested nearby."),
			Make(RuneKind.Clarity, "Clarity", "BFF6FF", "piece_stonecutter", "BlackMarble:30, Wisp:30, Eitr:10, YggdrasilWood:20", 20f, 1f, 40f, "Рунный камень: Ясность", "Runestone: Clarity", "Рассеивает туман Туманных земель вокруг камня.", "Disperses the mist of the Mistlands around the stone."),
			Make(RuneKind.Comfort, "Comfort", "5CFF7A", "piece_workbench", "Stone:20, FineWood:20, AmberPearl:5, Ruby:2", 0f, 0f, 0f, "Рунный камень: Покой", "Runestone: Comfort", "Прибавляет комфорт отдыхающим под крышей рядом с камнем.", "Adds comfort to those resting under a roof near the stone."),
			Make(RuneKind.Ward, "Ward", "B04DFF", "piece_stonecutter", "Stone:40, BlackMetal:20, Needle:20, Crystal:10", 30f, 1f, 100f, "Рунный камень: Оберег", "Runestone: Ward", "Рядом с камнем монстры не появляются.", "Monsters do not spawn near the stone.")
		};

		public static RuneDef Get(RuneKind kind)
		{
			return Get((int)kind);
		}

		public static RuneDef Get(int kind)
		{
			for (int i = 0; i < All.Count; i++)
			{
				if (All[i].Kind == (RuneKind)kind)
				{
					return All[i];
				}
			}
			return null;
		}

		public static bool TryParseColor(string hex, out float r, out float g, out float b)
		{
			r = (g = (b = 0f));
			if (hex == null)
			{
				return false;
			}
			string text = hex.Trim().TrimStart(new char[1] { '#' });
			if (text.Length != 6 || !int.TryParse(text, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var result))
			{
				return false;
			}
			r = (float)((result >> 16) & 0xFF) / 255f;
			g = (float)((result >> 8) & 0xFF) / 255f;
			b = (float)(result & 0xFF) / 255f;
			return true;
		}

		private static RuneDef Make(RuneKind kind, string key, string color, string station, string recipe, float radius, float minRadius, float maxRadius, string nameRu, string nameEn, string descRu, string descEn)
		{
			string text = key.ToLowerInvariant();
			return new RuneDef
			{
				Kind = kind,
				Key = key,
				Prefab = "sansara_runestone_" + text,
				NameToken = "$sansara_runestone_" + text,
				DescriptionToken = "$sansara_runestone_" + text + "_desc",
				NameRu = nameRu,
				NameEn = nameEn,
				DescriptionRu = descRu,
				DescriptionEn = descEn,
				ColorHex = color,
				DefaultStation = station,
				DefaultRecipe = recipe,
				HasRadius = (maxRadius > 0f),
				DefaultRadius = radius,
				MinRadius = minRadius,
				MaxRadius = maxRadius
			};
		}
	}
	public static class WardMath
	{
		public static bool InRange(float dx, float dz, float radius)
		{
			if (!(radius > 0f))
			{
				return false;
			}
			return dx * dx + dz * dz <= radius * radius;
		}

		public static bool Covers(float[] xz, float radius, float x, float z)
		{
			if (xz == null || !(radius > 0f))
			{
				return false;
			}
			float num = radius * radius;
			for (int i = 0; i + 1 < xz.Length; i += 2)
			{
				float num2 = x - xz[i];
				float num3 = z - xz[i + 1];
				if (num2 * num2 + num3 * num3 <= num)
				{
					return true;
				}
			}
			return false;
		}
	}
}