Decompiled source of BetterBreed v0.2.1

plugins/ValheimBetterBreed.dll

Decompiled 5 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using ValheimBetterBreed.Patches;

[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("ValheimBetterBreed")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.1.0")]
[assembly: AssemblyInformationalVersion("0.2.1")]
[assembly: AssemblyProduct("ValheimBetterBreed")]
[assembly: AssemblyTitle("ValheimBetterBreed")]
[assembly: AssemblyVersion("0.2.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 ValheimBetterBreed
{
	internal static class Anchor
	{
		private const string SignPrefab = "sign";

		private const float CheckInterval = 2f;

		private const float ScanInterval = 30f;

		private static ZDOID _sign = ZDOID.None;

		private static Vector3 _signPos;

		private static bool _moved;

		private static bool _failed;

		private static readonly List<ZDO> _found = new List<ZDO>();

		private static int _scanIndex = -1;

		private static float _checkTimer = 2f;

		private static float _scanTimer = 30f;

		private static bool _scannedOnce;

		private static string _lastReport;

		internal static bool IsActive { get; private set; }

		internal static void Update(float dt)
		{
			if (_failed)
			{
				return;
			}
			ZNet instance = ZNet.instance;
			if ((Object)(object)instance == (Object)null || !instance.IsDedicated() || ZDOMan.instance == null)
			{
				return;
			}
			if (_scanIndex >= 0)
			{
				StepScan();
			}
			else
			{
				_scanTimer += dt;
				if (_scanTimer >= 30f)
				{
					_scanTimer = 0f;
					_found.Clear();
					_scanIndex = 0;
				}
			}
			_checkTimer += dt;
			if (!(_checkTimer < 2f) && _scannedOnce)
			{
				_checkTimer = 0f;
				Apply(instance);
			}
		}

		internal static void Rescan()
		{
			_scanTimer = 30f;
			_checkTimer = 2f;
		}

		internal static void Fail(Exception e)
		{
			_failed = true;
			Plugin.Log.LogError((object)($"Error while sharing objects with players ({e}). BetterBreed stops " + "until the server restarts: the server behaves as without the mod."));
			Stop();
		}

		internal static void Stop()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			IsActive = false;
			ZNet instance = ZNet.instance;
			if (_moved && (Object)(object)instance != (Object)null)
			{
				instance.SetReferencePosition(Vector3.zero);
			}
			_moved = false;
		}

		private static void StepScan()
		{
			if (ZDOMan.instance.GetAllZDOsWithPrefabIterative("sign", _found, ref _scanIndex))
			{
				_scanIndex = -1;
				_scannedOnce = true;
				ChooseSign();
				_found.Clear();
				_checkTimer = 2f;
			}
		}

		private static void ChooseSign()
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			List<ZDO> list = new List<ZDO>();
			HashSet<ZDOID> hashSet = new HashSet<ZDOID>();
			foreach (ZDO item in _found)
			{
				if (hashSet.Add(item.m_uid) && Matches(item))
				{
					list.Add(item);
				}
			}
			if (list.Count == 0)
			{
				_sign = ZDOID.None;
				return;
			}
			ZDO val = list.Find((ZDO z) => z.m_uid == _sign);
			if (val == null)
			{
				list.Sort((ZDO a, ZDO b) => ((ZDOID)(ref a.m_uid)).CompareTo(b.m_uid));
				val = list[0];
			}
			_sign = val.m_uid;
			if (list.Count > 1)
			{
				Report($"{list.Count} signs contain '{Options.Keyword}'. The one at " + Describe(val.GetPosition()) + " is used, the others are ignored.", warning: true);
			}
		}

		private static void Apply(ZNet net)
		{
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: 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_008a: Unknown result type (might be due to invalid IL or missing references)
			string text = null;
			World world = ZNet.World;
			string text2 = ((world != null) ? world.m_name : "");
			if (!Options.IsWorldEnabled(text2))
			{
				text = "world '" + text2 + "' is not listed in Worlds";
			}
			else if (Options.Keyword.Length == 0)
			{
				text = "SignKeyword is empty";
			}
			else if (!SignStillThere())
			{
				text = "no sign contains '" + Options.Keyword + "'";
			}
			else if (net.GetNrOfPlayers() == 0)
			{
				text = "no player is connected";
			}
			if (text == null)
			{
				if (net.GetReferencePosition() != _signPos)
				{
					net.SetReferencePosition(_signPos);
				}
				_moved = true;
				IsActive = true;
				Report("Keeping the area around the sign at " + Describe(_signPos) + " running.");
			}
			else
			{
				Stop();
				Report("Idle, " + text + ": the server behaves as without the mod.");
			}
		}

		private static bool SignStillThere()
		{
			//IL_0013: 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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			if (((ZDOID)(ref _sign)).IsNone())
			{
				return false;
			}
			ZDO zDO = ZDOMan.instance.GetZDO(_sign);
			if (zDO == null || !Matches(zDO))
			{
				_sign = ZDOID.None;
				_scanTimer = 30f;
				return false;
			}
			_signPos = zDO.GetPosition();
			return true;
		}

		private static bool Matches(ZDO zdo)
		{
			if (!zdo.IsValid())
			{
				return false;
			}
			string keyword = Options.Keyword;
			if (keyword.Length == 0)
			{
				return false;
			}
			return zdo.GetString(ZDOVars.s_text, "").IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0;
		}

		private static string Describe(Vector3 p)
		{
			//IL_0005: 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)
			return $"({p.x:0}, {p.z:0})";
		}

		private static void Report(string message, bool warning = false)
		{
			if (!(message == _lastReport))
			{
				_lastReport = message;
				if (warning)
				{
					Plugin.Log.LogWarning((object)message);
				}
				else
				{
					Plugin.Log.LogInfo((object)message);
				}
			}
		}
	}
	internal static class Options
	{
		private const string DefaultWorlds = "*";

		private const string AllWorlds = "*";

		private const string DefaultKeyword = "BetterBreed";

		internal static ConfigEntry<string> Worlds { get; private set; }

		internal static ConfigEntry<string> SignKeyword { get; private set; }

		internal static ConfigEntry<float> BirthDistance { get; private set; }

		internal static ConfigEntry<float> CountRange { get; private set; }

		internal static string Keyword => SignKeyword.Value.Trim();

		internal static void Bind(ConfigFile config)
		{
			BirthDistance = config.Bind<float>("Breeding", "BirthDistance", 1f, "Maximum distance, in meters, between a tamed animal and its newborn. The game uses 2 m for boars, enough for a piglet to be born on the other side of a fence. A value at or above the game's own changes nothing. Only works on the machine that owns the animal: install the mod on every player's game, and on the server.");
			CountRange = config.Bind<float>("Breeding", "CountRange", 5f, "Radius, in meters, in which the game counts animals of the same kind before letting one get pregnant. The game uses 10 m, with a cap of about 4 or 5 animals in that radius. A smaller radius lets a denser pen keep breeding. A value at or above the game's own changes nothing.");
			Worlds = config.Bind<string>("General", "Worlds", "*", "Worlds where the sign works, separated by commas, or * for every world. On any other world the server ignores the sign. Leave empty to turn the sign off everywhere. Breeding settings apply on every world regardless.");
			SignKeyword = config.Bind<string>("General", "SignKeyword", "BetterBreed", "Text to write on a sign. While at least one player is connected, the server keeps the area around that sign running, as if a player stood there. Upper or lower case does not matter, and the sign may hold other text too. With no such sign, or an empty keyword, the server behaves as without the mod.");
			Worlds.SettingChanged += delegate
			{
				Anchor.Rescan();
			};
			SignKeyword.SettingChanged += delegate
			{
				Anchor.Rescan();
			};
		}

		internal static bool IsWorldEnabled(string world)
		{
			if (string.IsNullOrEmpty(world))
			{
				return false;
			}
			string[] array = Worlds.Value.Split(new char[1] { ',' });
			foreach (string text in array)
			{
				if (text.Trim() == "*")
				{
					return true;
				}
				if (string.Equals(text.Trim(), world, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
			}
			return false;
		}
	}
	internal static class Ownership
	{
		private static readonly List<ZDO> _near = new List<ZDO>();

		private static readonly List<Vector2s> _playerZones = new List<Vector2s>();

		private static readonly Dictionary<int, bool> _isCreature = new Dictionary<int, bool>();

		internal static void ReleaseNearby(Vector3 refPosition)
		{
			//IL_0006: 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_000c: 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)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: 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_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: 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_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: 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)
			long sessionID = ZDOMan.GetSessionID();
			Vector2s zone = ZoneSystem.GetZone(refPosition);
			SimulationDistance syncedSimulationDistance = ZNet.instance.GetSyncedSimulationDistance();
			SimulationDistance val = default(SimulationDistance);
			((SimulationDistance)(ref val))..ctor(((SimulationDistance)(ref syncedSimulationDistance)).NearSimulationDistance, 0, ((SimulationDistance)(ref syncedSimulationDistance)).IsClassic);
			_playerZones.Clear();
			foreach (ZNetPeer peer in ZNet.instance.GetPeers())
			{
				if (peer.IsReady())
				{
					_playerZones.Add(ZoneSystem.GetZone(peer.GetRefPos()));
				}
			}
			_near.Clear();
			ZDOMan.instance.FindSectorObjects(zone, val, _near, (List<ZDO>)null);
			foreach (ZDO item in _near)
			{
				if (!item.Persistent)
				{
					continue;
				}
				Vector3 position = item.GetPosition();
				bool flag = ZNetScene.InActiveArea(position, zone) && !NearPlayer(position) && !IsWildCreature(item);
				if (item.GetOwner() == sessionID)
				{
					if (!flag)
					{
						item.SetOwner(0L);
					}
				}
				else if (flag && (!item.HasOwner() || !OwnerIsNear(position, item.GetOwner())))
				{
					item.SetOwner(sessionID);
				}
			}
			_near.Clear();
		}

		private static bool NearPlayer(Vector3 position)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			foreach (Vector2s playerZone in _playerZones)
			{
				if (ZNetScene.InActiveArea(position, playerZone))
				{
					return true;
				}
			}
			return false;
		}

		private static bool OwnerIsNear(Vector3 position, long owner)
		{
			//IL_0011: 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)
			ZNetPeer peer = ZNet.instance.GetPeer(owner);
			if (peer == null)
			{
				return false;
			}
			return ZNetScene.InActiveArea(position, peer.GetRefPos());
		}

		private static bool IsWildCreature(ZDO zdo)
		{
			int prefab = zdo.GetPrefab();
			if (!_isCreature.TryGetValue(prefab, out var value))
			{
				GameObject prefab2 = ZNetScene.instance.GetPrefab(prefab);
				value = (Object)(object)prefab2 != (Object)null && (Object)(object)prefab2.GetComponent<Character>() != (Object)null;
				_isCreature[prefab] = value;
			}
			if (value)
			{
				return !zdo.GetBool(ZDOVars.s_tamed, false);
			}
			return false;
		}
	}
	[BepInPlugin("moochi.valheim.betterbreed", "BetterBreed", "0.2.1")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "moochi.valheim.betterbreed";

		public const string PluginName = "BetterBreed";

		public const string PluginVersion = "0.2.1";

		private Harmony _harmony;

		private FileSystemWatcher _watcher;

		private bool _ready;

		internal static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Invalid comparison between Unknown and I4
			Log = ((BaseUnityPlugin)this).Logger;
			Options.Bind(((BaseUnityPlugin)this).Config);
			_harmony = new Harmony("moochi.valheim.betterbreed");
			bool num = TryPatch(typeof(Procreation_Procreate_Patch), "Procreation.Procreate", "births and pen counts stay as in the game");
			_ready = TryPatch(typeof(ZDOMan_ReleaseNearbyZDOS_Patch), "ZDOMan.ReleaseNearbyZDOS", "the sign is ignored: the server behaves as without the mod");
			WatchConfigFile();
			Log.LogInfo((object)"BetterBreed v0.2.1 loaded.");
			if (num)
			{
				Log.LogInfo((object)($"Breeding: newborns at most {Options.BirthDistance.Value} m from the parent, " + $"same-kind animals counted within {Options.CountRange.Value} m."));
			}
			if (_ready && (int)SystemInfo.graphicsDeviceType == 4)
			{
				Log.LogInfo((object)("Worlds '" + Options.Worlds.Value + "': the area around the sign containing '" + Options.SignKeyword.Value + "' keeps running while players are connected."));
			}
		}

		private bool TryPatch(Type patch, string target, string consequence)
		{
			try
			{
				_harmony.CreateClassProcessor(patch).Patch();
				return true;
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Could not patch " + target + " (" + ex.Message + "): " + consequence + "."));
				return false;
			}
		}

		private void Update()
		{
			if (_ready)
			{
				Anchor.Update(Time.deltaTime);
			}
		}

		private void WatchConfigFile()
		{
			_watcher = new FileSystemWatcher(Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath), Path.GetFileName(((BaseUnityPlugin)this).Config.ConfigFilePath));
			_watcher.Changed += delegate
			{
				ReloadConfig();
			};
			_watcher.Created += delegate
			{
				ReloadConfig();
			};
			_watcher.Renamed += delegate
			{
				ReloadConfig();
			};
			_watcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			_watcher.EnableRaisingEvents = true;
		}

		private void ReloadConfig()
		{
			if (!File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath))
			{
				return;
			}
			try
			{
				((BaseUnityPlugin)this).Config.Reload();
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Could not read " + Path.GetFileName(((BaseUnityPlugin)this).Config.ConfigFilePath) + ": " + ex.Message));
			}
		}

		private void OnDestroy()
		{
			Anchor.Stop();
			if (_harmony != null)
			{
				_harmony.UnpatchSelf();
			}
			if (_watcher != null)
			{
				_watcher.Dispose();
			}
		}
	}
}
namespace ValheimBetterBreed.Patches
{
	[HarmonyPatch(typeof(Procreation), "Procreate")]
	internal static class Procreation_Procreate_Patch
	{
		internal struct Saved
		{
			public bool Changed;

			public float SpawnOffset;

			public float SpawnOffsetMax;

			public float TotalCheckRange;
		}

		private static void Prefix(Procreation __instance, out Saved __state)
		{
			__state = new Saved
			{
				SpawnOffset = __instance.m_spawnOffset,
				SpawnOffsetMax = __instance.m_spawnOffsetMax,
				TotalCheckRange = __instance.m_totalCheckRange
			};
			float num = Mathf.Max(0f, Options.BirthDistance.Value);
			float num2 = Mathf.Max(0f, Options.CountRange.Value);
			__instance.m_spawnOffset = Mathf.Min(__instance.m_spawnOffset, num);
			if (__instance.m_spawnOffsetMax > 0f)
			{
				__instance.m_spawnOffsetMax = Mathf.Max(__instance.m_spawnOffset, Mathf.Min(__instance.m_spawnOffsetMax, num));
			}
			__instance.m_totalCheckRange = Mathf.Min(__instance.m_totalCheckRange, num2);
			__state.Changed = true;
		}

		private static Exception Finalizer(Exception __exception, Procreation __instance, Saved __state)
		{
			if (__state.Changed && (Object)(object)__instance != (Object)null)
			{
				__instance.m_spawnOffset = __state.SpawnOffset;
				__instance.m_spawnOffsetMax = __state.SpawnOffsetMax;
				__instance.m_totalCheckRange = __state.TotalCheckRange;
			}
			return __exception;
		}
	}
	[HarmonyPatch(typeof(ZDOMan), "ReleaseNearbyZDOS")]
	internal static class ZDOMan_ReleaseNearbyZDOS_Patch
	{
		private static bool Prefix(Vector3 refPosition, long uid)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (!Anchor.IsActive || uid != ZDOMan.GetSessionID())
			{
				return true;
			}
			try
			{
				Ownership.ReleaseNearby(refPosition);
			}
			catch (Exception e)
			{
				Anchor.Fail(e);
			}
			return false;
		}
	}
}