Decompiled source of DiminishingReturnsSyncFix v0.0.1

DiminishingReturns.dll

Decompiled 8 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
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 CSync.Extensions;
using CSync.Lib;
using DiminishingReturns.NetcodePatcher;
using HarmonyLib;
using JackEhttack.netcode;
using JackEhttack.patch;
using JackEhttack.service;
using Microsoft.CodeAnalysis;
using Unity.Mathematics;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("DiminishingReturns")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.9.0")]
[assembly: AssemblyInformationalVersion("1.0.9-alpha.0.2+e7419fe6bd3e3bae69e56eda0b7ef6e6d6303a0a")]
[assembly: AssemblyProduct("DiminishingReturns")]
[assembly: AssemblyTitle("DiminishingReturns")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
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 JackEhttack
{
	public class DRConfig : SyncedConfig2<DRConfig>
	{
		[field: SyncedEntryField]
		public SyncedEntry<int> restock { get; private set; }

		[field: SyncedEntryField]
		public SyncedEntry<float> denominator { get; private set; }

		[field: SyncedEntryField]
		public SyncedEntry<float> amount { get; private set; }

		[field: SyncedEntryField]
		public SyncedEntry<float> maxBonus { get; private set; }

		[field: SyncedEntryField]
		public SyncedEntry<float> bonusChance { get; private set; }

		[field: SyncedEntryField]
		public SyncedEntry<float> moonDiscount { get; private set; }

		public DRConfig(ConfigFile cfg)
			: base("DiminishingReturns")
		{
			cfg.SaveOnConfigSet = false;
			restock = SyncedBindingExtensions.BindSyncedEntry<int>(cfg, "General", "DaysTillRestock", 4, "How many days until a moon with diminishing returns regenerate their scrap to full.");
			denominator = SyncedBindingExtensions.BindSyncedEntry<float>(cfg, "General", "MaxDiminish", 0.5f, "The maximum amount a moon's scrap can be diminished.");
			amount = SyncedBindingExtensions.BindSyncedEntry<float>(cfg, "General", "DiminishAmount", 1f, "How much a moon is diminished per visit. Note: diminishment will not exceed MaxDiminish. [0 - 1.0]");
			maxBonus = SyncedBindingExtensions.BindSyncedEntry<float>(cfg, "General", "MaxBonus", 3.2f, "The upper limit for a bonus moon's scrap.");
			bonusChance = SyncedBindingExtensions.BindSyncedEntry<float>(cfg, "General", "BonusChance", 0.5f, "The chance of a bonus moon appearing per day.");
			moonDiscount = SyncedBindingExtensions.BindSyncedEntry<float>(cfg, "General", "MoonDiscount", 0.5f, "A discount applied to the price of moons, to make up for diminishment. [0 - 1.0]");
			ClearOrphanedEntries(cfg);
			cfg.Save();
			cfg.SaveOnConfigSet = true;
			ConfigManager.Register<DRConfig>((SyncedConfig2<DRConfig>)this);
		}

		private static void ClearOrphanedEntries(ConfigFile cfg)
		{
			((Dictionary<ConfigDefinition, string>)AccessTools.Property(typeof(ConfigFile), "OrphanedEntries").GetValue(cfg)).Clear();
		}
	}
	[BepInPlugin("DiminishingReturns", "DiminishingReturns", "1.0.0")]
	[BepInDependency("com.sigurd.csync", "5.0.1")]
	public class Plugin : BaseUnityPlugin
	{
		public static MoonTracker Service;

		public AssetBundle MainAssetBundle;

		internal static DRConfig Config;

		public static Plugin Instance { get; set; }

		public ManualLogSource Log => ((BaseUnityPlugin)Instance).Logger;

		public Plugin()
		{
			Instance = this;
		}

		private static void NetcodePatcher()
		{
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			for (int i = 0; i < types.Length; i++)
			{
				MethodInfo[] methods = types[i].GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				foreach (MethodInfo methodInfo in methods)
				{
					if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}

		private void Awake()
		{
			Service = new MoonTracker();
			Config = new DRConfig(((BaseUnityPlugin)this).Config);
			string text = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "DiminishingReturns.assets");
			MainAssetBundle = AssetBundle.LoadFromFile(text);
			NetcodePatcher();
			Log.LogInfo((object)"Applying patches...");
			Harmony.CreateAndPatchAll(typeof(ScrapModifierPatches), (string)null);
			Harmony.CreateAndPatchAll(typeof(TerminalPatches), (string)null);
			Harmony.CreateAndPatchAll(typeof(NetworkObjectManager), (string)null);
			Log.LogInfo((object)"Applied all patches!");
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "DiminishingReturns";

		public const string PLUGIN_NAME = "DiminishingReturns";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace JackEhttack.service
{
	public class MoonTracker
	{
		public static MoonTracker Instance;

		private string trackerText;

		private string bonusMoon;

		private float bonusAmount;

		private Dictionary<string, float> moonVisits;

		public void DiminishMoon(SelectableLevel moon)
		{
			if (!(((Object)moon).name == "CompanyBuildingLevel"))
			{
				if (moonVisits.ContainsKey(moon.PlanetName))
				{
					moonVisits[moon.PlanetName] = Math.Min(Plugin.Config.restock.Value, moonVisits[moon.PlanetName] + (float)Plugin.Config.restock.Value / Plugin.Config.denominator.Value * Plugin.Config.amount.Value);
				}
				else
				{
					moonVisits[moon.PlanetName] = Math.Min(Plugin.Config.restock.Value, (float)Plugin.Config.restock.Value / Plugin.Config.denominator.Value * Plugin.Config.amount.Value);
				}
				UpdateClientTrackers();
			}
		}

		public MoonTracker()
		{
			Instance = this;
			trackerText = "";
			moonVisits = new Dictionary<string, float>();
			bonusMoon = "";
			bonusAmount = 1f;
		}

		public void ReplenishMoons()
		{
			if (StartOfRound.Instance.currentLevel.levelID == 3)
			{
				return;
			}
			foreach (string item in moonVisits.Keys.ToList())
			{
				moonVisits[item] = Mathf.Max(moonVisits[item] - 1f, 0f);
				if ((double)moonVisits[item] < 0.1)
				{
					moonVisits.Remove(item);
				}
			}
			Plugin.Instance.Log.LogInfo((object)"Replenished diminishment.");
			Random random = new Random(StartOfRound.Instance.randomMapSeed + 216);
			List<SelectableLevel> list = StartOfRound.Instance.levels.ToList();
			SelectableLevel val = list[random.Next(0, list.Count)];
			if (random.NextDouble() < (double)Plugin.Config.bonusChance.Value && val.levelID != 3 && val.levelID != -1 && val.levelID != 11)
			{
				bonusMoon = val.PlanetName;
				bonusAmount = 1f + (float)random.NextDouble() * (Plugin.Config.maxBonus.Value - 1f);
				moonVisits.Remove(val.PlanetName);
				Plugin.Instance.Log.LogInfo((object)$"{val.PlanetName} selected as bonus moon with bonus of {bonusAmount}");
			}
			else
			{
				bonusMoon = "";
				bonusAmount = 1f;
			}
			UpdateClientTrackers();
		}

		public void SaveMoons()
		{
			try
			{
				string currentSaveFileName = GameNetworkManager.Instance.currentSaveFileName;
				ES3.Save<string[]>("MoonTrackerMoons", moonVisits.Keys.ToArray(), currentSaveFileName);
				ES3.Save<float[]>("MoonTrackerValues", moonVisits.Values.ToArray(), currentSaveFileName);
				ES3.Save<string>("BonusMoon", bonusMoon, currentSaveFileName);
				ES3.Save<float>("BonusAmount", bonusAmount, currentSaveFileName);
				Plugin.Instance.Log.LogInfo((object)"Saved MoonTracker values.");
			}
			catch (Exception arg)
			{
				Plugin.Instance.Log.LogError((object)$"Error while trying to save MoonTracker values: {arg}");
			}
		}

		public void LoadMoons()
		{
			moonVisits = new Dictionary<string, float>();
			bonusMoon = "";
			bonusAmount = 1f;
			try
			{
				string currentSaveFileName = GameNetworkManager.Instance.currentSaveFileName;
				List<string> list = ES3.Load<string[]>("MoonTrackerMoons", currentSaveFileName, Array.Empty<string>()).ToList();
				List<float> list2 = ES3.Load<float[]>("MoonTrackerValues", currentSaveFileName, Array.Empty<float>()).ToList();
				bonusMoon = ES3.Load<string>("BonusMoon", currentSaveFileName, "");
				bonusAmount = ES3.Load<float>("BonusAmount", currentSaveFileName, 1f);
				for (int i = 0; i < list.Count; i++)
				{
					moonVisits[list[i]] = list2[i];
				}
				Plugin.Instance.Log.LogInfo((object)"Successfully loaded MoonTracker data.");
			}
			catch (Exception arg)
			{
				Plugin.Instance.Log.LogError((object)$"Error while trying to load MoonTracker values: {arg}");
			}
		}

		public float GetMoon(SelectableLevel moon)
		{
			if (moon.PlanetName == bonusMoon)
			{
				return (0f - (float)Plugin.Config.restock.Value / Plugin.Config.denominator.Value) * (bonusAmount - 1f);
			}
			if (!moonVisits.ContainsKey(moon.PlanetName))
			{
				return 0f;
			}
			return moonVisits[moon.PlanetName];
		}

		public void ResetMoons()
		{
			moonVisits = new Dictionary<string, float>();
			SaveMoons();
			UpdateClientTrackers();
		}

		public void SetText(string text)
		{
			trackerText = text;
		}

		public string GetText()
		{
			if (!NetworkManager.Singleton.IsHost && !NetworkManager.Singleton.IsServer)
			{
				return trackerText;
			}
			return GenerateText();
		}

		public string GenerateText()
		{
			string text = "";
			if (bonusMoon.Length > 0)
			{
				text += $"\nBonus Scrap Moons:\n      {bonusMoon}: {bonusAmount:P1}\n";
			}
			if (moonVisits.Count > 0)
			{
				text += "\nReduced Scrap Moons:\n";
			}
			foreach (KeyValuePair<string, float> moonVisit in moonVisits)
			{
				text += $"      {moonVisit.Key}: {1f - moonVisit.Value / (float)Plugin.Config.restock.Value * Plugin.Config.denominator.Value:P1}\n";
			}
			if (text.Length != 0)
			{
				return text;
			}
			return "\nNo scrap anomalies detected!\n";
		}

		public void UpdateClientTrackers()
		{
			if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
			{
				NetworkHandler.Instance.TrackerUpdateClientRpc(GenerateText());
			}
		}
	}
}
namespace JackEhttack.patch
{
	internal static class NetworkObjectManager
	{
		private static GameObject networkPrefab;

		[HarmonyPatch(typeof(GameNetworkManager), "Start")]
		[HarmonyPostfix]
		private static void NetworkPatch(GameNetworkManager __instance)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			if (!((Object)(object)networkPrefab != (Object)null))
			{
				networkPrefab = (GameObject)Plugin.Instance.MainAssetBundle.LoadAsset("TrackerNetworkHandler");
				networkPrefab.AddComponent<NetworkHandler>();
				NetworkManager.Singleton.AddNetworkPrefab(networkPrefab);
			}
		}

		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPostfix]
		private static void SpawnNetworkHandler(StartOfRound __instance)
		{
			//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)
			if (NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer)
			{
				Object.Instantiate<GameObject>(networkPrefab, Vector3.zero, Quaternion.identity).GetComponent<NetworkObject>().Spawn(false);
			}
		}
	}
	internal static class ScrapModifierPatches
	{
		private static float oldAmountMultiplier = 1f;

		private static float oldValueMultiplier = 1f;

		[HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")]
		[HarmonyPriority(-100)]
		[HarmonyPrefix]
		private static void ScrapPatch(RoundManager __instance)
		{
			oldAmountMultiplier = __instance.scrapAmountMultiplier;
			oldValueMultiplier = __instance.scrapValueMultiplier;
			float num = 1f - MoonTracker.Instance.GetMoon(__instance.currentLevel) / (float)Plugin.Config.restock.Value * Plugin.Config.denominator.Value;
			__instance.scrapAmountMultiplier *= math.min(2f, num);
			__instance.scrapValueMultiplier += math.max(0f, num - 3f);
			Plugin.Instance.Log.LogInfo((object)("Scrap Amount Modifier: " + __instance.scrapAmountMultiplier + ", Scrap Value Modifier: " + __instance.scrapValueMultiplier));
			Plugin.Instance.Log.LogInfo((object)("Old Scrap Amount Modifier: " + oldAmountMultiplier + ", Scrap Value Modifier: " + oldValueMultiplier));
		}

		[HarmonyPatch(typeof(RoundManager), "SpawnScrapInLevel")]
		[HarmonyPostfix]
		private static void ScrapFix(RoundManager __instance)
		{
			__instance.scrapAmountMultiplier = oldAmountMultiplier;
			__instance.scrapValueMultiplier = oldValueMultiplier;
		}

		[HarmonyPatch(typeof(StartOfRound), "EndOfGame")]
		[HarmonyPostfix]
		private static void ReplenishPatch(StartOfRound __instance)
		{
			MoonTracker.Instance.ReplenishMoons();
			MoonTracker.Instance.DiminishMoon(__instance.currentLevel);
			MoonTracker.Instance.SaveMoons();
		}

		[HarmonyPatch(typeof(StartOfRound), "Start")]
		[HarmonyPostfix]
		private static void StartPatch(StartOfRound __instance)
		{
			if (((NetworkBehaviour)__instance).IsServer || ((NetworkBehaviour)__instance).IsHost)
			{
				MoonTracker.Instance.LoadMoons();
			}
		}

		[HarmonyPatch(typeof(GameNetworkManager), "ResetSavedGameValues")]
		[HarmonyPostfix]
		private static void ResetMoonsPatch(GameNetworkManager __instance)
		{
			MoonTracker.Instance.ResetMoons();
		}

		[HarmonyPatch(typeof(StartOfRound), "OnClientConnect")]
		[HarmonyPostfix]
		private static void UpdateTrackerPatch(StartOfRound __instance)
		{
			MoonTracker.Instance.UpdateClientTrackers();
		}
	}
	internal static class TerminalPatches
	{
		private static List<(TerminalNode, int)> oldMoonPrices = new List<(TerminalNode, int)>();

		private static bool debounce = true;

		private static void addTrackerCommand(Terminal self)
		{
			TerminalNode val = ScriptableObject.CreateInstance<TerminalNode>();
			((Object)val).name = "ShowMoonsDiminish";
			val.displayText = "ScrapTracker 9000 | V0.84 | FitLady CRACK (REPACK)\n____________________________\nAll rights reserved, do not redistribute.\n\nResults from local celestial bodies:\n[moonTracker]\n";
			val.clearPreviousText = true;
			TerminalKeyword val2 = ScriptableObject.CreateInstance<TerminalKeyword>();
			((Object)val2).name = "scrapAmountMoons";
			val2.word = "tracker";
			val2.isVerb = false;
			val2.compatibleNouns = null;
			val2.specialKeywordResult = val;
			val2.defaultVerb = null;
			val2.accessTerminalObjects = false;
			List<TerminalKeyword> list = self.terminalNodes.allKeywords.ToList();
			list.Add(val2);
			self.terminalNodes.allKeywords = list.ToArray();
		}

		public static void UpdatePrices(float discount)
		{
			foreach (var oldMoonPrice in oldMoonPrices)
			{
				oldMoonPrice.Item1.itemCost = (int)((float)oldMoonPrice.Item2 * discount);
			}
		}

		[HarmonyPatch(typeof(Terminal), "Awake")]
		[HarmonyPostfix]
		private static void Terminal_Awake(Terminal __instance)
		{
			if (debounce)
			{
				debounce = false;
				addTrackerCommand(__instance);
				TerminalNode[] array = Resources.FindObjectsOfTypeAll<TerminalNode>();
				Plugin.Instance.Log.LogInfo((object)$"Scanned {array.Length} terminal nodes to potentially discount.");
				TerminalNode[] array2 = array;
				foreach (TerminalNode val in array2)
				{
					if (val.buyRerouteToMoon != -1 && val.itemCost > 0)
					{
						oldMoonPrices.Add((val, val.itemCost));
					}
				}
			}
			((SyncedConfig2<DRConfig>)Plugin.Config).InitialSyncCompleted += delegate
			{
				UpdatePrices(Plugin.Config.moonDiscount.Value);
			};
		}

		[HarmonyPatch(typeof(Terminal), "TextPostProcess")]
		[HarmonyPostfix]
		private static void Terminal_PostProcess(ref string __result)
		{
			__result = __result.Replace("[moonTracker]", MoonTracker.Instance.GetText());
			__result = __result.Replace("Other commands:", "Other commands:\n\n>TRACKER\nScans nearby moons for scrap density.");
		}
	}
}
namespace JackEhttack.netcode
{
	public class NetworkHandler : NetworkBehaviour
	{
		public static NetworkHandler Instance { get; private set; }

		public override void OnNetworkSpawn()
		{
			if ((NetworkManager.Singleton.IsHost || NetworkManager.Singleton.IsServer) & ((Object)(object)Instance != (Object)null))
			{
				NetworkHandler instance = Instance;
				if (instance != null)
				{
					((Component)instance).gameObject.GetComponent<NetworkObject>().Despawn(true);
				}
			}
			Instance = this;
			((NetworkBehaviour)this).OnNetworkSpawn();
		}

		[ClientRpc]
		public void TrackerUpdateClientRpc(string text)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Invalid comparison between Unknown and I4
			//IL_005f: 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_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				ClientRpcParams val = default(ClientRpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendClientRpc(258964929u, val, (RpcDelivery)0);
				bool flag = text != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(text, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val2, 258964929u, val, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 2 && (networkManager.IsClient || networkManager.IsHost))
			{
				MoonTracker.Instance.SetText(text);
			}
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_NetworkHandler()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(258964929u, new RpcReceiveHandler(__rpc_handler_258964929));
		}

		private static void __rpc_handler_258964929(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: 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_0061: 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)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string text = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref text, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((NetworkHandler)(object)target).TrackerUpdateClientRpc(text);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		protected internal override string __getTypeName()
		{
			return "NetworkHandler";
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace DiminishingReturns.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}