Decompiled source of Feminine Figure v1.0.0

FeminineFigure.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("FeminineFigure")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("FeminineFigure")]
[assembly: AssemblyTitle("FeminineFigure")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FeminineFigure
{
	internal static class BodyMeshSwap
	{
		private sealed class Entry
		{
			public Mesh Vanilla;

			public Mesh? Shaped;

			public string[] BoneNames = Array.Empty<string>();

			public bool Failed;
		}

		private const int ModelIndex = 1;

		private static readonly Dictionary<Mesh, Entry> ByVanilla = new Dictionary<Mesh, Entry>();

		private static readonly Dictionary<Mesh, Entry> ByShaped = new Dictionary<Mesh, Entry>();

		private static ArmShape _shape = new ArmShape();

		private static bool _active;

		private static bool _broken;

		internal static bool Install(Harmony harmony)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(VisEquipment), "UpdateBaseModel", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				FeminineFigurePlugin.Log.LogError((object)"VisEquipment.UpdateBaseModel was not found in this game version, so the body is left as it is.");
				return false;
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(BodyMeshSwap), "BeforeUpdateBaseModel", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return true;
		}

		internal static void SetShape(bool enabled, ArmShape shape)
		{
			_shape = shape;
			_active = enabled && !shape.IsVanilla;
			if (!_active)
			{
				return;
			}
			foreach (Entry value in ByVanilla.Values)
			{
				if (!value.Failed && Object.op_Implicit((Object)(object)value.Vanilla) && Object.op_Implicit((Object)(object)value.Shaped))
				{
					try
					{
						int num = BodySlimmer.Apply(value.Vanilla, value.Shaped, value.BoneNames, shape);
						FeminineFigurePlugin.Log.LogInfo((object)$"Body mesh '{((Object)value.Vanilla).name}' reshaped again: {num} of {value.Vanilla.vertexCount} vertices moved ({shape}).");
					}
					catch (Exception arg)
					{
						value.Failed = true;
						FeminineFigurePlugin.Log.LogError((object)$"Body mesh '{((Object)value.Vanilla).name}' could not be reshaped, so it stays vanilla: {arg}");
					}
				}
			}
		}

		private static void BeforeUpdateBaseModel(VisEquipment __instance)
		{
			if (_broken)
			{
				return;
			}
			try
			{
				PlayerModel[] models = __instance.m_models;
				if (models == null || models.Length <= 1 || models[1] == null || !Object.op_Implicit((Object)(object)__instance.m_bodyModel))
				{
					return;
				}
				Mesh mesh = models[1].m_mesh;
				if (mesh == null)
				{
					return;
				}
				if (!ByShaped.TryGetValue(mesh, out Entry value) && !ByVanilla.TryGetValue(mesh, out value))
				{
					if (!_active || !Object.op_Implicit((Object)(object)mesh))
					{
						return;
					}
					value = Make(mesh, __instance.m_bodyModel);
				}
				Mesh val = (Mesh)((_active && !value.Failed && Object.op_Implicit((Object)(object)value.Shaped)) ? ((object)value.Shaped) : ((object)value.Vanilla));
				if (Object.op_Implicit((Object)(object)val) && val != mesh)
				{
					models[1].m_mesh = val;
				}
			}
			catch (Exception arg)
			{
				_broken = true;
				FeminineFigurePlugin.Log.LogError((object)$"Stopped reshaping bodies after an error: {arg}");
			}
		}

		private static Entry Make(Mesh vanilla, SkinnedMeshRenderer body)
		{
			Forget();
			Entry entry = new Entry
			{
				Vanilla = vanilla
			};
			ByVanilla[vanilla] = entry;
			try
			{
				if (!vanilla.isReadable)
				{
					throw new InvalidOperationException("the game does not let scripts read this mesh");
				}
				entry.BoneNames = body.bones.Select((Transform bone) => (!Object.op_Implicit((Object)(object)bone)) ? "" : ((Object)bone).name).ToArray();
				int moved;
				Mesh val = BodySlimmer.Build(vanilla, entry.BoneNames, _shape, out moved);
				((Object)val).hideFlags = (HideFlags)61;
				entry.Shaped = val;
				ByShaped[val] = entry;
				if (moved == 0)
				{
					entry.Failed = true;
					FeminineFigurePlugin.Log.LogWarning((object)("Body mesh '" + ((Object)vanilla).name + "' has no arm or hand bones this mod knows, so it stays vanilla."));
				}
				else
				{
					FeminineFigurePlugin.Log.LogInfo((object)$"Reshaped body mesh '{((Object)vanilla).name}': {moved} of {vanilla.vertexCount} vertices moved ({_shape}).");
				}
			}
			catch (Exception arg)
			{
				entry.Failed = true;
				FeminineFigurePlugin.Log.LogError((object)$"Body mesh '{((Object)vanilla).name}' could not be reshaped, so it stays vanilla: {arg}");
			}
			return entry;
		}

		private static void Forget()
		{
			foreach (Entry item in ByVanilla.Values.Where((Entry entry) => !Object.op_Implicit((Object)(object)entry.Vanilla)).ToList())
			{
				ByVanilla.Remove(item.Vanilla);
				if (item.Shaped != null)
				{
					ByShaped.Remove(item.Shaped);
					if (Object.op_Implicit((Object)(object)item.Shaped))
					{
						Object.Destroy((Object)(object)item.Shaped);
					}
				}
			}
		}
	}
	public sealed class ArmShape
	{
		public float UpperArm = 1f;

		public float Forearm = 1f;

		public float Hand = 1f;

		public bool IsVanilla
		{
			get
			{
				if (Same(UpperArm) && Same(Forearm))
				{
					return Same(Hand);
				}
				return false;
			}
		}

		private static bool Same(float value)
		{
			return Mathf.Abs(value - 1f) < 0.0005f;
		}

		public override string ToString()
		{
			return string.Format(CultureInfo.InvariantCulture, "upper arm {0:0.###}, forearm {1:0.###}, hand {2:0.###}", UpperArm, Forearm, Hand);
		}
	}
	public static class BodySlimmer
	{
		public static Mesh Build(Mesh source, IList<string> boneNames, ArmShape shape, out int moved)
		{
			Mesh val = Object.Instantiate<Mesh>(source);
			((Object)val).name = ((Object)source).name;
			moved = Apply(source, val, boneNames, shape);
			return val;
		}

		public static int Apply(Mesh source, Mesh target, IList<string> boneNames, ArmShape shape)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: 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)
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0249: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0336: Unknown result type (might be due to invalid IL or missing references)
			//IL_033b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_034b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0350: Unknown result type (might be due to invalid IL or missing references)
			//IL_0354: Unknown result type (might be due to invalid IL or missing references)
			//IL_0359: Unknown result type (might be due to invalid IL or missing references)
			//IL_0361: Unknown result type (might be due to invalid IL or missing references)
			//IL_0366: Unknown result type (might be due to invalid IL or missing references)
			//IL_036b: Unknown result type (might be due to invalid IL or missing references)
			//IL_03bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0381: Unknown result type (might be due to invalid IL or missing references)
			//IL_0386: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0403: Unknown result type (might be due to invalid IL or missing references)
			//IL_0408: Unknown result type (might be due to invalid IL or missing references)
			Matrix4x4[] bindposes = source.bindposes;
			int num = Mathf.Min(bindposes.Length, boneNames.Count);
			Matrix4x4[] array = (Matrix4x4[])(object)new Matrix4x4[bindposes.Length];
			bool[] changes = new bool[bindposes.Length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = Matrix4x4.identity;
			}
			string[] array2 = new string[2] { "Left", "Right" };
			foreach (string text in array2)
			{
				int num2 = Find(boneNames, num, text + "Arm");
				int num3 = Find(boneNames, num, text + "ForeArm");
				int num4 = Find(boneNames, num, text + "Hand");
				if (num2 < 0 || num3 < 0 || num4 < 0)
				{
					continue;
				}
				Vector3 val = Joint(bindposes[num2]);
				Vector3 val2 = Joint(bindposes[num3]);
				Vector3 val3 = Joint(bindposes[num4]);
				Set(array, changes, num2, Squeeze(val, val2 - val, shape.UpperArm));
				Set(array, changes, num3, Squeeze(val2, val3 - val2, shape.Forearm));
				Matrix4x4 matrix = Shrink(val3, shape.Hand);
				for (int k = 0; k < num; k++)
				{
					if (boneNames[k] != null && boneNames[k].StartsWith(text + "Hand", StringComparison.Ordinal))
					{
						Set(array, changes, k, matrix);
					}
				}
			}
			Vector3[] vertices = source.vertices;
			Vector3[] normals = source.normals;
			Vector4[] tangents = source.tangents;
			BoneWeight[] boneWeights = source.boneWeights;
			bool flag = normals.Length == vertices.Length;
			bool flag2 = tangents.Length == vertices.Length;
			int num5 = 0;
			if (boneWeights.Length == vertices.Length)
			{
				for (int l = 0; l < vertices.Length; l++)
				{
					BoneWeight val4 = boneWeights[l];
					if (!Counts(changes, ((BoneWeight)(ref val4)).boneIndex0, ((BoneWeight)(ref val4)).weight0) && !Counts(changes, ((BoneWeight)(ref val4)).boneIndex1, ((BoneWeight)(ref val4)).weight1) && !Counts(changes, ((BoneWeight)(ref val4)).boneIndex2, ((BoneWeight)(ref val4)).weight2) && !Counts(changes, ((BoneWeight)(ref val4)).boneIndex3, ((BoneWeight)(ref val4)).weight3))
					{
						continue;
					}
					Matrix4x4 sum = default(Matrix4x4);
					float num6 = 0f;
					num6 += Add(ref sum, array, ((BoneWeight)(ref val4)).boneIndex0, ((BoneWeight)(ref val4)).weight0);
					num6 += Add(ref sum, array, ((BoneWeight)(ref val4)).boneIndex1, ((BoneWeight)(ref val4)).weight1);
					num6 += Add(ref sum, array, ((BoneWeight)(ref val4)).boneIndex2, ((BoneWeight)(ref val4)).weight2);
					num6 += Add(ref sum, array, ((BoneWeight)(ref val4)).boneIndex3, ((BoneWeight)(ref val4)).weight3);
					if (num6 <= 1E-06f)
					{
						continue;
					}
					for (int m = 0; m < 16; m++)
					{
						int j = m;
						((Matrix4x4)(ref sum))[j] = ((Matrix4x4)(ref sum))[j] / num6;
					}
					sum.m30 = 0f;
					sum.m31 = 0f;
					sum.m32 = 0f;
					sum.m33 = 1f;
					vertices[l] = ((Matrix4x4)(ref sum)).MultiplyPoint3x4(vertices[l]);
					if (flag)
					{
						Matrix4x4 val5 = ((Matrix4x4)(ref sum)).inverse;
						val5 = ((Matrix4x4)(ref val5)).transpose;
						Vector3 val6 = ((Matrix4x4)(ref val5)).MultiplyVector(normals[l]);
						if (((Vector3)(ref val6)).sqrMagnitude > 1E-12f)
						{
							normals[l] = ((Vector3)(ref val6)).normalized;
						}
					}
					if (flag2)
					{
						Vector3 val7 = ((Matrix4x4)(ref sum)).MultiplyVector(new Vector3(tangents[l].x, tangents[l].y, tangents[l].z));
						if (((Vector3)(ref val7)).sqrMagnitude > 1E-12f)
						{
							((Vector3)(ref val7)).Normalize();
							tangents[l] = new Vector4(val7.x, val7.y, val7.z, tangents[l].w);
						}
					}
					num5++;
				}
			}
			target.vertices = vertices;
			if (flag)
			{
				target.normals = normals;
			}
			if (flag2)
			{
				target.tangents = tangents;
			}
			target.RecalculateBounds();
			return num5;
		}

		private static int Find(IList<string> names, int count, string name)
		{
			for (int i = 0; i < count; i++)
			{
				if (names[i] == name)
				{
					return i;
				}
			}
			return -1;
		}

		private static Vector3 Joint(Matrix4x4 bindPose)
		{
			//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_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)
			Matrix4x4 inverse = ((Matrix4x4)(ref bindPose)).inverse;
			return ((Matrix4x4)(ref inverse)).MultiplyPoint3x4(Vector3.zero);
		}

		private static void Set(Matrix4x4[] change, bool[] changes, int bone, Matrix4x4 matrix)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			change[bone] = matrix;
			changes[bone] = !((Matrix4x4)(ref matrix)).isIdentity;
		}

		private static bool Counts(bool[] changes, int bone, float weight)
		{
			if (weight > 0f && bone >= 0 && bone < changes.Length)
			{
				return changes[bone];
			}
			return false;
		}

		private static float Add(ref Matrix4x4 sum, Matrix4x4[] change, int bone, float weight)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			if (weight <= 0f || bone < 0 || bone >= change.Length)
			{
				return 0f;
			}
			Matrix4x4 val = change[bone];
			for (int i = 0; i < 16; i++)
			{
				int num = i;
				((Matrix4x4)(ref sum))[num] = ((Matrix4x4)(ref sum))[num] + ((Matrix4x4)(ref val))[i] * weight;
			}
			return weight;
		}

		private static Matrix4x4 Squeeze(Vector3 point, Vector3 along, float factor)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: 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_00de: 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_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			if (((Vector3)(ref along)).sqrMagnitude < 1E-12f || Mathf.Abs(factor - 1f) < 0.0005f)
			{
				return Matrix4x4.identity;
			}
			Vector3 normalized = ((Vector3)(ref along)).normalized;
			float num = 1f - factor;
			Matrix4x4 identity = Matrix4x4.identity;
			identity.m00 = factor + num * normalized.x * normalized.x;
			identity.m01 = num * normalized.x * normalized.y;
			identity.m02 = num * normalized.x * normalized.z;
			identity.m10 = num * normalized.y * normalized.x;
			identity.m11 = factor + num * normalized.y * normalized.y;
			identity.m12 = num * normalized.y * normalized.z;
			identity.m20 = num * normalized.z * normalized.x;
			identity.m21 = num * normalized.z * normalized.y;
			identity.m22 = factor + num * normalized.z * normalized.z;
			return About(point, identity);
		}

		private static Matrix4x4 Shrink(Vector3 point, float factor)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (Mathf.Abs(factor - 1f) < 0.0005f)
			{
				return Matrix4x4.identity;
			}
			return About(point, Matrix4x4.Scale(new Vector3(factor, factor, factor)));
		}

		private static Matrix4x4 About(Vector3 point, Matrix4x4 linear)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: 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_000e: 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_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = point - ((Matrix4x4)(ref linear)).MultiplyVector(point);
			linear.m03 = val.x;
			linear.m13 = val.y;
			linear.m23 = val.z;
			return linear;
		}
	}
	[BepInPlugin("com.skaket.valheim.femininefigure", "Feminine Figure", "1.0.0")]
	public class FeminineFigurePlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.skaket.valheim.femininefigure";

		public const string PluginName = "Feminine Figure";

		public const string PluginVersion = "1.0.0";

		private const string Section = "Female body";

		internal static ManualLogSource Log;

		private Harmony? _harmony;

		private ConfigEntry<bool> _enabled;

		private ConfigEntry<float> _upperArm;

		private ConfigEntry<float> _forearm;

		private ConfigEntry<float> _hand;

		private FileSystemWatcher? _watcher;

		private long _reloadAt;

		private bool _settingsChanged;

		private string _applied = "";

		private void Awake()
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Expected O, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Expected O, but got Unknown
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			AcceptableValueRange<float> val = new AcceptableValueRange<float>(0.6f, 1.2f);
			_enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Reshape the body. Off shows the game's own shape. Applies to every character with the female body that you see, not only your own. Takes effect at once.");
			_upperArm = ((BaseUnityPlugin)this).Config.Bind<float>("Female body", "UpperArmThickness", 0.8f, new ConfigDescription("How thick the arm is between shoulder and elbow, as a fraction of the game's. Its length stays. 1 is the game's own shape. Takes effect at once, also when this file is saved while the game runs.", (AcceptableValueBase)(object)val, Array.Empty<object>()));
			_forearm = ((BaseUnityPlugin)this).Config.Bind<float>("Female body", "ForearmThickness", 0.85f, new ConfigDescription("How thick the arm is between elbow and wrist, as a fraction of the game's. Its length stays. 1 is the game's own shape. Takes effect at once, also when this file is saved while the game runs.", (AcceptableValueBase)(object)val, Array.Empty<object>()));
			_hand = ((BaseUnityPlugin)this).Config.Bind<float>("Female body", "HandSize", 0.8f, new ConfigDescription("How big the hand and fingers are, as a fraction of the game's. The hand shrinks towards the wrist; what it holds stays where the game puts it, so much below 0.8 a grip may look loose. 1 is the game's own shape. Takes effect at once, also when this file is saved while the game runs.", (AcceptableValueBase)(object)val, Array.Empty<object>()));
			((BaseUnityPlugin)this).Config.SettingChanged += delegate
			{
				_settingsChanged = true;
			};
			ApplySettings();
			_harmony = new Harmony("com.skaket.valheim.femininefigure");
			if (BodyMeshSwap.Install(_harmony))
			{
				Log.LogInfo((object)"Watching for characters with the female body. A 'Reshaped body mesh' line follows when the first one is drawn.");
			}
			WatchConfigFile();
		}

		private void Update()
		{
			long num = Interlocked.Read(in _reloadAt);
			if (num != 0L && DateTime.UtcNow.Ticks >= num)
			{
				Interlocked.Exchange(ref _reloadAt, 0L);
				try
				{
					((BaseUnityPlugin)this).Config.Reload();
					_settingsChanged = true;
				}
				catch (Exception ex)
				{
					Log.LogWarning((object)("The config file could not be read again; keeping the current shape. " + ex.Message));
				}
			}
			if (_settingsChanged)
			{
				_settingsChanged = false;
				ApplySettings();
			}
		}

		private void OnDestroy()
		{
			_watcher?.Dispose();
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private void ApplySettings()
		{
			ArmShape armShape = new ArmShape
			{
				UpperArm = _upperArm.Value,
				Forearm = _forearm.Value,
				Hand = _hand.Value
			};
			string text = (_enabled.Value ? armShape.ToString() : "off");
			if (!(text == _applied))
			{
				_applied = text;
				Log.LogInfo((object)((!_enabled.Value) ? "Female body: reshaping is off (Enabled = false)." : (armShape.IsVanilla ? "Female body: every number is 1, so it is left vanilla." : $"Female body shape: {armShape}.")));
				BodyMeshSwap.SetShape(_enabled.Value, armShape);
			}
		}

		private void WatchConfigFile()
		{
			try
			{
				string configFilePath = ((BaseUnityPlugin)this).Config.ConfigFilePath;
				_watcher = new FileSystemWatcher(Path.GetDirectoryName(configFilePath), Path.GetFileName(configFilePath))
				{
					NotifyFilter = (NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.CreationTime)
				};
				FileSystemEventHandler value = delegate
				{
					Interlocked.Exchange(ref _reloadAt, DateTime.UtcNow.AddSeconds(0.5).Ticks);
				};
				_watcher.Changed += value;
				_watcher.Created += value;
				_watcher.Renamed += delegate
				{
					Interlocked.Exchange(ref _reloadAt, DateTime.UtcNow.AddSeconds(0.5).Ticks);
				};
				_watcher.EnableRaisingEvents = true;
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("Could not watch the config file, so changes to it apply on the next launch. " + ex.Message));
			}
		}
	}
}