Decompiled source of RandomEncounters v1.1.3

RandomEncounters\RandomEncounters.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
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("RandomEncounters")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RandomEncounters")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("06b0b4cd-89d7-4ff2-8dc9-3eaa535b8d99")]
[assembly: AssemblyFileVersion("1.1.3.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.1.3.0")]
namespace RandomEncounters;

internal class SeaLifeMod
{
	public class FinWhaleAIPatches
	{
		[HarmonyPrefix]
		public static bool CheckDistanceToPlayerPatch()
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < EncounterGenerator.whaleSpawns.Count; i++)
			{
				if (Vector3.Distance(EncounterGenerator.whaleSpawns[i].position, ((Component)Refs.observerMirror).transform.position) > 650f)
				{
					Plugin.logger.LogDebug((object)("Destroying " + ((Object)EncounterGenerator.whaleSpawns[i]).name));
					Object.Destroy((Object)(object)((Component)EncounterGenerator.whaleSpawns[i]).gameObject);
					EncounterGenerator.whaleSpawns.Remove(EncounterGenerator.whaleSpawns[i]);
				}
			}
			return false;
		}
	}

	public static FastInvokeHandler spawnWhale;

	public static FastInvokeHandler triggerRandomAnimation;

	public static void PatchMod()
	{
		//IL_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_0112: Expected O, but got Unknown
		((MonoBehaviour)Plugin.seaLifeModInstance).StopAllCoroutines();
		Type type2 = (from type in AppDomain.CurrentDomain.GetAssemblies().SelectMany((Assembly asm) => asm.GetTypes())
			where type.IsClass && type.Name == "SeaLifePlugin"
			select type).Single();
		MethodInfo methodInfo = AccessTools.Method(type2, "SpawnWhale", (Type[])null, (Type[])null);
		spawnWhale = MethodInvoker.GetHandler(methodInfo, false);
		Type type3 = (from type in AppDomain.CurrentDomain.GetAssemblies().SelectMany((Assembly asm) => asm.GetTypes())
			where type.IsClass && type.Name == "FinWhaleAI"
			select type).Single();
		MethodInfo methodInfo2 = AccessTools.Method(type3, "CheckDistanceToPlayer", (Type[])null, (Type[])null);
		MethodInfo methodInfo3 = AccessTools.Method(typeof(FinWhaleAIPatches), "CheckDistanceToPlayerPatch", (Type[])null, (Type[])null);
		Plugin.harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(methodInfo3), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		MethodInfo methodInfo4 = AccessTools.Method(type3, "TriggerRandomAnimation", (Type[])null, (Type[])null);
		triggerRandomAnimation = MethodInvoker.GetHandler(methodInfo4, false);
	}
}
internal class EncounterGenerator : MonoBehaviour
{
	public static EncounterGenerator instance;

	public static List<Transform> whaleSpawns;

	public void Awake()
	{
		instance = this;
		whaleSpawns = new List<Transform>();
		((MonoBehaviour)this).StartCoroutine(GenerateEncounters());
	}

	private IEnumerator GenerateEncounters()
	{
		while (true)
		{
			yield return (object)new WaitForSeconds((float)Random.Range(Plugin.generateEncounterMinTime.Value, Plugin.generateEncounterMinTime.Value + 300));
			if ((Object)(object)GameState.currentBoat != (Object)null)
			{
				Generate();
			}
		}
	}

	internal void Generate()
	{
		Plugin.logger.LogDebug((object)$"Distance to land {GameState.distanceToLand}");
		if (!GameState.playing || GameState.sleeping || !(GameState.distanceToLand > 1000f))
		{
			return;
		}
		int num = Random.Range(1, 100);
		Plugin.logger.LogDebug((object)$"Roll: {num}");
		int num2 = num;
		int num3 = num2;
		if (num3 <= 10)
		{
			GenerateFlotsam();
			return;
		}
		int num4 = num3;
		if (num4 > 10 && num4 <= 15)
		{
			GenerateFlotsam();
			((MonoBehaviour)this).StartCoroutine(GenerateWhale());
			return;
		}
		int num5 = num3;
		if (num5 > 15 && num5 <= 40)
		{
			((MonoBehaviour)this).StartCoroutine(GenerateWhale());
			return;
		}
		int num6 = num3;
		if (num6 > 40 && num6 <= 45)
		{
			((MonoBehaviour)this).StartCoroutine(GenerateDenseFog());
		}
	}

	internal static void GenerateFlotsam()
	{
		//IL_0006: 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)
		//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)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		Vector3 spawnPoint = GameState.currentBoat.position + GameState.currentBoat.right * 100f + GameState.currentBoat.forward * (float)Random.Range(-30, 30);
		Flotsam.Spawn(spawnPoint);
	}

	internal IEnumerator GenerateWhale()
	{
		if (Plugin.controlSeaLifeMod.Value && (Object)(object)Plugin.seaLifeModInstance != (Object)null)
		{
			for (int i = 0; i < Random.Range(1, 3); i++)
			{
				Vector3 seaLifespawnPoint = GameState.currentBoat.position + new Vector3((float)Random.Range(-200, 200), -8f, (float)Random.Range(-200, 200));
				SeaLifeMod.spawnWhale.Invoke((object)Plugin.seaLifeModInstance, new object[1] { seaLifespawnPoint });
				yield return (object)new WaitForSeconds(0.5f);
			}
			yield return (object)new WaitForSeconds(2f);
			whaleSpawns = (from t in ((Component)Refs.shiftingWorld).GetComponentsInChildren<Transform>()
				where ((Object)t).name == "FinWhalePrefab(Clone)"
				select t).ToList();
			Transform whaleTransform = whaleSpawns.FirstOrDefault();
			Component finWhaleAI = ((Component)whaleTransform).gameObject.GetComponent("FinWhaleAI");
			SeaLifeMod.triggerRandomAnimation.Invoke((object)finWhaleAI, Array.Empty<object>());
		}
	}

	internal IEnumerator GenerateDenseFog()
	{
		if (!DenseFog.running && !(Traverse.Create((object)WeatherStorms.instance).Method("GetNormalizedDistance", Array.Empty<object>()).GetValue<float>() < 0.5f))
		{
			DenseFog.Spawn();
			yield return (object)new WaitForSeconds(23f);
			for (int i = 0; i < 4; i++)
			{
				Vector3 spawnPoint = GameState.currentBoat.position + GameState.currentBoat.right * (200f + Random.Range(20f, 60f) * (float)i) + GameState.currentBoat.forward * (float)Random.Range(-200, 200);
				Flotsam.SpawnItem(spawnPoint, AssetLoader.hull, 1f, wreckage: true);
				yield return (object)new WaitForSeconds(1f);
				Flotsam.SpawnItem(spawnPoint, AssetLoader.mast, 1f, wreckage: true);
				yield return (object)new WaitForSeconds(1f);
				Flotsam.SpawnItem(spawnPoint, AssetLoader.bowsprit, 1f, wreckage: true);
				yield return (object)new WaitForSeconds(1f);
			}
			yield return (object)new WaitForSeconds((float)Plugin.fogDuration.Value);
			DenseFog.ClearFog();
		}
	}
}
internal class DenseFog
{
	[HarmonyPatch(typeof(OceanColorBlender))]
	private class OceanColorBlenderPatches
	{
		[HarmonyPrefix]
		[HarmonyPatch("ApplyPalette")]
		public static void ApplyFogDensity(ref OceanColorPalette palette)
		{
			if (running)
			{
				originalFogDensity = ((originalFogDensity == 0f) ? palette.fogDensity : originalFogDensity);
				currentFogDensity = ((currentFogDensity == 0f) ? palette.fogDensity : currentFogDensity);
				if (clearFog && currentFogDensity > originalFogDensity)
				{
					currentFogDensity -= 1E-05f;
				}
				if (!clearFog && currentFogDensity < fogDensityMax)
				{
					currentFogDensity += 1E-05f;
				}
				palette.fogDensity = currentFogDensity;
				if (clearFog && currentFogDensity <= originalFogDensity)
				{
					running = false;
					currentFogDensity = 0f;
					originalFogDensity = 0f;
					Traverse.Create((object)GameObject.Find("wind").GetComponent<Wind>()).Field("timer").SetValue((object)0);
				}
			}
		}
	}

	[HarmonyPatch(typeof(Wind))]
	private class WindPatches
	{
		[HarmonyPrefix]
		[HarmonyPatch("SetNewGustTarget")]
		public static bool NoGust(ref Vector3 ___currentGustTarget, Vector3 ___currentWindTarget)
		{
			//IL_0012: 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 (!running)
			{
				return true;
			}
			___currentGustTarget = ___currentWindTarget;
			return false;
		}

		[HarmonyPrefix]
		[HarmonyPatch("SetNewWindTarget")]
		public static bool LightWind(ref Vector3 ___currentWindTarget)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			if (!running)
			{
				return true;
			}
			___currentWindTarget = ((Vector3)(ref Wind.currentBaseWind)).normalized * 3f;
			return false;
		}
	}

	[HarmonyPatch(typeof(WaveSound))]
	private class WaveSoundPatches
	{
		[HarmonyPrefix]
		[HarmonyPatch("UpdateIntensity")]
		public static bool SetToMinVolume(ref float ___audioVolume, float ___minVolume)
		{
			if (!running)
			{
				return true;
			}
			___audioVolume = ___minVolume;
			return false;
		}
	}

	[HarmonyPatch(typeof(WindSound))]
	private class WindSoundPatches
	{
		[HarmonyPrefix]
		[HarmonyPatch("Update")]
		public static bool SetToMinVolume(ref AudioSource ___audio)
		{
			if (!running)
			{
				return true;
			}
			___audio.volume = 0.0001f;
			return false;
		}
	}

	internal static bool running = false;

	private static bool clearFog = true;

	private static readonly float fogDensityMax = 0.06f;

	private static float currentFogDensity = 0f;

	private static float originalFogDensity = 0f;

	public static void Spawn()
	{
		Plugin.logger.LogDebug((object)"Spawning fog");
		clearFog = false;
		running = true;
	}

	public static void ClearFog()
	{
		Plugin.logger.LogDebug((object)"Clearing fog");
		clearFog = true;
	}
}
internal class Flotsam
{
	private static readonly int[] cargos = new int[22]
	{
		1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
		11, 13, 14, 15, 16, 17, 18, 19, 24, 25,
		26, 27
	};

	private static readonly int[] consumables = new int[4] { 104, 108, 131, 132 };

	private static readonly int[] bottles = new int[5] { 55, 56, 57, 58, 59 };

	private static readonly int[] tobaccos = new int[4] { 311, 313, 315, 319 };

	public static void Spawn(Vector3 spawnPoint)
	{
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_0141: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_024f: Unknown result type (might be due to invalid IL or missing references)
		//IL_025b: Unknown result type (might be due to invalid IL or missing references)
		//IL_026d: Unknown result type (might be due to invalid IL or missing references)
		//IL_027f: Unknown result type (might be due to invalid IL or missing references)
		int num = 4;
		int num2 = 3;
		int num3 = 2;
		for (int i = 0; i < Random.Range(1, num); i++)
		{
			int num4 = Random.Range(0, cargos.Length - 1);
			for (int j = 0; j < Random.Range(1, num2); j++)
			{
				Plugin.logger.LogDebug((object)$"Choice: {cargos[num4]}");
				GameObject val = PrefabsDirectory.instance.directory[cargos[num4]];
				float amount = (float)Math.Round((decimal)Random.Range(0f, val.GetComponent<ShipItem>().amount));
				SpawnItem(spawnPoint, val, amount);
			}
		}
		for (int k = 0; k < Random.Range(1, num3); k++)
		{
			int num5 = Random.Range(0, consumables.Length - 1);
			Plugin.logger.LogDebug((object)$"Choice: {consumables[num5]}");
			GameObject val2 = PrefabsDirectory.instance.directory[consumables[num5]];
			float amount2 = (float)Math.Round((decimal)Random.Range(0f, val2.GetComponent<ShipItem>().amount));
			SpawnItem(spawnPoint, val2, amount2);
		}
		for (int l = 0; l < Random.Range(5, 10); l++)
		{
			int num6 = Random.Range(0, bottles.Length - 1);
			Plugin.logger.LogDebug((object)$"Choice: {bottles[num6]}");
			GameObject prefabGO = PrefabsDirectory.instance.directory[bottles[num6]];
			float amount3 = 0f;
			SpawnItem(spawnPoint, prefabGO, amount3);
		}
		int num7 = Random.Range(0, tobaccos.Length - 1);
		Plugin.logger.LogDebug((object)$"Choice: {tobaccos[num7]}");
		GameObject val3 = PrefabsDirectory.instance.directory[tobaccos[num7]];
		float amount4 = (float)Math.Round((decimal)Random.Range(0f, val3.GetComponent<ShipItem>().amount));
		SpawnItem(spawnPoint, val3, amount4);
		SpawnItem(spawnPoint, AssetLoader.hull, 1f, wreckage: true);
		SpawnItem(spawnPoint, AssetLoader.mast, 1f, wreckage: true);
		SpawnItem(spawnPoint, AssetLoader.bowsprit, 1f, wreckage: true);
	}

	public static void SpawnItem(Vector3 spawnPoint, GameObject prefabGO, float amount, bool wreckage = false)
	{
		//IL_0002: 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)
		GameObject val = Object.Instantiate<GameObject>(prefabGO, spawnPoint, Quaternion.Euler((float)Random.Range(0, 360), (float)Random.Range(0, 360), (float)Random.Range(0, 360)));
		val.GetComponent<ShipItem>().sold = true;
		val.GetComponent<SaveablePrefab>().RegisterToSave();
		if (Object.op_Implicit((Object)(object)val.GetComponent<Good>()))
		{
			val.GetComponent<Good>().RegisterAsMissionless();
		}
		val.GetComponent<ShipItem>().amount = amount;
		val.GetComponent<ShipItem>().health = amount;
		if (wreckage)
		{
			((GoPointerButton)val.GetComponent<ShipItem>()).unclickable = true;
			val.transform.parent = Refs.shiftingWorld;
		}
		Plugin.logger.LogDebug((object)("Prefab " + ((Object)prefabGO).name + " spawned"));
	}
}
[BepInPlugin("com.raddude82.randomencounters", "RandomEncounters", "1.1.3")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class Plugin : BaseUnityPlugin
{
	public const string PLUGIN_GUID = "com.raddude82.randomencounters";

	public const string PLUGIN_NAME = "RandomEncounters";

	public const string PLUGIN_VERSION = "1.1.3";

	public const string SEALIFEMOD_GUID = "com.yourname.sailwind.sealifeplugin";

	internal static BaseUnityPlugin seaLifeModInstance;

	internal static Plugin instance;

	internal static ManualLogSource logger;

	internal static Harmony harmony;

	internal static ConfigEntry<bool> controlSeaLifeMod;

	internal static ConfigEntry<int> generateEncounterMinTime;

	internal static ConfigEntry<int> fogDuration;

	private void Awake()
	{
		instance = this;
		logger = ((BaseUnityPlugin)this).Logger;
		harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "com.raddude82.randomencounters");
		generateEncounterMinTime = ((BaseUnityPlugin)this).Config.Bind<int>("Settings", "Minimum encounter generation time", 900, "Minimum time in seconds to get a chance roll for an encounter, the encounter time range max is 5 minutes added to this.");
		generateEncounterMinTime = ((BaseUnityPlugin)this).Config.Bind<int>("Settings", "Fog encounter duration", 480, "In seconds, the amount of time the fog encounter lasts.");
		controlSeaLifeMod = ((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "Control SeaLifeMod spawns", true, "Use this mod to control SeaLifeMod spawns.");
		foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
		{
			BepInPlugin metadata = pluginInfo.Value.Metadata;
			if (controlSeaLifeMod.Value && metadata.GUID.Equals("com.yourname.sailwind.sealifeplugin"))
			{
				logger.LogInfo((object)"com.yourname.sailwind.sealifeplugin found");
				seaLifeModInstance = pluginInfo.Value.Instance;
				SeaLifeMod.PatchMod();
			}
		}
		AssetLoader.LoadFlotsam();
		((Component)this).gameObject.AddComponent<EncounterGenerator>();
	}
}
internal class AssetLoader
{
	internal static GameObject hull;

	internal static GameObject mast;

	internal static GameObject bowsprit;

	internal static void LoadFlotsam()
	{
		string path = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)Plugin.instance).Info.Location), "Assets", "wreckage_bundle");
		AssetBundle val = LoadAssetBundle(path);
		hull = val.LoadAsset<GameObject>("hull");
		mast = val.LoadAsset<GameObject>("mast");
		bowsprit = val.LoadAsset<GameObject>("bowsprit");
	}

	public static AssetBundle LoadAssetBundle(string path)
	{
		AssetBundle val = AssetBundle.LoadFromFile(path);
		if ((Object)(object)val == (Object)null)
		{
			Plugin.logger.LogError((object)("Failed to load " + path));
			return null;
		}
		return val;
	}
}