Decompiled source of SturdyStructures v0.1.0

plugins/SturdyStructures.dll

Decompiled 3 days 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.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using SturdyStructures.Core;

[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("SturdyStructures")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+448334db3d4c5df8b4978e836b09a015ed76936a")]
[assembly: AssemblyProduct("SturdyStructures")]
[assembly: AssemblyTitle("SturdyStructures")]
[assembly: AssemblyVersion("0.1.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[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 SturdyStructures
{
	[BepInPlugin("sansara.SturdyStructures", "Sturdy Structures", "0.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Guid = "sansara.SturdyStructures";

		public const string Name = "Sturdy Structures";

		public const string Version = "0.1.0";

		private static readonly string[] SettingOrder = new string[9] { "Wood", "HardWood", "Stone", "Iron", "Marble", "Ashstone", "Ancient", "Ice", "Timberwood" };

		private static readonly Dictionary<string, string> Descriptions = new Dictionary<string, string>
		{
			["Wood"] = "Дерево: обычные деревянные части и большая часть мебели.",
			["HardWood"] = "Брёвна и ядровая древесина (wood_log_*, wood_pole_log*, wood_wall_log*), части двергров.",
			["Stone"] = "Камень (стены, полы, лестницы из камня).",
			["Iron"] = "Железо: балки и столбы из дерева с железом и огнеметалла, железные полы, стены, решётки, ворота, сундуки.",
			["Marble"] = "Чёрный мрамор.",
			["Ashstone"] = "Грауштейн (Piece_grausten_*) и часть руин Пепельных земель.",
			["Ancient"] = "Только руины Пепельных земель (игроку не строится).",
			["Ice"] = "Ледяной куб (piece_icecube).",
			["Timberwood"] = "Брус: балки, столбы и стены stave_*."
		};

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		private static readonly Dictionary<string, ConfigEntry<float>> s_reach = new Dictionary<string, ConfigEntry<float>>();

		private static List<KeyValuePair<string, int>> s_enumValues;

		internal static float[] Table = new float[0];

		private static bool s_logPending;

		private static string s_logReason;

		private void Awake()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//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_00d5: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Expected I4, but got Unknown
			//IL_0236: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Server", "Enabled", true, new ConfigDescription("Увеличивать дальность опоры построек множителями ниже. false — опора как в игре.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
			string[] settingOrder = SettingOrder;
			foreach (string text in settingOrder)
			{
				float num = ((text == "Iron") ? 2f : 1f);
				s_reach[text] = ((BaseUnityPlugin)this).Config.Bind<float>("Server", text + "Reach", num, new ConfigDescription("Множитель дальности опоры для материала " + text + ": потери опоры по горизонтали и вертикали делятся на него, 1 — как в игре. " + Descriptions[text], (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), new object[1] { (object)new ConfigurationManagerAttributes
				{
					IsAdminOnly = true
				} }));
			}
			s_enumValues = new List<KeyValuePair<string, int>>();
			foreach (MaterialType value in Enum.GetValues(typeof(MaterialType)))
			{
				s_enumValues.Add(new KeyValuePair<string, int>(((object)value/*cast due to .constrained prefix*/).ToString(), (int)value));
			}
			settingOrder = SettingOrder;
			foreach (string material in settingOrder)
			{
				if (!s_enumValues.Exists((KeyValuePair<string, int> p) => p.Key == material))
				{
					Log.LogWarning((object)("В игре нет материала " + material + ": настройка " + material + "Reach не действует."));
				}
			}
			Rebuild();
			((BaseUnityPlugin)this).Config.SettingChanged += delegate
			{
				Rebuild();
				RequestLog("настройки изменены");
			};
			SynchronizationManager.OnConfigurationSynchronized += delegate(object _, ConfigurationSynchronizationEventArgs e)
			{
				Rebuild();
				RequestLog(e.InitialSynchronization ? "получены настройки сервера" : "обновлены настройки сервера");
			};
			new Harmony("sansara.SturdyStructures").PatchAll();
			MethodInfo methodInfo = AccessTools.Method(typeof(WearNTear), "GetMaterialProperties", (Type[])null, (Type[])null);
			Patches val2 = ((methodInfo == null) ? null : Harmony.GetPatchInfo((MethodBase)methodInfo));
			if (val2 != null && val2.Postfixes.Any((Patch p) => p.owner == "sansara.SturdyStructures"))
			{
				Log.LogInfo((object)("Sturdy Structures 0.1.0 загружен, патч WearNTear.GetMaterialProperties применён. " + Summary()));
			}
			else
			{
				Log.LogError((object)"Sturdy Structures 0.1.0: патч WearNTear.GetMaterialProperties не применён, опора как в игре.");
			}
		}

		private void Update()
		{
			if (s_logPending)
			{
				s_logPending = false;
				Log.LogInfo((object)(s_logReason + ". " + Summary()));
			}
		}

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

		private static void Rebuild()
		{
			Dictionary<string, float> dictionary = new Dictionary<string, float>();
			foreach (KeyValuePair<string, ConfigEntry<float>> item in s_reach)
			{
				dictionary[item.Key] = item.Value.Value;
			}
			Table = SupportMath.BuildTable(Enabled.Value, s_enumValues, dictionary);
		}

		private static string Summary()
		{
			return "Дальность опоры (" + (Enabled.Value ? "включено" : "выключено, всё как в игре") + "): " + SupportMath.Describe(Table, s_enumValues);
		}
	}
	[HarmonyPatch(typeof(WearNTear), "GetMaterialProperties")]
	internal static class GetMaterialPropertiesPatch
	{
		private static void Postfix(WearNTear __instance, ref float horizontalLoss, ref float verticalLoss)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected I4, but got Unknown
			SupportMath.ApplyReach(ref horizontalLoss, ref verticalLoss, SupportMath.Lookup(Plugin.Table, (int)__instance.m_materialType));
		}
	}
}
namespace SturdyStructures.Core
{
	public static class SupportMath
	{
		public const float MinReach = 1f;

		public const float MaxReach = 10f;

		public const float VanillaReach = 1f;

		public const float BeamStep = 2.1f;

		public const float BeamLength = 2f;

		public static readonly string[] MaterialNames = new string[9] { "Wood", "Stone", "Iron", "HardWood", "Marble", "Ashstone", "Ancient", "Ice", "Timberwood" };

		public static float ClampReach(float reach)
		{
			if (float.IsNaN(reach))
			{
				return 1f;
			}
			if (reach < 1f)
			{
				return 1f;
			}
			if (reach > 10f)
			{
				return 10f;
			}
			return reach;
		}

		public static void ApplyReach(ref float horizontalLoss, ref float verticalLoss, float reach)
		{
			if (reach != 1f)
			{
				horizontalLoss /= reach;
				verticalLoss /= reach;
			}
		}

		public static float[] BuildTable(bool enabled, IList<KeyValuePair<string, int>> enumValues, IDictionary<string, float> values)
		{
			int num = 0;
			foreach (KeyValuePair<string, int> enumValue in enumValues)
			{
				if (enumValue.Value >= num)
				{
					num = enumValue.Value + 1;
				}
			}
			float[] array = new float[num];
			for (int i = 0; i < num; i++)
			{
				array[i] = 1f;
			}
			if (!enabled)
			{
				return array;
			}
			foreach (KeyValuePair<string, int> enumValue2 in enumValues)
			{
				if (enumValue2.Value >= 0 && values.TryGetValue(enumValue2.Key, out var value))
				{
					array[enumValue2.Value] = ClampReach(value);
				}
			}
			return array;
		}

		public static float Lookup(float[] table, int index)
		{
			if ((uint)index >= (uint)table.Length)
			{
				return 1f;
			}
			return table[index];
		}

		public static int PiecesBeyondGround(float maxSupport, float minSupport, float loss, float step, float reach)
		{
			float num = loss / ClampReach(reach);
			float num2 = maxSupport;
			int i;
			for (i = 0; i < 100000; i++)
			{
				num2 -= num * step * num2;
				if (num2 < minSupport)
				{
					break;
				}
			}
			return i;
		}

		public static float ChainLength(int piecesBeyondGround, float pieceLength)
		{
			return (float)(piecesBeyondGround + 1) * pieceLength;
		}

		public static float SnowDamageBelow(float maxSupport, float minSupport, float snowSupportLevel)
		{
			return minSupport + snowSupportLevel * (maxSupport * 0.5f - minSupport);
		}

		public static string Describe(float[] table, IList<KeyValuePair<string, int>> enumValues)
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (KeyValuePair<string, int> enumValue in enumValues)
			{
				if (stringBuilder.Length > 0)
				{
					stringBuilder.Append(", ");
				}
				stringBuilder.Append(enumValue.Key).Append('×').Append(Lookup(table, enumValue.Value).ToString("0.##", CultureInfo.InvariantCulture));
			}
			return stringBuilder.ToString();
		}
	}
	public readonly struct VanillaMaterial
	{
		public readonly string Name;

		public readonly float MaxSupport;

		public readonly float MinSupport;

		public readonly float HorizontalLoss;

		public readonly float VerticalLoss;

		public static readonly VanillaMaterial[] All = new VanillaMaterial[9]
		{
			new VanillaMaterial("Wood", 100f, 10f, 0.2f, 0.125f),
			new VanillaMaterial("HardWood", 140f, 10f, 1f / 6f, 0.1f),
			new VanillaMaterial("Stone", 1000f, 100f, 1f, 0.125f),
			new VanillaMaterial("Iron", 1500f, 20f, 1f / 13f, 1f / 13f),
			new VanillaMaterial("Marble", 1500f, 100f, 0.5f, 0.125f),
			new VanillaMaterial("Ashstone", 2000f, 100f, 1f / 3f, 0.1f),
			new VanillaMaterial("Ancient", 5000f, 100f, 0.25f, 1f / 15f),
			new VanillaMaterial("Ice", 1000f, 100f, 1f / 3f, 0.125f),
			new VanillaMaterial("Timberwood", 200f, 10f, 0.2f, 1f / 13f)
		};

		public VanillaMaterial(string name, float maxSupport, float minSupport, float horizontalLoss, float verticalLoss)
		{
			Name = name;
			MaxSupport = maxSupport;
			MinSupport = minSupport;
			HorizontalLoss = horizontalLoss;
			VerticalLoss = verticalLoss;
		}

		public static VanillaMaterial Get(string name)
		{
			VanillaMaterial[] all = All;
			for (int i = 0; i < all.Length; i++)
			{
				VanillaMaterial result = all[i];
				if (result.Name == name)
				{
					return result;
				}
			}
			throw new ArgumentException("Unknown material " + name, "name");
		}
	}
}