Decompiled source of Hearthpack Oaths v1.0.1

BepInEx/plugins/TamedWolfProgression/TamedWolfProgression.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Utils;
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("TamedWolfProgression")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1+eab6c7e89f658012dfcf541fd5b3c00fa1ebd550")]
[assembly: AssemblyProduct("TamedWolfProgression")]
[assembly: AssemblyTitle("TamedWolfProgression")]
[assembly: AssemblyVersion("1.0.1.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 TamedWolfProgression
{
	internal sealed class TrainingRecord
	{
		private const byte Format = 1;

		private const int ReceiptLimit = 128;

		private readonly List<(long Creator, uint Object)> receipts = new List<(long, uint)>();

		internal int BirthStars { get; }

		internal long EarnedStars { get; private set; }

		internal long Stars => BirthStars + EarnedStars;

		internal decimal Lifetime { get; private set; }

		internal decimal XP { get; private set; }

		internal decimal HealthBonus { get; private set; }

		internal decimal DamageBonus { get; private set; }

		internal TrainingRecord(int birthStars)
		{
			BirthStars = Math.Max(0, birthStars);
		}

		internal decimal Threshold(decimal first, decimal growth)
		{
			return first + growth * (decimal)Stars;
		}

		internal void Award(decimal amount, decimal first, decimal growth, decimal healthPerStar, decimal damagePerStar)
		{
			if (amount <= 0m)
			{
				return;
			}
			Lifetime += amount;
			XP += amount;
			decimal next = Threshold(first, growth);
			if (XP < next)
			{
				return;
			}
			long num = 1L;
			long num2 = (long)Math.Min(long.MaxValue - Stars, decimal.Floor(XP / next));
			while (num < num2)
			{
				long num3 = num + (num2 - num) / 2 + 1;
				if (Cost(num3) <= XP)
				{
					num = num3;
				}
				else
				{
					num2 = num3 - 1;
				}
			}
			XP -= Cost(num);
			EarnedStars += num;
			HealthBonus += (decimal)num * healthPerStar;
			DamageBonus += (decimal)num * damagePerStar;
			decimal Cost(long n)
			{
				return (decimal)n * (next + (decimal)(n - 1) * growth / 2m);
			}
		}

		internal bool AcceptKill(long creator, uint id)
		{
			(long, uint) item = (creator, id);
			if (receipts.Contains(item))
			{
				return false;
			}
			if (receipts.Count == 128)
			{
				receipts.RemoveAt(0);
			}
			receipts.Add(item);
			return true;
		}

		internal byte[] Encode()
		{
			using MemoryStream memoryStream = new MemoryStream();
			using BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
			binaryWriter.Write((byte)1);
			binaryWriter.Write(BirthStars);
			binaryWriter.Write(EarnedStars);
			binaryWriter.Write(Lifetime);
			binaryWriter.Write(XP);
			binaryWriter.Write(HealthBonus);
			binaryWriter.Write(DamageBonus);
			binaryWriter.Write((byte)receipts.Count);
			foreach (var receipt in receipts)
			{
				binaryWriter.Write(receipt.Creator);
				binaryWriter.Write(receipt.Object);
			}
			return memoryStream.ToArray();
		}

		internal static TrainingRecord Decode(byte[] data)
		{
			using MemoryStream input = new MemoryStream(data, writable: false);
			using BinaryReader binaryReader = new BinaryReader(input);
			if (binaryReader.ReadByte() != 1)
			{
				throw new InvalidDataException("Unknown wolf training record version.");
			}
			TrainingRecord trainingRecord = new TrainingRecord(binaryReader.ReadInt32())
			{
				EarnedStars = binaryReader.ReadInt64(),
				Lifetime = binaryReader.ReadDecimal(),
				XP = binaryReader.ReadDecimal(),
				HealthBonus = binaryReader.ReadDecimal(),
				DamageBonus = binaryReader.ReadDecimal()
			};
			int num = binaryReader.ReadByte();
			for (int i = 0; i < num; i++)
			{
				trainingRecord.receipts.Add((binaryReader.ReadInt64(), binaryReader.ReadUInt32()));
			}
			return trainingRecord;
		}
	}
	[BepInPlugin("valheimcollection.tamedwolfprogression", "Hearthpack Oaths", "1.0.1")]
	[BepInDependency("com.jotunn.jotunn", "2.30.2")]
	[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
	public sealed class WolfPlugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(Growup), "GrowUpdate")]
		private static class CubGrowth
		{
			private static void Prefix(Growup __instance, out byte[] __state)
			{
				__state = growingCub;
				growingCub = null;
				WolfTraining wolfTraining = default(WolfTraining);
				if (((Component)__instance).TryGetComponent<WolfTraining>(ref wolfTraining) && wolfTraining.IsTamed && wolfTraining.View.IsOwner())
				{
					growingCub = wolfTraining.View.GetZDO().GetByteArray(WolfTraining.DataKey, (byte[])null);
				}
			}

			private static void Finalizer(byte[] __state)
			{
				growingCub = __state;
			}
		}

		internal const string Id = "valheimcollection.tamedwolfprogression";

		internal static ConfigEntry<float> Food;

		internal static ConfigEntry<float> Kill;

		internal static ConfigEntry<float> Metre;

		internal static ConfigEntry<float> BaseCost;

		internal static ConfigEntry<float> Growth;

		internal static ConfigEntry<float> Health;

		internal static ConfigEntry<float> Damage;

		internal static ConfigEntry<bool> LogAwards;

		internal static ManualLogSource Log;

		private Harmony patches;

		[ThreadStatic]
		private static byte[] growingCub;

		private void Awake()
		{
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Food = Number("XP", "Food", 10f, 0f, "XP per food item actually eaten by a tamed wolf.");
			Kill = Number("XP", "Kill", 25f, 0f, "XP per hostile killing blow.");
			Metre = Number("XP", "PerMetre", 0.1f, 0f, "XP per horizontal metre walked or run.");
			BaseCost = Number("Thresholds", "Base", 100f, 0.01f, "XP cost at zero stars.");
			Growth = Number("Thresholds", "PerStar", 50f, 0f, "Added cost per current star, including birth stars.");
			Health = Number("Stats", "HealthPercent", 100f, 0.01f, "Percent of unstarred base max health added per future star.");
			Damage = Number("Stats", "DamagePercent", 50f, 0.01f, "Percent of unstarred attack damage added per future star.");
			LogAwards = ((BaseUnityPlugin)this).Config.Bind<bool>("Diagnostics", "LogAwards", false, "Log each award on the wolf's simulation owner.");
			patches = new Harmony("valheimcollection.tamedwolfprogression");
			patches.PatchAll(typeof(WolfPlugin));
			patches.PatchAll(typeof(CubGrowth));
		}

		private ConfigEntry<float> Number(string section, string name, float value, float min, string description)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			return ((BaseUnityPlugin)this).Config.Bind<float>(section, name, value, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<float>(min, 1000000f), new object[1] { (object)new ConfigurationManagerAttributes
			{
				IsAdminOnly = true
			} }));
		}

		private void OnDestroy()
		{
			Harmony obj = patches;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
		}

		[HarmonyPatch(typeof(ZNet), "Save")]
		[HarmonyPrefix]
		private static void FlushBeforeSave()
		{
			WolfTraining[] array = Object.FindObjectsByType<WolfTraining>((FindObjectsSortMode)0);
			for (int i = 0; i < array.Length; i++)
			{
				array[i].FlushTravel();
			}
		}

		[HarmonyPatch(typeof(Character), "Awake")]
		[HarmonyPostfix]
		private static void CharacterReady(Character __instance)
		{
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if (Object.op_Implicit((Object)(object)component) && component.IsValid() && WolfTraining.IsWolf(component.GetZDO()))
			{
				if (growingCub != null && WolfTraining.IsAdult(component.GetZDO()) && component.IsOwner())
				{
					component.GetZDO().Set(WolfTraining.DataKey, growingCub);
				}
				((Component)__instance).gameObject.AddComponent<WolfTraining>();
			}
		}

		[HarmonyPatch(typeof(Character), "SetupMaxHealth")]
		[HarmonyPrefix]
		private static bool RestoreMaxHealth(Character __instance, ZNetView ___m_nview)
		{
			if (!Object.op_Implicit((Object)(object)___m_nview) || !___m_nview.IsValid())
			{
				return true;
			}
			ZDO zDO = ___m_nview.GetZDO();
			if (!WolfTraining.IsWolf(zDO) || !__instance.IsTamed())
			{
				return true;
			}
			byte[] byteArray = zDO.GetByteArray(WolfTraining.DataKey, (byte[])null);
			if (byteArray == null)
			{
				return true;
			}
			TrainingRecord trainingRecord = TrainingRecord.Decode(byteArray);
			if (trainingRecord.HealthBonus == 0m)
			{
				return true;
			}
			WolfTraining.ApplyHealth(__instance, trainingRecord);
			return false;
		}

		[HarmonyPatch(typeof(Attack), "GetLevelDamageFactor")]
		[HarmonyPostfix]
		private static void AttackScale(Humanoid ___m_character, ref float __result)
		{
			WolfTraining wolfTraining = default(WolfTraining);
			if (Object.op_Implicit((Object)(object)___m_character) && ((Component)___m_character).TryGetComponent<WolfTraining>(ref wolfTraining) && wolfTraining.IsTamed)
			{
				__result += (float)wolfTraining.State.DamageBonus;
			}
		}

		[HarmonyPatch(typeof(Tameable), "OnConsumedItem")]
		[HarmonyPostfix]
		private static void Ate(Tameable __instance)
		{
			WolfTraining wolfTraining = default(WolfTraining);
			if (((Component)__instance).TryGetComponent<WolfTraining>(ref wolfTraining))
			{
				wolfTraining.Award("food", (decimal)Food.Value);
			}
		}

		[HarmonyPatch(typeof(Character), "OnDeath")]
		[HarmonyPrefix]
		private static void Killed(Character __instance, HitData ___m_lastHit)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if (__instance.IsOwner() && !__instance.IsPlayer() && ___m_lastHit != null)
			{
				Character attacker = ___m_lastHit.GetAttacker();
				WolfTraining wolfTraining = default(WolfTraining);
				if (Object.op_Implicit((Object)(object)attacker) && ((Component)attacker).TryGetComponent<WolfTraining>(ref wolfTraining) && wolfTraining.IsTamed && BaseAI.IsEnemy(attacker, __instance))
				{
					wolfTraining.ReportKill(__instance.GetZDOID());
				}
			}
		}

		[HarmonyPatch(typeof(Tameable), "GetHoverName")]
		[HarmonyPostfix]
		private static void Name(Tameable __instance, ref string __result)
		{
			WolfTraining wolfTraining = default(WolfTraining);
			if (((Component)__instance).TryGetComponent<WolfTraining>(ref wolfTraining) && wolfTraining.IsTamed)
			{
				__result = __result + "  ★ " + wolfTraining.State.Stars;
			}
		}

		[HarmonyPatch(typeof(EnemyHud), "UpdateHuds")]
		[HarmonyTranspiler]
		private static IEnumerable<CodeInstruction> WolfHudStars(IEnumerable<CodeInstruction> instructions)
		{
			MethodInfo original = AccessTools.Method(typeof(Character), "GetLevel", (Type[])null, (Type[])null);
			MethodInfo replacement = AccessTools.Method(typeof(WolfPlugin), "IconLevel", (Type[])null, (Type[])null);
			foreach (CodeInstruction instruction in instructions)
			{
				if (CodeInstructionExtensions.Calls(instruction, original))
				{
					instruction.opcode = OpCodes.Call;
					instruction.operand = replacement;
				}
				yield return instruction;
			}
		}

		private static int IconLevel(Character character)
		{
			WolfTraining wolfTraining = default(WolfTraining);
			if (!((Component)character).TryGetComponent<WolfTraining>(ref wolfTraining) || !wolfTraining.IsTamed)
			{
				return character.GetLevel();
			}
			return 1;
		}

		[HarmonyPatch(typeof(Tameable), "GetHoverText")]
		[HarmonyPostfix]
		private static void Hover(Tameable __instance, ref string __result)
		{
			WolfTraining wolfTraining = default(WolfTraining);
			if (((Component)__instance).TryGetComponent<WolfTraining>(ref wolfTraining) && wolfTraining.IsTamed)
			{
				TrainingRecord state = wolfTraining.State;
				decimal num = state.Threshold((decimal)BaseCost.Value, (decimal)Growth.Value);
				__result += $"\n★ {state.Stars}   XP {state.XP:0.##} / {num:0.##}   (total {state.Lifetime:0.##})";
			}
		}
	}
	internal sealed class WolfTraining : MonoBehaviour
	{
		internal static readonly int DataKey = StringExtensionMethods.GetStableHashCode("valheimcollection.wolf.training");

		private static readonly int Adult = StringExtensionMethods.GetStableHashCode("Wolf");

		private static readonly int Cub = StringExtensionMethods.GetStableHashCode("Wolf_cub");

		private static readonly FieldRef<Character, Rigidbody> GroundBody = AccessTools.FieldRefAccess<Character, Rigidbody>("m_lastGroundBody");

		private const string KillRpc = "VMWolf.Kill";

		private const string AckRpc = "VMWolf.Receipt";

		private readonly Dictionary<ZDOID, float> pending = new Dictionary<ZDOID, float>();

		private readonly List<ZDOID> toSend = new List<ZDOID>();

		private Character wolf;

		private TrainingRecord cached;

		private byte[] cachedBytes;

		private bool wasOwner;

		private bool walking;

		private Vector3 previous;

		private Vector3 previousIntent;

		private decimal travelXP;

		private float sampleTime;

		private float nextRetry;

		internal ZNetView View { get; private set; }

		internal bool IsTamed
		{
			get
			{
				if (Object.op_Implicit((Object)(object)View) && View.IsValid())
				{
					return wolf.IsTamed();
				}
				return false;
			}
		}

		internal TrainingRecord State
		{
			get
			{
				byte[] byteArray = View.GetZDO().GetByteArray(DataKey, (byte[])null);
				int num = Math.Max(0, wolf.GetLevel() - 1);
				if (cached == null || byteArray != cachedBytes || (byteArray == null && cached.BirthStars != num))
				{
					cached = ((byteArray == null) ? new TrainingRecord(num) : TrainingRecord.Decode(byteArray));
					cachedBytes = byteArray;
				}
				return cached;
			}
		}

		internal static bool IsAdult(ZDO zdo)
		{
			return zdo.GetPrefab() == Adult;
		}

		internal static bool IsWolf(ZDO zdo)
		{
			if (!IsAdult(zdo))
			{
				return zdo.GetPrefab() == Cub;
			}
			return true;
		}

		private void Awake()
		{
			wolf = ((Component)this).GetComponent<Character>();
			View = ((Component)this).GetComponent<ZNetView>();
			View.Register<ZDOID>("VMWolf.Kill", (Action<long, ZDOID>)ReceiveKill);
			View.Register<ZDOID>("VMWolf.Receipt", (Action<long, ZDOID>)delegate(long sender, ZDOID victim)
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				if (sender == View.GetZDO().GetOwner())
				{
					pending.Remove(victim);
				}
			});
		}

		internal static void ApplyHealth(Character character, TrainingRecord state)
		{
			float num = character.GetMaxHealthBase() * ((float)character.GetLevel() + (float)state.HealthBonus);
			if (character.GetMaxHealth() != num)
			{
				character.SetMaxHealth(num);
			}
		}

		internal void Award(string source, decimal amount)
		{
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			if (!(amount <= 0m) && IsTamed && View.IsOwner() && !wolf.IsDead())
			{
				TrainingRecord state = State;
				long stars = state.Stars;
				state.Award(amount, (decimal)WolfPlugin.BaseCost.Value, (decimal)WolfPlugin.Growth.Value, (decimal)WolfPlugin.Health.Value / 100m, (decimal)WolfPlugin.Damage.Value / 100m);
				Save(state);
				if (stars != state.Stars)
				{
					ApplyHealth(wolf, state);
				}
				if (WolfPlugin.LogAwards.Value)
				{
					WolfPlugin.Log.LogInfo((object)($"{View.GetZDO().m_uid} {source} +{amount:0.###} XP, total {state.Lifetime:0.###}, " + $"partial {state.XP:0.###}, stars {state.Stars}, max HP {wolf.GetMaxHealth():0.##}, " + $"attack scale {1m + 0.5m * (decimal)state.BirthStars + state.DamageBonus:0.###}"));
				}
			}
		}

		private void Save(TrainingRecord state)
		{
			cachedBytes = state.Encode();
			View.GetZDO().Set(DataKey, cachedBytes);
		}

		internal void ReportKill(ZDOID victim)
		{
			//IL_0032: 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_0025: Unknown result type (might be due to invalid IL or missing references)
			if (!(WolfPlugin.Kill.Value <= 0f))
			{
				if (View.IsOwner())
				{
					ReceiveKill(ZDOMan.GetSessionID(), victim);
					return;
				}
				pending[victim] = Time.unscaledTime + 20f;
				View.InvokeRPC("VMWolf.Kill", new object[1] { victim });
			}
		}

		private void ReceiveKill(long sender, ZDOID victim)
		{
			//IL_0031: 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_00af: Unknown result type (might be due to invalid IL or missing references)
			if (!IsTamed || !View.IsOwner() || wolf.IsDead() || ((ZDOID)(ref victim)).IsNone())
			{
				return;
			}
			ZDO zDO = ZDOMan.instance.GetZDO(victim);
			if (zDO == null || !zDO.HasOwner() || zDO.GetOwner() == sender)
			{
				if (WolfPlugin.Kill.Value > 0f && State.AcceptKill(((ZDOID)(ref victim)).UserID, ((ZDOID)(ref victim)).ID))
				{
					Award("kill", (decimal)WolfPlugin.Kill.Value);
				}
				if (sender != ZDOMan.GetSessionID())
				{
					View.InvokeRPC(sender, "VMWolf.Receipt", new object[1] { victim });
				}
				else
				{
					pending.Remove(victim);
				}
			}
		}

		private void Update()
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			if (pending.Count == 0 || !View.IsValid() || Time.unscaledTime < nextRetry)
			{
				return;
			}
			nextRetry = Time.unscaledTime + 0.5f;
			toSend.Clear();
			toSend.AddRange(pending.Keys);
			foreach (ZDOID item in toSend)
			{
				if (Time.unscaledTime > pending[item])
				{
					pending.Remove(item);
					continue;
				}
				View.InvokeRPC("VMWolf.Kill", new object[1] { item });
			}
		}

		private void FixedUpdate()
		{
			//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_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: 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_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			if (!IsTamed || !View.IsOwner() || wolf.IsDead())
			{
				wasOwner = (walking = false);
				travelXP = default(decimal);
				return;
			}
			if (!wasOwner)
			{
				wasOwner = true;
				TrainingRecord state = State;
				if (cachedBytes == null)
				{
					Save(state);
				}
				if (state.EarnedStars > 0)
				{
					ApplyHealth(wolf, state);
				}
			}
			Vector3 moveDir = wolf.GetMoveDir();
			moveDir.y = 0f;
			bool flag = wolf.IsOnGround() && !wolf.IsSwimming() && !wolf.IsFlying() && !wolf.IsAttached() && !Object.op_Implicit((Object)(object)GroundBody.Invoke(wolf));
			if (walking && flag)
			{
				Vector3 val = ((Component)this).transform.position - previous;
				val.y = 0f;
				float magnitude = ((Vector3)(ref val)).magnitude;
				float num = Mathf.Max(wolf.m_runSpeed, wolf.m_speed) * Time.fixedDeltaTime * 1.5f + 0.08f;
				if (magnitude > 0.0001f && magnitude <= num && Vector3.Dot(val, previousIntent) > 0f)
				{
					travelXP += (decimal)magnitude * (decimal)WolfPlugin.Metre.Value;
				}
			}
			walking = flag && ((Vector3)(ref moveDir)).sqrMagnitude >= 0.01f && WolfPlugin.Metre.Value > 0f;
			previous = ((Component)this).transform.position;
			previousIntent = moveDir;
			sampleTime += Time.fixedDeltaTime;
			if (!walking || sampleTime >= 0.35f)
			{
				FlushTravel();
			}
		}

		internal void FlushTravel()
		{
			sampleTime = 0f;
			if (!(travelXP <= 0m))
			{
				decimal amount = travelXP;
				travelXP = default(decimal);
				Award("travel", amount);
			}
		}

		private void OnDisable()
		{
			FlushTravel();
		}
	}
}