Decompiled source of BuildRadius v1.0.0

plugins/BuildRadius.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.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Managers;
using Jotunn.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;
using ValheimMods.Shared;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("BuildRadius")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Bigger build radius for workbenches, forges and every other crafting station: one multiplier plus optional per-station radii, set by the server in multiplayer. Needs Jotunn.")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("BuildRadius")]
[assembly: AssemblyTitle("BuildRadius")]
[assembly: InternalsVisibleTo("ValheimMods.Tests")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[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 BuildRadius
{
	[BepInPlugin("s992.BuildRadius", "BuildRadius", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		private void Awake()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			Settings.Bind(((BaseUnityPlugin)this).Config);
			if (SafePatching.PatchAll(new Harmony("s992.BuildRadius"), ((BaseUnityPlugin)this).Logger))
			{
				Settings.Changed += Stations.ApplyAll;
				SynchronizationManager.OnConfigurationSynchronized += delegate(object _, ConfigurationSynchronizationEventArgs args)
				{
					ServerAuthority.OnSynchronized(args);
					Settings.Reload();
				};
				((BaseUnityPlugin)this).Logger.LogInfo((object)(ModInfo.Name + " " + ModInfo.Version + " loaded"));
			}
		}
	}
	internal static class Radius
	{
		public const float MinOverride = 1f;

		public const float MaxOverride = 500f;

		public static (float baseRange, float extraPerLevel) Compute(float vanillaBase, float vanillaExtra, float multiplier, float? overrideBase)
		{
			return (baseRange: overrideBase ?? (vanillaBase * multiplier), extraPerLevel: vanillaExtra * multiplier);
		}

		public static string Key(string name)
		{
			return (name ?? "").Trim().TrimStart('$').ToLowerInvariant();
		}

		public static Dictionary<string, float> ParseOverrides(string text, List<string> problems)
		{
			Dictionary<string, float> dictionary = new Dictionary<string, float>();
			string[] array = (text ?? "").Split(',');
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (text2.Length != 0)
				{
					string[] array2 = text2.Split(':');
					if (array2.Length != 2 || Key(array2[0]).Length == 0 || !float.TryParse(array2[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || float.IsNaN(result) || result < 1f || result > 500f)
					{
						problems.Add(text2);
					}
					else
					{
						dictionary[Key(array2[0])] = result;
					}
				}
			}
			return dictionary;
		}

		public static float? Find(Dictionary<string, float> overrides, string prefabName, string stationName)
		{
			if (overrides.TryGetValue(Key(prefabName), out var value))
			{
				return value;
			}
			if (overrides.TryGetValue(Key(stationName), out var value2))
			{
				return value2;
			}
			return null;
		}
	}
	internal static class ServerAuthority
	{
		private static ZNet s_syncedFrom;

		public static bool Active
		{
			get
			{
				ZNet instance = ZNet.instance;
				if (!Object.op_Implicit((Object)(object)instance) || instance.IsServer())
				{
					return true;
				}
				return (Object)(object)s_syncedFrom == (Object)(object)instance;
			}
		}

		public static void OnSynchronized(ConfigurationSynchronizationEventArgs args)
		{
			if (((args != null) ? args.UpdatedPluginGUIDs : null) != null && args.UpdatedPluginGUIDs.Contains("s992.BuildRadius"))
			{
				ZNet instance = ZNet.instance;
				if (Object.op_Implicit((Object)(object)instance) && !instance.IsServer() && !((Object)(object)s_syncedFrom == (Object)(object)instance))
				{
					s_syncedFrom = instance;
					ModInfo.Log.LogInfo((object)"Using the server's build radius settings");
				}
			}
		}
	}
	internal static class Settings
	{
		public static ConfigEntry<float> Multiplier;

		public static ConfigEntry<string> Overrides;

		public static Dictionary<string, float> ParsedOverrides { get; private set; } = new Dictionary<string, float>();

		public static event Action Changed;

		public static void Bind(ConfigFile config)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			Multiplier = config.Bind<float>("1. Server", "Multiplier", 2f, new ConfigDescription("Scales every crafting station's build radius, and the extra radius each extension adds. 1 is the game's own radius. Modded stations are included. Set by the server in multiplayer.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f), new object[1] { Admin(2) }));
			Overrides = config.Bind<string>("1. Server", "Station radii", "", new ConfigDescription("Exact base radius in metres for named stations, as name:metres separated by commas, e.g. piece_workbench:40, forge:30. Names are prefab names (piece_workbench, forge, piece_stonecutter, piece_artisanstation, blackforge, piece_magetable) or station names without the $. Extensions still add their bonus times the multiplier. Stations not listed use the multiplier. Set by the server in multiplayer.", (AcceptableValueBase)null, new object[1] { Admin(1) }));
			Multiplier.SettingChanged += OnChanged;
			Overrides.SettingChanged += OnChanged;
			Parse();
		}

		private static ConfigurationManagerAttributes Admin(int order)
		{
			//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_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			return new ConfigurationManagerAttributes
			{
				IsAdminOnly = true,
				Order = order
			};
		}

		private static void OnChanged(object sender, EventArgs e)
		{
			Reload();
		}

		public static void Reload()
		{
			Parse();
			Settings.Changed?.Invoke();
		}

		private static void Parse()
		{
			List<string> list = new List<string>();
			ParsedOverrides = Radius.ParseOverrides(Overrides.Value, list);
			if (list.Count > 0)
			{
				ModInfo.Log.LogWarning((object)("Station radii: ignored " + string.Join(", ", list) + " (use name:metres, " + $"{1f}-{500f} m)"));
			}
		}
	}
	internal static class Stations
	{
		private struct Vanilla
		{
			public float Base;

			public float Extra;
		}

		private static readonly Dictionary<CraftingStation, Vanilla> s_vanilla = new Dictionary<CraftingStation, Vanilla>();

		public static void Track(CraftingStation station)
		{
			if (Object.op_Implicit((Object)(object)station) && !s_vanilla.ContainsKey(station))
			{
				Vanilla vanilla = new Vanilla
				{
					Base = station.m_rangeBuild,
					Extra = station.m_extraRangePerLevel
				};
				s_vanilla[station] = vanilla;
				Apply(station, vanilla);
			}
		}

		public static void Forget(CraftingStation station)
		{
			s_vanilla.Remove(station);
		}

		public static void ApplyAll()
		{
			foreach (KeyValuePair<CraftingStation, Vanilla> item in s_vanilla)
			{
				if (Object.op_Implicit((Object)(object)item.Key))
				{
					Apply(item.Key, item.Value);
				}
			}
		}

		private static void Apply(CraftingStation station, Vanilla vanilla)
		{
			float num = vanilla.Base;
			float num2 = vanilla.Extra;
			if (ServerAuthority.Active)
			{
				float? overrideBase = Radius.Find(Settings.ParsedOverrides, Utils.GetPrefabName(((Component)station).gameObject), station.m_name);
				(num, num2) = Radius.Compute(vanilla.Base, vanilla.Extra, Settings.Multiplier.Value, overrideBase);
			}
			if (station.m_rangeBuild != num || station.m_extraRangePerLevel != num2)
			{
				station.m_rangeBuild = num;
				station.m_extraRangePerLevel = num2;
				station.m_updateExtensionTimer = 2f;
			}
		}
	}
	[HarmonyPatch(typeof(CraftingStation), "Start")]
	internal static class StationStart
	{
		private static void Postfix(CraftingStation __instance)
		{
			if (CraftingStation.m_allStations.Contains(__instance))
			{
				Stations.Track(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(CraftingStation), "OnDestroy")]
	internal static class StationDestroy
	{
		private static void Prefix(CraftingStation __instance)
		{
			Stations.Forget(__instance);
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "s992.BuildRadius";

		public const string PLUGIN_NAME = "BuildRadius";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace ValheimMods.Shared
{
	internal sealed class FrameGuard
	{
		private const int MaxErrors = 10;

		private readonly Behaviour m_owner;

		private readonly string m_feature;

		private int m_errors;

		public FrameGuard(Behaviour owner, string feature)
		{
			m_owner = owner;
			m_feature = feature;
		}

		public void Report(Exception e)
		{
			m_errors++;
			if (m_errors == 1)
			{
				ModInfo.Log.LogError((object)$"Error in {m_feature}: {e}");
			}
			if (m_errors >= 10)
			{
				m_owner.enabled = false;
				string text = ModInfo.Name + ": " + m_feature + " kept failing and is off until the game restarts. Details are in BepInEx/LogOutput.log.";
				ModInfo.Log.LogError((object)text);
				PlayerNotice.Show(text);
			}
		}
	}
	internal static class Hotkeys
	{
		private static readonly KeyCode[] s_modifierKeys;

		public static bool Pressed(ConfigEntry<KeyboardShortcut> entry)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: 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)
			KeyboardShortcut value = entry.Value;
			if ((int)((KeyboardShortcut)(ref value)).MainKey == 0 || !ZInput.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey, false))
			{
				return false;
			}
			List<KeyCode> modifiers = ((KeyboardShortcut)(ref value)).Modifiers.ToList();
			if (modifiers.Any((KeyCode key) => !ZInput.GetKey(key, false)))
			{
				return false;
			}
			return !s_modifierKeys.Any((KeyCode key) => !modifiers.Contains(key) && ZInput.GetKey(key, false));
		}

		public static bool Held(ConfigEntry<KeyboardShortcut> entry)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: 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)
			KeyboardShortcut value = entry.Value;
			if ((int)((KeyboardShortcut)(ref value)).MainKey != 0 && ZInput.GetKey(((KeyboardShortcut)(ref value)).MainKey, false))
			{
				return ((KeyboardShortcut)(ref value)).Modifiers.All((KeyCode key) => ZInput.GetKey(key, false));
			}
			return false;
		}

		public static bool IsTyping()
		{
			if (!Console.IsVisible() && !TextInput.IsVisible() && !Menu.IsVisible() && !Minimap.InTextInput())
			{
				if (Object.op_Implicit((Object)(object)Chat.instance))
				{
					return Chat.instance.HasFocus();
				}
				return false;
			}
			return true;
		}

		static Hotkeys()
		{
			KeyCode[] array = new KeyCode[6];
			RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
			s_modifierKeys = (KeyCode[])(object)array;
		}
	}
	internal static class ModInfo
	{
		public static readonly string Name = typeof(ModInfo).Assembly.GetName().Name;

		public static readonly string Version = typeof(ModInfo).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? typeof(ModInfo).Assembly.GetName().Version.ToString(3);

		private static ManualLogSource s_log;

		public static ManualLogSource Log => s_log ?? (s_log = Logger.CreateLogSource(Name));
	}
	internal static class PatchGuard
	{
		private static readonly HashSet<string> s_reported = new HashSet<string>();

		public static Exception Contain(Exception exception, string feature)
		{
			if (exception == null || !FromThisMod(exception))
			{
				return exception;
			}
			if (s_reported.Add(feature))
			{
				ModInfo.Log.LogError((object)$"Error in {feature} (further errors there aren't logged): {exception}");
				PlayerNotice.Show(ModInfo.Name + ": " + feature + " hit an error and may not work until the game restarts. Details are in BepInEx/LogOutput.log.");
			}
			return null;
		}

		private static bool FromThisMod(Exception exception)
		{
			Assembly assembly = typeof(PatchGuard).Assembly;
			for (Exception ex = exception; ex != null; ex = ex.InnerException)
			{
				StackFrame[] array = new StackTrace(ex, fNeedFileInfo: false).GetFrames() ?? Array.Empty<StackFrame>();
				for (int i = 0; i < array.Length; i++)
				{
					if (array[i].GetMethod()?.DeclaringType?.Assembly == assembly)
					{
						return true;
					}
				}
			}
			return false;
		}
	}
	internal sealed class PlayerNotice : MonoBehaviour
	{
		private static PlayerNotice s_instance;

		private readonly List<string> m_pending = new List<string>();

		public static void Show(string message)
		{
			//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)
			//IL_0026: Expected O, but got Unknown
			if (!Object.op_Implicit((Object)(object)s_instance))
			{
				GameObject val = new GameObject(ModInfo.Name + ".PlayerNotice");
				Object.DontDestroyOnLoad((Object)val);
				s_instance = val.AddComponent<PlayerNotice>();
			}
			s_instance.m_pending.Add(message);
		}

		private void Update()
		{
			if (m_pending.Count == 0 || !Object.op_Implicit((Object)(object)Player.m_localPlayer) || !Object.op_Implicit((Object)(object)MessageHud.instance))
			{
				return;
			}
			try
			{
				foreach (string item in m_pending)
				{
					Send(item);
				}
			}
			catch (Exception ex)
			{
				ModInfo.Log.LogWarning((object)("Couldn't show a message in game: " + ex.Message));
			}
			m_pending.Clear();
		}

		private static void Send(string message)
		{
			((Character)Player.m_localPlayer).Message((MessageType)1, message, 0, (Sprite)null, false);
			if (Object.op_Implicit((Object)(object)Console.instance))
			{
				Console.instance.Print(message);
			}
		}
	}
	internal static class SafePatching
	{
		public static bool PatchAll(Harmony harmony, ManualLogSource log)
		{
			List<string> list = new List<string>();
			Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(typeof(SafePatching).Assembly);
			foreach (Type type in typesFromAssembly)
			{
				try
				{
					harmony.CreateClassProcessor(type).Patch();
				}
				catch (Exception arg)
				{
					list.Add(type.Name);
					log.LogError((object)$"Patch {type.Name} failed: {arg}");
				}
			}
			if (list.Count == 0)
			{
				return true;
			}
			harmony.UnpatchSelf();
			string text = ModInfo.Name + " is turned off: this game version changed something it relies on (" + string.Join(", ", list) + "). Check for an update to " + ModInfo.Name + ".";
			log.LogError((object)text);
			PlayerNotice.Show(text);
			return false;
		}

		public static void ExpectReplaced(int replaced, int expected, string what)
		{
			if (replaced != expected)
			{
				throw new InvalidOperationException($"{what}: expected {expected} change(s), made {replaced}");
			}
		}
	}
}