Decompiled source of Pseudonym v1.4.0

Pseudonym.dll

Decompiled 4 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ComfyLib;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Pseudonym")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Pseudonym")]
[assembly: AssemblyCopyright("Copyright © 2022")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9f7d622d-a609-436a-ab50-ce9ba5f53cad")]
[assembly: AssemblyFileVersion("1.4.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.4.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 Pseudonym
{
	public sealed class NameDigitInputValidator : TMP_InputValidator
	{
		public static NameDigitInputValidator Create()
		{
			return ScriptableObject.CreateInstance<NameDigitInputValidator>();
		}

		public override char Validate(ref string text, ref int pos, char ch)
		{
			ch = ValidateInternal(text, pos, ch);
			if (ch != 0)
			{
				text = text.Insert(pos, ch.ToString());
				pos++;
			}
			return ch;
		}

		private static char ValidateInternal(string text, int pos, char ch)
		{
			char c = ((text.Length > 0) ? text[Mathf.Clamp(pos - 1, 0, text.Length - 1)] : ' ');
			char c2 = ((text.Length > 0) ? text[Mathf.Clamp(pos, 0, text.Length - 1)] : ' ');
			char c3 = ((text.Length > 0) ? text[Mathf.Clamp(pos + 1, 0, text.Length - 1)] : '\n');
			if (ch >= '0' && ch <= '9')
			{
				return ch;
			}
			if (char.IsLetter(ch))
			{
				if (char.IsLower(ch) && pos == 0)
				{
					return char.ToUpper(ch);
				}
				if (char.IsLower(ch) && (c == ' ' || c == '-'))
				{
					return char.ToUpper(ch);
				}
				if (char.IsUpper(ch) && pos > 0 && c != ' ' && c != '\'' && c != '-' && !char.IsLower(c))
				{
					return char.ToLower(ch);
				}
				if (char.IsUpper(ch) && char.IsUpper(c2))
				{
					return '\0';
				}
				return ch;
			}
			if (ch == '\'' && c2 != ' ' && c2 != '\'' && c3 != '\'' && !text.Contains("'"))
			{
				return ch;
			}
			if (char.IsLetter(c) && ch == '-' && c2 != '-')
			{
				return ch;
			}
			if ((ch == ' ' || ch == '-') && pos != 0 && c != ' ' && c != '\'' && c != '-' && c2 != ' ' && c2 != '\'' && c2 != '-' && c3 != ' ' && c3 != '\'' && c3 != '-')
			{
				return ch;
			}
			return '\0';
		}
	}
	[HarmonyPatch(typeof(FejdStartup))]
	internal static class FejdStartupPatch
	{
		private static Button _editButton;

		private static PlayerProfile _editingPlayerProfile;

		private static TextMeshProUGUI _editCharacterPanelTopicText;

		private static TextMeshProUGUI _newCharacterPanelTopicText;

		private static ButtonClickedEvent _onNewCharacterDoneEvent;

		private static PlayerCustomizaton _playerCustomization;

		private static int _characterLimit;

		private static ContentType _contentType;

		private static TMP_InputValidator _inputValidator;

		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		private static void StartPostfix(ref FejdStartup __instance)
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			CreateEditButton(__instance);
			_newCharacterPanelTopicText = ((Component)__instance.m_newCharacterPanel.transform.Find("Topic")).GetComponent<TextMeshProUGUI>();
			_editCharacterPanelTopicText = Object.Instantiate<TextMeshProUGUI>(_newCharacterPanelTopicText, ((TMP_Text)_newCharacterPanelTopicText).transform.parent);
			((TMP_Text)_editCharacterPanelTopicText).text = string.Empty;
			((Component)_editCharacterPanelTopicText).gameObject.SetActive(false);
			_onNewCharacterDoneEvent = __instance.m_csNewCharacterDone.onClick;
			_characterLimit = ((TMP_InputField)__instance.m_csNewCharacterName).characterLimit;
			_contentType = ((TMP_InputField)__instance.m_csNewCharacterName).contentType;
			_inputValidator = ((TMP_InputField)__instance.m_csNewCharacterName).inputValidator;
			_playerCustomization = __instance.m_newCharacterPanel.GetComponentInChildren<PlayerCustomizaton>(true);
		}

		private static void CreateEditButton(FejdStartup fejdStartup)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: 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)
			Object.Destroy((Object)(object)_editButton);
			_editButton = Object.Instantiate<Button>(fejdStartup.m_csNewButton, ((Component)fejdStartup.m_csNewButton).transform.parent);
			((UnityEventBase)_editButton.onClick).RemoveAllListeners();
			((UnityEvent)_editButton.onClick).AddListener((UnityAction)delegate
			{
				OnEditCharacter(fejdStartup);
			});
			((TMP_Text)((Component)_editButton).GetComponentInChildren<TextMeshProUGUI>()).text = "Edit";
			RectTransform component = ((Component)_editButton).GetComponent<RectTransform>();
			component.anchoredPosition += new Vector2(190f, 0f);
		}

		[HarmonyPostfix]
		[HarmonyPatch("UpdateCharacterList")]
		private static void UpdateCharacterList(FejdStartup __instance)
		{
			Button obj = _editButton.Ref<Button>();
			if (obj != null)
			{
				((Component)obj).gameObject.SetActive(__instance.m_profiles.Count > 0);
			}
		}

		private static void OnEditCharacter(FejdStartup fejdStartup)
		{
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Expected O, but got Unknown
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			if (fejdStartup.TryGetPlayerProfile(out var profile))
			{
				Pseudonym.LogInfo("Editing existing player: " + profile.GetName());
				_editingPlayerProfile = profile;
				fejdStartup.m_newCharacterPanel.SetActive(true);
				fejdStartup.m_newCharacterError.SetActive(false);
				fejdStartup.m_selectCharacterPanel.SetActive(false);
				((Component)_newCharacterPanelTopicText).gameObject.SetActive(false);
				((TMP_Text)_editCharacterPanelTopicText).text = "Edit Character: " + profile.GetName();
				((Component)_editCharacterPanelTopicText).gameObject.SetActive(true);
				fejdStartup.m_csNewCharacterDone.onClick = new ButtonClickedEvent();
				((UnityEvent)fejdStartup.m_csNewCharacterDone.onClick).AddListener((UnityAction)delegate
				{
					OnEditCharacterDone(fejdStartup);
				});
				((TMP_InputField)fejdStartup.m_csNewCharacterName).characterLimit = 20;
				((TMP_InputField)fejdStartup.m_csNewCharacterName).inputValidator = (TMP_InputValidator)(object)NameDigitInputValidator.Create();
				((TMP_InputField)fejdStartup.m_csNewCharacterName).contentType = (ContentType)9;
				((TMP_InputField)fejdStartup.m_csNewCharacterName).characterValidation = (CharacterValidation)8;
				((TMP_InputField)fejdStartup.m_csNewCharacterName).text = profile.GetName();
				fejdStartup.SetupCharacterPreview(profile);
				GameObject obj = fejdStartup.m_playerInstance.Ref<GameObject>();
				SetupPlayerCustomization((obj != null) ? obj.GetComponent<Player>() : null, _playerCustomization);
			}
			else
			{
				_editingPlayerProfile = null;
			}
		}

		private static void SetupPlayerCustomization(Player player, PlayerCustomizaton customization)
		{
			//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_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_0055: 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_0083: 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_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: 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_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)player) && Object.op_Implicit((Object)(object)customization))
			{
				customization.m_maleToggle.SetIsOnWithoutNotify(player.m_modelIndex == 0);
				customization.m_femaleToggle.SetIsOnWithoutNotify(player.m_modelIndex == 1);
				float valueWithoutNotify = InverseLerp(Color.op_Implicit(customization.m_skinColor0), Color.op_Implicit(customization.m_skinColor1), Color.op_Implicit(Utils.Vec3ToColor(player.m_skinColor)));
				customization.m_skinHue.SetValueWithoutNotify(valueWithoutNotify);
				float x = player.m_hairColor.x;
				Color val = Utils.Vec3ToColor(player.m_hairColor / x);
				float valueWithoutNotify2 = InverseLerp(Color.op_Implicit(customization.m_hairColor0), Color.op_Implicit(customization.m_hairColor1), Color.op_Implicit(val));
				customization.m_hairTone.SetValueWithoutNotify(valueWithoutNotify2);
				customization.m_hairLevel.SetValueWithoutNotify(Mathf.InverseLerp(customization.m_hairMinLevel, customization.m_hairMaxLevel, x));
			}
			else
			{
				Pseudonym.LogError("Could not setup player customization for editing.");
			}
		}

		private static float InverseLerp(Vector4 a, Vector4 b, Vector4 value)
		{
			//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)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: 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_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_0010: 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_0017: 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)
			Vector4 val = b - a;
			Vector4 val2 = value - a;
			return Vector4.Dot(val, val2) / Vector4.Dot(val, val);
		}

		[HarmonyPrefix]
		[HarmonyPatch("OnNewCharacterCancel")]
		private static void OnNewCharacterCancel(ref FejdStartup __instance)
		{
			_editingPlayerProfile = null;
			OnEditCharacterDone(__instance);
		}

		private static void OnEditCharacterDone(FejdStartup fejdStartup)
		{
			if (_editingPlayerProfile != null)
			{
				string text = ((TMP_InputField)fejdStartup.m_csNewCharacterName).text;
				Pseudonym.LogInfo("Saving existing player: " + _editingPlayerProfile.GetName() + " -> " + text);
				_editingPlayerProfile.SetName(text);
				_editingPlayerProfile.SavePlayerData(fejdStartup.m_playerInstance.GetComponent<Player>());
				_editingPlayerProfile.SavePlayerToDisk();
			}
			_editingPlayerProfile = null;
			((Component)_newCharacterPanelTopicText).gameObject.SetActive(true);
			((Component)_editCharacterPanelTopicText).gameObject.SetActive(false);
			fejdStartup.m_csNewCharacterDone.onClick = _onNewCharacterDoneEvent;
			((TMP_InputField)fejdStartup.m_csNewCharacterName).text = string.Empty;
			((TMP_InputField)fejdStartup.m_csNewCharacterName).characterLimit = _characterLimit;
			((TMP_InputField)fejdStartup.m_csNewCharacterName).characterValidation = (CharacterValidation)5;
			((TMP_InputField)fejdStartup.m_csNewCharacterName).contentType = (ContentType)5;
			((TMP_InputField)fejdStartup.m_csNewCharacterName).inputValidator = _inputValidator;
			fejdStartup.m_selectCharacterPanel.SetActive(true);
			fejdStartup.m_newCharacterPanel.SetActive(false);
			fejdStartup.UpdateCharacterList();
		}
	}
	public static class PluginConfig
	{
		public static ConfigEntry<bool> IsModEnabled { get; private set; }

		public static void BindConfig(ConfigFile config)
		{
			IsModEnabled = config.BindInOrder("_Global", "isModEnabled", defaultValue: true, "Globally enable or disable this mod (restart required).");
		}
	}
	public static class FejdStartupExtensions
	{
		public static bool TryGetPlayerProfile(this FejdStartup fejdStartup, out PlayerProfile profile)
		{
			if (Object.op_Implicit((Object)(object)fejdStartup))
			{
				return fejdStartup.TryGetPlayerProfile(out profile, fejdStartup.m_profileIndex);
			}
			profile = null;
			return false;
		}

		public static bool TryGetPlayerProfile(this FejdStartup fejdStartup, out PlayerProfile profile, int profileIndex)
		{
			profile = null;
			if (!Object.op_Implicit((Object)(object)fejdStartup) || fejdStartup.m_profiles == null || fejdStartup.m_profiles.Count <= 0)
			{
				return false;
			}
			if (profileIndex < 0 || profileIndex >= fejdStartup.m_profiles.Count)
			{
				return false;
			}
			profile = fejdStartup.m_profiles[profileIndex];
			return true;
		}
	}
	[HarmonyPatch(typeof(PlayerCustomizaton))]
	internal static class PlayerCustomizatonPatch
	{
		[HarmonyTranspiler]
		[HarmonyPatch("OnBeardLeft")]
		private static IEnumerable<CodeInstruction> OnBeardLeftTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: 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_003b: Expected O, but got Unknown
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).Start().MatchStartForward((CodeMatch[])(object)new CodeMatch[2]
			{
				new CodeMatch((OpCode?)OpCodes.Callvirt, (object)AccessTools.Method(typeof(Player), "GetPlayerModel", (Type[])null, (Type[])null), (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldc_I4_1, (object)null, (string)null)
			}).ThrowIfInvalid("Could not patch PlayerCustomizaton.OnBeardLeft()! (GetPlayerModel)")
				.Advance(1)
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { Transpilers.EmitDelegate<Func<int, int>>((Func<int, int>)GetPlayerModelDelegate) })
				.InstructionEnumeration();
		}

		[HarmonyTranspiler]
		[HarmonyPatch("OnBeardRight")]
		private static IEnumerable<CodeInstruction> OnBeardRightTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: 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_003b: Expected O, but got Unknown
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).Start().MatchStartForward((CodeMatch[])(object)new CodeMatch[2]
			{
				new CodeMatch((OpCode?)OpCodes.Callvirt, (object)AccessTools.Method(typeof(Player), "GetPlayerModel", (Type[])null, (Type[])null), (string)null),
				new CodeMatch((OpCode?)OpCodes.Ldc_I4_1, (object)null, (string)null)
			}).ThrowIfInvalid("Could not patch PlayerCustomizaton.OnBeardRight()! (GetPlayerModel)")
				.Advance(1)
				.InsertAndAdvance((CodeInstruction[])(object)new CodeInstruction[1] { Transpilers.EmitDelegate<Func<int, int>>((Func<int, int>)GetPlayerModelDelegate) })
				.InstructionEnumeration();
		}

		private static int GetPlayerModelDelegate(int value)
		{
			if (!PluginConfig.IsModEnabled.Value)
			{
				return value;
			}
			return 0;
		}
	}
	[BepInPlugin("redseiko.valheim.pseudonym", "Pseudonym", "1.4.0")]
	public sealed class Pseudonym : BaseUnityPlugin
	{
		public const string PluginGuid = "redseiko.valheim.pseudonym";

		public const string PluginName = "Pseudonym";

		public const string PluginVersion = "1.4.0";

		private static ManualLogSource _logger;

		private void Awake()
		{
			_logger = ((BaseUnityPlugin)this).Logger;
			PluginConfig.BindConfig(((BaseUnityPlugin)this).Config);
			if (PluginConfig.IsModEnabled.Value)
			{
				Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "redseiko.valheim.pseudonym");
			}
		}

		public static void LogInfo(object o)
		{
			_logger.LogInfo((object)$"[{DateTime.Now.ToString(DateTimeFormatInfo.InvariantInfo)}] {o}");
		}

		public static void LogError(object o)
		{
			_logger.LogError((object)$"[{DateTime.Now.ToString(DateTimeFormatInfo.InvariantInfo)}] {o}");
		}
	}
}
namespace ComfyLib
{
	public static class ConfigFileExtensions
	{
		internal sealed class ConfigurationManagerAttributes
		{
			public Action<ConfigEntryBase> CustomDrawer;

			public bool? Browsable;

			public bool? HideDefaultButton;

			public bool? HideSettingName;

			public bool? IsAdvanced;

			public int? Order;

			public bool? ReadOnly;
		}

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

		private static int GetSettingOrder(string section)
		{
			if (!_sectionToSettingOrder.TryGetValue(section, out var value))
			{
				value = 0;
			}
			_sectionToSettingOrder[section] = value - 1;
			return value;
		}

		public static ConfigEntry<T> BindInOrder<T>(this ConfigFile config, string section, string key, T defaultValue, string description, AcceptableValueBase acceptableValues, bool browsable = true, bool hideDefaultButton = false, bool hideSettingName = false, bool isAdvanced = false, bool readOnly = false)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			return config.Bind<T>(section, key, defaultValue, new ConfigDescription(description, acceptableValues, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Browsable = browsable,
					CustomDrawer = null,
					HideDefaultButton = hideDefaultButton,
					HideSettingName = hideSettingName,
					IsAdvanced = isAdvanced,
					Order = GetSettingOrder(section),
					ReadOnly = readOnly
				}
			}));
		}

		public static ConfigEntry<T> BindInOrder<T>(this ConfigFile config, string section, string key, T defaultValue, string description, Action<ConfigEntryBase> customDrawer = null, bool browsable = true, bool hideDefaultButton = false, bool hideSettingName = false, bool isAdvanced = false, bool readOnly = false)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Expected O, but got Unknown
			return config.Bind<T>(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Browsable = browsable,
					CustomDrawer = customDrawer,
					HideDefaultButton = hideDefaultButton,
					HideSettingName = hideSettingName,
					IsAdvanced = isAdvanced,
					Order = GetSettingOrder(section),
					ReadOnly = readOnly
				}
			}));
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action settingChangedHandler)
		{
			configEntry.SettingChanged += delegate
			{
				settingChangedHandler();
			};
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action<T> settingChangedHandler)
		{
			configEntry.SettingChanged += delegate(object _, EventArgs eventArgs)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				settingChangedHandler((T)((SettingChangedEventArgs)eventArgs).ChangedSetting.BoxedValue);
			};
		}

		public static void OnSettingChanged<T>(this ConfigEntry<T> configEntry, Action<ConfigEntry<T>> settingChangedHandler)
		{
			configEntry.SettingChanged += delegate(object _, EventArgs eventArgs)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				settingChangedHandler((ConfigEntry<T>)((SettingChangedEventArgs)eventArgs).ChangedSetting.BoxedValue);
			};
		}
	}
	public static class ObjectExtensions
	{
		public static T FirstByNameOrThrow<T>(this IEnumerable<T> unityObjects, string name) where T : Object
		{
			foreach (T unityObject in unityObjects)
			{
				if (((Object)unityObject).name == name)
				{
					return unityObject;
				}
			}
			throw new InvalidOperationException($"Could not find Unity object of type {typeof(T)} with name: {name}");
		}

		public static T Ref<T>(this T unityObject) where T : Object
		{
			if (!Object.op_Implicit((Object)(object)unityObject))
			{
				return default(T);
			}
			return unityObject;
		}
	}
}