Decompiled source of CustomOutsideObjects v1.3.0

CustomOutsideObjects.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CustomOutsideObjects.Patches;
using HarmonyLib;
using LethalLib.Extras;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("Custom Outside Objects")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Custom Outside Objects")]
[assembly: AssemblyCopyright("Copyright Spookybuddy 2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("28f2f16b-6471-4c7e-b0a4-007e3a2450d4")]
[assembly: AssemblyFileVersion("1.3.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.3.0.0")]
namespace CustomOutsideObjects
{
	public class BreakObject : MonoBehaviour
	{
		public List<GameObject> prefabs = new List<GameObject>();

		private void OnTriggerEnter(Collider other)
		{
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: 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_00d3: Unknown result type (might be due to invalid IL or missing references)
			VehicleController val = default(VehicleController);
			if (!((Component)other).TryGetComponent<VehicleController>(ref val) || !(((Vector3)(ref val.averageVelocity)).magnitude > 5f))
			{
				return;
			}
			if (prefabs.Count > 0)
			{
				int num = ((prefabs.Count > 1) ? ((int)(100f * Mathf.Abs(((Component)this).transform.position.y)) % prefabs.Count) : 0);
				if ((Object)(object)prefabs[num] != (Object)null && num < prefabs.Count && num > -1)
				{
					Object.Instantiate<GameObject>(prefabs[num], ((Component)this).transform.parent.position, default(Quaternion), RoundManager.Instance.mapPropsContainer.transform);
				}
				else
				{
					CustomOutsideModBase.mls.LogError((object)$"{num} was either out of range or null!");
				}
			}
			Object.Destroy((Object)(object)((Component)((Component)this).transform.parent).gameObject);
			VehicleController obj = val;
			Vector3 val2 = val.mainRigidbody.position - ((Component)this).transform.position;
			obj.CarReactToObstacle(((Vector3)(ref val2)).normalized, ((Component)this).transform.position, Vector3.zero, (CarObstacleType)2, 1f, (EnemyAI)null, true);
		}
	}
	internal class ConfigControl : SyncedInstance<ConfigControl>
	{
		public struct ObjectConfig
		{
			public ConfigEntry<bool> cfgEnabled;

			public ConfigEntry<string> cfgWhitelist;

			public ConfigEntry<string> cfgTagOverride;

			public bool Enabled
			{
				get
				{
					return cfgEnabled.Value;
				}
				set
				{
					cfgEnabled.Value = value;
				}
			}

			public string Moons
			{
				get
				{
					if (cfgWhitelist == null)
					{
						return (string)((ConfigEntryBase)cfgWhitelist).DefaultValue;
					}
					return cfgWhitelist.Value;
				}
				set
				{
					cfgWhitelist.Value = value;
				}
			}

			public string NewTags
			{
				get
				{
					if (cfgTagOverride == null)
					{
						return (string)((ConfigEntryBase)cfgTagOverride).DefaultValue;
					}
					return cfgTagOverride.Value;
				}
				set
				{
					cfgTagOverride.Value = value;
				}
			}
		}

		public ObjectConfig[] objects;

		private List<string> moons = new List<string>();

		public ConfigControl(ConfigFile cfg)
		{
			InitInstance(this);
			string text = "Base game:\nExperimentation, Assurance, Vow, Offense, March, Adamance, Rend, Dine, Titan, Embrion, Artifice";
			cfg.Bind<string>("-Valid Options", "Valid Moon Names", "", text);
			cfg.Bind<string>("-Valid Options", "Valid Tag Names", "", "Common tags:\nGravel, Grass, Snow, Rock, Concrete, Catwalk, Wood\n\nOther valid tags:\nUntagged, Metal, Carpet, Puddle, Aluminum");
			objects = new ObjectConfig[CustomOutsideModBase.Instance.loadedInjectableOutsideObjects.Count];
			for (int i = 0; i < objects.Length; i++)
			{
				string name = ((Object)CustomOutsideModBase.Instance.loadedInjectableOutsideObjects[i].spawnableObject).name;
				string text2 = string.Join(", ", CustomOutsideModBase.Instance.loadedInjectableOutsideObjects[i].spawnableObject.spawnableFloorTags);
				moons.Clear();
				for (int j = 0; j < CustomOutsideModBase.Instance.loadedInjectableOutsideObjects[i].spawnableObject.spawnableFloorTags.Length; j++)
				{
					switch (CustomOutsideModBase.Instance.loadedInjectableOutsideObjects[i].spawnableObject.spawnableFloorTags[j])
					{
					case "Gravel":
						if (!moons.Contains("Experimentation"))
						{
							moons.Add("Experimentation");
						}
						if (!moons.Contains("Assurance"))
						{
							moons.Add("Assurance");
						}
						if (!moons.Contains("Offense"))
						{
							moons.Add("Offense");
						}
						break;
					case "Grass":
						if (!moons.Contains("Vow"))
						{
							moons.Add("Vow");
						}
						if (!moons.Contains("March"))
						{
							moons.Add("March");
						}
						if (!moons.Contains("Adamance"))
						{
							moons.Add("Adamance");
						}
						if (!moons.Contains("Artifice"))
						{
							moons.Add("Artifice");
						}
						break;
					case "Snow":
						if (!moons.Contains("Rend"))
						{
							moons.Add("Rend");
						}
						if (!moons.Contains("Dine"))
						{
							moons.Add("Dine");
						}
						if (!moons.Contains("Titan"))
						{
							moons.Add("Titan");
						}
						break;
					case "Rock":
						if (!moons.Contains("Adamance"))
						{
							moons.Add("Adamance");
						}
						if (!moons.Contains("Embrion"))
						{
							moons.Add("Embrion");
						}
						break;
					case "Concrete":
						if (!moons.Contains("Experimentation"))
						{
							moons.Add("Experimentation");
						}
						if (!moons.Contains("Vow"))
						{
							moons.Add("Vow");
						}
						if (!moons.Contains("Titan"))
						{
							moons.Add("Titan");
						}
						if (!moons.Contains("Embrion"))
						{
							moons.Add("Embrion");
						}
						if (!moons.Contains("Artifice"))
						{
							moons.Add("Artifice");
						}
						break;
					case "Catwalk":
						if (!moons.Contains("Experimentation"))
						{
							moons.Add("Experimentation");
						}
						if (!moons.Contains("Titan"))
						{
							moons.Add("Titan");
						}
						if (!moons.Contains("Artifice"))
						{
							moons.Add("Artifice");
						}
						break;
					case "Wood":
						if (!moons.Contains("Artifice"))
						{
							moons.Add("Artifice");
						}
						break;
					}
				}
				string text3 = string.Join(", ", moons.ToArray());
				objects[i].cfgEnabled = cfg.Bind<bool>(name, "Enabled", true, name + " can spawn.");
				objects[i].cfgWhitelist = cfg.Bind<string>(name, "Spawn on Moons", text3, "What moons the object can spawn on.\nDefault moons match the Default Tags. Separate moon names with a comma.");
				objects[i].cfgTagOverride = cfg.Bind<string>(name, "Spawn on Tags", text2, "What surfaces the object can spawn on. Separate tags with a comma.");
			}
		}
	}
	[BepInPlugin("CustomOutsideObjects", "CustomOutsideObjects", "1.3.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class CustomOutsideModBase : BaseUnityPlugin
	{
		public const string modGUID = "CustomOutsideObjects";

		private const string modName = "CustomOutsideObjects";

		private const string modVersion = "1.3.0";

		private readonly Harmony harmony = new Harmony("CustomOutsideObjects");

		internal static CustomOutsideModBase Instance;

		internal static ManualLogSource mls;

		internal static ConfigControl Configuration;

		internal static string[] foundOutsideAssetFiles;

		internal static AssetBundle currentAsset;

		internal static SpawnableOutsideObjectDef[] currentAssetObjects;

		internal List<SpawnableOutsideObjectWithRarity> loadedInjectableOutsideObjects = new List<SpawnableOutsideObjectWithRarity>();

		private void Awake()
		{
			if ((Object)(object)Instance == (Object)null)
			{
				Instance = this;
			}
			mls = Logger.CreateLogSource("CustomOutsideObjects");
			string text = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location).ToString();
			string[] array = text.Split(new char[1] { '\\' });
			for (int num = array.Length - 1; num > 0; num--)
			{
				if (array[num].Equals("plugins"))
				{
					for (int i = 0; i < array.Length - num - 1; i++)
					{
						text = Directory.GetParent(text).ToString();
					}
					foundOutsideAssetFiles = Directory.GetFiles(text, "*.coo", SearchOption.AllDirectories);
					break;
				}
			}
			if (foundOutsideAssetFiles != null && foundOutsideAssetFiles.Length != 0)
			{
				for (int j = 0; j < foundOutsideAssetFiles.Length; j++)
				{
					currentAsset = AssetBundle.LoadFromFile(Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), foundOutsideAssetFiles[j]));
					if ((Object)(object)currentAsset != (Object)null)
					{
						currentAssetObjects = currentAsset.LoadAllAssets<SpawnableOutsideObjectDef>();
						if (currentAssetObjects != null && currentAssetObjects.Length != 0)
						{
							GameObject[] array2 = currentAsset.LoadAllAssets<GameObject>();
							for (int k = 0; k < currentAssetObjects.Length; k++)
							{
								if (currentAssetObjects[k].spawnableMapObject != null)
								{
									if (currentAssetObjects[k].spawnableMapObject.spawnableObject.prefabToSpawn.layer.Equals(25))
									{
										if (((Object)currentAssetObjects[k].spawnableMapObject.spawnableObject.prefabToSpawn.transform.GetChild(0)).name.Equals("BreakTrigger"))
										{
											((Component)currentAssetObjects[k].spawnableMapObject.spawnableObject.prefabToSpawn.transform.GetChild(0)).gameObject.AddComponent<TerrainObstacleTrigger>();
											string name = ((Object)currentAssetObjects[k].spawnableMapObject.spawnableObject.prefabToSpawn).name;
											if ((Object)(object)currentAssetObjects[k].spawnableMapObject.spawnableObject.prefabToSpawn.GetComponentInChildren<TerrainObstacleTrigger>() != (Object)null)
											{
												mls.LogInfo((object)("Added generic break trigger script to " + name + "!"));
											}
											else
											{
												mls.LogError((object)("Add generic break to " + name + " failed!"));
											}
										}
										else
										{
											BreakObject breakObject = ((Component)currentAssetObjects[k].spawnableMapObject.spawnableObject.prefabToSpawn.transform.GetChild(0)).gameObject.AddComponent<BreakObject>();
											string name2 = ((Object)currentAssetObjects[k].spawnableMapObject.spawnableObject.prefabToSpawn).name;
											for (int l = 0; l < array2.Length; l++)
											{
												if (((Object)array2[l]).name.Contains(name2) && ((Object)array2[l]).name.Contains("Break"))
												{
													breakObject.prefabs.Add(array2[l]);
												}
											}
											if ((Object)(object)currentAssetObjects[k].spawnableMapObject.spawnableObject.prefabToSpawn.GetComponentInChildren<BreakObject>() != (Object)null)
											{
												mls.LogInfo((object)("Added custom break trigger script to " + name2 + "!"));
											}
											else
											{
												mls.LogError((object)("Add custom break to " + name2 + " failed!"));
											}
										}
									}
									loadedInjectableOutsideObjects.Add(currentAssetObjects[k].spawnableMapObject);
									mls.LogInfo((object)("Custom Outside Object added: " + ((Object)currentAssetObjects[k].spawnableMapObject.spawnableObject).name));
								}
								else
								{
									mls.LogWarning((object)$"Spawnable Rarity {currentAssetObjects[k]} found, but no Spawnable Map Object is attached.");
								}
							}
						}
						else
						{
							mls.LogWarning((object)("No Spawnable Map Object found in " + foundOutsideAssetFiles[j] + ".coo."));
						}
					}
					else
					{
						mls.LogError((object)("Failed to load " + foundOutsideAssetFiles[j] + ".coo."));
					}
				}
				if (loadedInjectableOutsideObjects.Count < 1 || loadedInjectableOutsideObjects == null)
				{
					mls.LogWarning((object)"No Custom Outside Objects were added.");
					return;
				}
				Configuration = new ConfigControl(((BaseUnityPlugin)this).Config);
				mls.LogInfo((object)"Generated Config file for all loaded objects.");
				harmony.PatchAll(typeof(CustomOutsideModBase));
				harmony.PatchAll(typeof(RoundManagerPatch));
				mls.LogInfo((object)"Outside Objects loaded.");
			}
			else
			{
				mls.LogWarning((object)"No Custom Outside Objects were found.");
			}
		}
	}
	[Serializable]
	public class SyncedInstance<T>
	{
		[NonSerialized]
		protected static int IntSize = 4;

		internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager;

		internal static bool IsClient => NetworkManager.Singleton.IsClient;

		internal static bool IsHost => NetworkManager.Singleton.IsHost;

		public static T Default { get; private set; }

		public static T Instance { get; private set; }

		public static bool Synced { get; internal set; }

		protected void InitInstance(T instance)
		{
			Default = instance;
			Instance = instance;
			IntSize = 4;
		}

		internal static void SyncInstance(byte[] data)
		{
			Instance = DeserializeFromBytes(data);
			Synced = true;
		}

		internal static void RevertSync()
		{
			Instance = Default;
			Synced = false;
		}

		public static byte[] SerializeToBytes(T val)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			MemoryStream memoryStream = new MemoryStream();
			try
			{
				binaryFormatter.Serialize(memoryStream, val);
				return memoryStream.ToArray();
			}
			catch (Exception arg)
			{
				CustomOutsideModBase.mls.LogError((object)$"Error serializing instance: {arg}");
				return null;
			}
		}

		public static T DeserializeFromBytes(byte[] data)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			MemoryStream serializationStream = new MemoryStream(data);
			try
			{
				return (T)binaryFormatter.Deserialize(serializationStream);
			}
			catch (Exception arg)
			{
				CustomOutsideModBase.mls.LogError((object)$"Error deserializing instance: {arg}");
				return default(T);
			}
		}

		public static void RequestSync()
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (IsClient)
			{
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(IntSize, (Allocator)2, -1);
				MessageManager.SendNamedMessage("CustomOutsideObjects_OnRequestConfigSync", 0uL, val, (NetworkDelivery)3);
			}
		}

		public static void OnRequestSync(ulong clientId, FastBufferReader _)
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			if (!IsHost)
			{
				return;
			}
			CustomOutsideModBase.mls.LogInfo((object)$"Config sync request received from client: {clientId}");
			byte[] array = SerializeToBytes(Instance);
			int num = array.Length;
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(num + IntSize, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0);
				MessageManager.SendNamedMessage("CustomOutsideObjects_OnReceiveConfigSync", clientId, val, (NetworkDelivery)3);
			}
			catch (Exception arg)
			{
				CustomOutsideModBase.mls.LogInfo((object)$"Error occurred syncing config with client: {clientId}\n{arg}");
			}
		}

		public static void OnReceiveSync(ulong _, FastBufferReader reader)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			if (!((FastBufferReader)(ref reader)).TryBeginRead(IntSize))
			{
				CustomOutsideModBase.mls.LogError((object)"Config sync error: Could not begin reading buffer.");
				return;
			}
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			if (!((FastBufferReader)(ref reader)).TryBeginRead(num))
			{
				CustomOutsideModBase.mls.LogError((object)"Config sync error: Host could not sync.");
				return;
			}
			byte[] data = new byte[num];
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0);
			SyncInstance(data);
			CustomOutsideModBase.mls.LogInfo((object)"Successfully synced config with host.");
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "SteamMatchmaking_OnLobbyMemberJoined")]
		public static void InitializeLocalPlayer()
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			if (IsHost)
			{
				MessageManager.RegisterNamedMessageHandler("CustomOutsideObjects_OnRequestConfigSync", new HandleNamedMessageDelegate(OnRequestSync));
				Synced = true;
			}
			else
			{
				Synced = false;
				MessageManager.RegisterNamedMessageHandler("CustomOutsideObjects_OnReceiveConfigSync", new HandleNamedMessageDelegate(OnReceiveSync));
				RequestSync();
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GameNetworkManager), "StartDisconnect")]
		public static void PlayerLeave()
		{
			SyncedInstance<ConfigControl>.RevertSync();
		}
	}
}
namespace CustomOutsideObjects.Patches
{
	[HarmonyPatch(typeof(RoundManager))]
	internal class RoundManagerPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void ModifyTags()
		{
			for (int i = 0; i < CustomOutsideModBase.Instance.loadedInjectableOutsideObjects.Count; i++)
			{
				CustomOutsideModBase.mls.LogInfo((object)("Updating " + ((Object)CustomOutsideModBase.Instance.loadedInjectableOutsideObjects[i].spawnableObject).name + "'s tags."));
				string[] array = SyncedInstance<ConfigControl>.Instance.objects[i].NewTags.Split(new string[3] { ", ", ",", " " }, StringSplitOptions.RemoveEmptyEntries);
				CustomOutsideModBase.Instance.loadedInjectableOutsideObjects[i].spawnableObject.spawnableFloorTags = new string[array.Length];
				for (int j = 0; j < array.Length; j++)
				{
					CustomOutsideModBase.Instance.loadedInjectableOutsideObjects[i].spawnableObject.spawnableFloorTags[j] = array[j];
				}
			}
		}

		[HarmonyPatch("SpawnOutsideHazards")]
		[HarmonyPrefix]
		private static void OutsideHazardPatch(ref SelectableLevel ___currentLevel)
		{
			string text = ___currentLevel.PlanetName.ToLower().Trim();
			string text2 = ((Object)___currentLevel).name.ToLower().Trim();
			string[] array = text.Split(new char[1] { ' ' });
			string[] array2 = text2.Split(new string[2] { "level", "selectable" }, StringSplitOptions.RemoveEmptyEntries);
			CustomOutsideModBase.mls.LogWarning((object)("Planet " + array2[0] + "."));
			List<SpawnableOutsideObjectWithRarity> list = new List<SpawnableOutsideObjectWithRarity>();
			for (int i = 0; i < CustomOutsideModBase.Instance.loadedInjectableOutsideObjects.Count; i++)
			{
				if (!SyncedInstance<ConfigControl>.Instance.objects[i].Enabled)
				{
					continue;
				}
				string[] array3 = SyncedInstance<ConfigControl>.Instance.objects[i].Moons.Split(new string[3] { ", ", ",", " " }, StringSplitOptions.RemoveEmptyEntries);
				int num = 0;
				while (num < array3.Length)
				{
					if (array3[num].ToLower().Equals(array2[0]))
					{
						goto IL_0151;
					}
					for (int num2 = 0; num2 < array.Length; num2++)
					{
						if (array3[num].ToLower().Equals(array[num2]))
						{
							goto IL_0151;
						}
					}
					num++;
					continue;
					IL_0151:
					if (list.Contains(CustomOutsideModBase.Instance.loadedInjectableOutsideObjects[i]))
					{
						break;
					}
					int num3 = 0;
					while (true)
					{
						if (num3 < ___currentLevel.spawnableOutsideObjects.Length)
						{
							if (((object)___currentLevel.spawnableOutsideObjects[num3]).Equals((object?)CustomOutsideModBase.Instance.loadedInjectableOutsideObjects[i]) || ((Object)___currentLevel.spawnableOutsideObjects[num3].spawnableObject).name.ToLower().Equals(((Object)CustomOutsideModBase.Instance.loadedInjectableOutsideObjects[i].spawnableObject).name.ToLower()))
							{
								break;
							}
							num3++;
							continue;
						}
						list.Add(CustomOutsideModBase.Instance.loadedInjectableOutsideObjects[i]);
						CustomOutsideModBase.mls.LogInfo((object)("Added " + ((Object)CustomOutsideModBase.Instance.loadedInjectableOutsideObjects[i].spawnableObject).name + " as potential spawns."));
						break;
					}
					break;
				}
			}
			SpawnableOutsideObjectWithRarity[] spawnableOutsideObjects = ___currentLevel.spawnableOutsideObjects;
			for (int j = 0; j < spawnableOutsideObjects.Length; j++)
			{
				list.Add(spawnableOutsideObjects[j]);
			}
			___currentLevel.spawnableOutsideObjects = list.ToArray();
			for (int k = 0; k < ___currentLevel.spawnableOutsideObjects.Length; k++)
			{
				CustomOutsideModBase.mls.LogInfo((object)$"#{k}: {((Object)___currentLevel.spawnableOutsideObjects[k].spawnableObject).name}");
			}
		}
	}
}