Decompiled source of CarelessWisp v1.0.1

CarelessWisp.dll

Decompiled 3 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace CarelessWisp;

[BepInPlugin("com.parallel53.carelesswisp", "CarelessWisp", "1.0.1")]
public class CarelessWispPlugin : BaseUnityPlugin
{
	private const string WisplightPrefab = "Demister";

	private const float VanillaPush = 0.08f;

	internal static ConfigEntry<bool> EquipRequired;

	internal static ConfigEntry<bool> UseLevels;

	internal static ConfigEntry<int> MaxLevel;

	internal static ConfigEntry<string> RadiusPerLevel;

	internal static ConfigEntry<string> FogPerLevel;

	internal static ConfigEntry<string> WispsPerLevel;

	internal static ConfigEntry<string> SilverPerLevel;

	internal static ConfigEntry<string> EitrPerLevel;

	internal static ConfigEntry<string> SoftTissuePerLevel;

	internal static ConfigEntry<string> CarapacePerLevel;

	internal static ConfigEntry<bool> FastClear;

	internal static ConfigEntry<float> ClearSeconds;

	internal static ConfigEntry<float> PushStrength;

	internal static ConfigEntry<bool> ThinFog;

	internal static ConfigEntry<float> FogDensity;

	internal static ManualLogSource Log;

	private static readonly FieldRef<SE_Demister, GameObject> BallInstance = AccessTools.FieldRefAccess<SE_Demister, GameObject>("m_ballInstance");

	private static readonly FieldRef<ParticleMist, ParticleSystem> MistParticles = AccessTools.FieldRefAccess<ParticleMist, ParticleSystem>("m_ps");

	private static readonly Dictionary<Requirement, ConfigEntry<string>> upgradeCosts = new Dictionary<Requirement, ConfigEntry<string>>();

	private static Demister wisp;

	private static Vector3 wispRest;

	private static int carriedEffect;

	private static int level = 1;

	private static float wispSeen = -10f;

	private static string logged = "";

	private static float fogBlend;

	private static Particle[] particles = (Particle[])(object)new Particle[0];

	private static int EffectiveLevel
	{
		get
		{
			if (!UseLevels.Value)
			{
				return Mathf.Max(1, MaxLevel.Value);
			}
			return level;
		}
	}

	private static bool WispActive
	{
		get
		{
			if ((Object)(object)wisp != (Object)null)
			{
				return Time.time - wispSeen < 0.5f;
			}
			return false;
		}
	}

	private void Awake()
	{
		//IL_006d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Expected O, but got Unknown
		//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d0: Expected O, but got Unknown
		//IL_0203: Unknown result type (might be due to invalid IL or missing references)
		//IL_020d: Expected O, but got Unknown
		//IL_0260: Unknown result type (might be due to invalid IL or missing references)
		//IL_026a: Expected O, but got Unknown
		//IL_029d: Unknown result type (might be due to invalid IL or missing references)
		Log = ((BaseUnityPlugin)this).Logger;
		EquipRequired = ((BaseUnityPlugin)this).Config.Bind<bool>("Wisp", "EquipRequired", false, "Off by default: a Wisplight anywhere in your inventory gives you its wisp, without using the utility slot, and the best one you carry sets the level. On: only an equipped Wisplight gives a wisp and sets the level.");
		UseLevels = ((BaseUnityPlugin)this).Config.Bind<bool>("Levels", "UseLevels", true, "Your best Wisplight's level picks the radius and fog below. On by default. Turn it off to always use the highest level's values, whatever your Wisplight's level.");
		MaxLevel = ((BaseUnityPlugin)this).Config.Bind<int>("Levels", "MaxLevel", 5, new ConfigDescription("How far the Wisplight can be upgraded. 5 by default; the vanilla Wisplight can't be upgraded. Each level needs a workbench of that level.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 5), Array.Empty<object>()));
		RadiusPerLevel = ((BaseUnityPlugin)this).Config.Bind<string>("Levels", "RadiusPerLevel", "15, 30, 70, 200, 350", "How far around your wisp mist is cleared at each level, in metres, from level 1. 15, 30, 70, 200, 350 by default. 15 is the vanilla Wisplight; 350 is the farthest the game draws mist from you.");
		FogPerLevel = ((BaseUnityPlugin)this).Config.Bind<string>("Levels", "FogPerLevel", "100, 85, 65, 30, 0", "How much of the Mistlands fog is left while your wisp is out, at each level, as a percentage, from level 1. 100, 85, 65, 30, 0 by default. 100 leaves the fog as it is; 0 thins it to FogDensity.");
		WispsPerLevel = ((BaseUnityPlugin)this).Config.Bind<string>("Upgrades", "WispsPerLevel", "5, 10, 15, 30", "Wisps needed to upgrade the Wisplight to level 2, 3, 4 and 5. 5, 10, 15, 30 by default. Later levels use the last number.");
		SilverPerLevel = ((BaseUnityPlugin)this).Config.Bind<string>("Upgrades", "SilverPerLevel", "20, 30, 0, 0", "Silver needed for each upgrade, from level 2. 20, 30, 0, 0 by default, so only the upgrades to levels 2 and 3 need it.");
		EitrPerLevel = ((BaseUnityPlugin)this).Config.Bind<string>("Upgrades", "EitrPerLevel", "0, 0, 20, 0", "Eitr needed for each upgrade, from level 2. 0, 0, 20, 0 by default, so only the upgrade to level 4 needs it.");
		SoftTissuePerLevel = ((BaseUnityPlugin)this).Config.Bind<string>("Upgrades", "SoftTissuePerLevel", "0, 10, 0, 0", "Soft tissue needed for each upgrade, from level 2. 0, 10, 0, 0 by default, so the upgrade to level 3 needs something from the Mistlands.");
		CarapacePerLevel = ((BaseUnityPlugin)this).Config.Bind<string>("Upgrades", "MajesticCarapacePerLevel", "0, 0, 0, 1", "Majestic carapace, the Seeker Queen's drop, needed for each upgrade, from level 2. 0, 0, 0, 1 by default, so level 5 waits until the Queen is beaten. She drops 5, and the artisan press extension needs 1.");
		FastClear = ((BaseUnityPlugin)this).Config.Bind<bool>("Wisp", "FastClear", true, "From level 2, mist inside the radius fades out over ClearSeconds. On by default. Turn it off to let the wisp push mist out instead, at PushStrength.");
		ClearSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Wisp", "ClearSeconds", 1.5f, new ConfigDescription("How long mist inside the radius takes to fade out with FastClear on, in seconds. 1.5 by default; 0 removes it at once. Without FastClear, the game takes up to 5 seconds.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>()));
		PushStrength = ((BaseUnityPlugin)this).Config.Bind<float>("Wisp", "PushStrength", 2f, new ConfigDescription("How hard the wisp pushes mist outward from level 2 when FastClear is off. 2 by default; the vanilla Wisplight pushes at 0.08. Stronger pushes clear faster but throw mist past the edge for a moment.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 20f), Array.Empty<object>()));
		ThinFog = ((BaseUnityPlugin)this).Config.Bind<bool>("Fog", "ThinFog", true, "Lets the Wisplight thin the Mistlands fog, as FogPerLevel sets. On by default. The vanilla Wisplight never changes the fog.");
		FogDensity = ((BaseUnityPlugin)this).Config.Bind<float>("Fog", "FogDensity", 0.003f, new ConfigDescription("The thinnest the Mistlands fog gets. 0.003 by default, the game's clear-weather fog. Mistlands weather uses 0.02 to 0.05.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 0.05f), Array.Empty<object>()));
		MaxLevel.SettingChanged += delegate
		{
			SetUpRecipe(ObjectDB.instance);
		};
		new Harmony("com.parallel53.carelesswisp").PatchAll(typeof(CarelessWispPlugin));
	}

	private void Update()
	{
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null)
		{
			carriedEffect = 0;
			return;
		}
		SEMan sEMan = ((Character)localPlayer).GetSEMan();
		StatusEffect val = BestWisplight(localPlayer, equippedOnly: false)?.m_shared.m_equipStatusEffect;
		if (!EquipRequired.Value && (Object)(object)val != (Object)null)
		{
			if (!sEMan.HaveStatusEffect(val.NameHash()))
			{
				sEMan.AddStatusEffect(val, false, 0, 0f, (short)(-1));
				carriedEffect = val.NameHash();
			}
		}
		else if (carriedEffect != 0)
		{
			if (BestWisplight(localPlayer, equippedOnly: true) == null)
			{
				sEMan.RemoveStatusEffect(carriedEffect, true);
			}
			carriedEffect = 0;
		}
	}

	private void LateUpdate()
	{
		if (WispActive && (Object)(object)Player.m_localPlayer != (Object)null)
		{
			Centre(Player.m_localPlayer);
		}
	}

	private static void Centre(Player player)
	{
		//IL_0036: 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)
		if (!((Object)(object)wisp == (Object)null))
		{
			if (EffectiveLevel >= 2)
			{
				((Component)wisp).transform.position = ((Character)player).GetCenterPoint();
			}
			else
			{
				((Component)wisp).transform.localPosition = wispRest;
			}
		}
	}

	private static ItemData BestWisplight(Player player, bool equippedOnly)
	{
		ItemData val = null;
		foreach (ItemData allItem in ((Humanoid)player).GetInventory().GetAllItems())
		{
			if ((Object)(object)allItem.m_dropPrefab != (Object)null && ((Object)allItem.m_dropPrefab).name == "Demister" && (!equippedOnly || allItem.m_equipped) && (val == null || allItem.m_quality > val.m_quality))
			{
				val = allItem;
			}
		}
		return val;
	}

	private static float ListValue(ConfigEntry<string> entry, int index)
	{
		float result = 0f;
		int num = 0;
		string[] array = entry.Value.Split(',');
		for (int i = 0; i < array.Length; i++)
		{
			if (float.TryParse(array[i].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result2))
			{
				result = result2;
				if (num == index)
				{
					break;
				}
				num++;
			}
		}
		return result;
	}

	[HarmonyPatch(typeof(ObjectDB), "Awake")]
	[HarmonyPostfix]
	private static void AfterObjectDBAwake(ObjectDB __instance)
	{
		SetUpRecipe(__instance);
	}

	[HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")]
	[HarmonyPostfix]
	private static void AfterCopyOtherDB(ObjectDB __instance)
	{
		SetUpRecipe(__instance);
	}

	private static void SetUpRecipe(ObjectDB db)
	{
		if (!((Object)(object)db == (Object)null) && db.m_items != null && db.m_recipes != null)
		{
			GameObject val = db.m_items.Find((GameObject item) => (Object)(object)item != (Object)null && ((Object)item).name == "Demister");
			Recipe val2 = db.m_recipes.Find((Recipe r) => (Object)(object)r != (Object)null && (Object)(object)r.m_item != (Object)null && ((Object)r.m_item).name == "Demister");
			if (!((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null))
			{
				val.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxQuality = Mathf.Max(1, MaxLevel.Value);
				upgradeCosts.Clear();
				Price(db, val2, "Wisp", WispsPerLevel);
				Price(db, val2, "Silver", SilverPerLevel);
				Price(db, val2, "Eitr", EitrPerLevel);
				Price(db, val2, "Softtissue", SoftTissuePerLevel);
				Price(db, val2, "QueenDrop", CarapacePerLevel);
			}
		}
	}

	private static void Price(ObjectDB db, Recipe recipe, string material, ConfigEntry<string> costs)
	{
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: 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_00cc: 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: Expected O, but got Unknown
		Requirement[] resources = recipe.m_resources;
		foreach (Requirement val in resources)
		{
			if ((Object)(object)val.m_resItem != (Object)null && ((Object)val.m_resItem).name == material)
			{
				upgradeCosts[val] = costs;
				return;
			}
		}
		GameObject val2 = db.m_items.Find((GameObject item) => (Object)(object)item != (Object)null && ((Object)item).name == material);
		ItemDrop val3 = (((Object)(object)val2 != (Object)null) ? val2.GetComponent<ItemDrop>() : null);
		if ((Object)(object)val3 == (Object)null)
		{
			Log.LogWarning((object)("Couldn't find " + material + " for the Wisplight upgrades."));
			return;
		}
		Requirement val4 = new Requirement
		{
			m_resItem = val3,
			m_amount = 0,
			m_amountPerLevel = 0,
			m_recover = true
		};
		recipe.m_resources = CollectionExtensions.AddToArray<Requirement>(recipe.m_resources, val4);
		upgradeCosts[val4] = costs;
	}

	[HarmonyPatch(typeof(Requirement), "GetAmount")]
	[HarmonyPostfix]
	private static void AfterGetAmount(Requirement __instance, int qualityLevel, ref int __result)
	{
		if (qualityLevel >= 2 && upgradeCosts.TryGetValue(__instance, out var value))
		{
			__result = Mathf.Max(0, Mathf.RoundToInt(ListValue(value, qualityLevel - 2)));
		}
	}

	[HarmonyPatch(typeof(ItemData), "GetTooltip", new Type[]
	{
		typeof(ItemData),
		typeof(int),
		typeof(bool),
		typeof(float),
		typeof(int),
		typeof(bool)
	})]
	[HarmonyPostfix]
	private static void AfterGetTooltip(ItemData item, int qualityLevel, ref string __result)
	{
		if (item != null && !((Object)(object)item.m_dropPrefab == (Object)null) && !(((Object)item.m_dropPrefab).name != "Demister"))
		{
			int num = Mathf.Max(1, MaxLevel.Value);
			int num2 = (UseLevels.Value ? Mathf.Clamp(qualityLevel, 1, num) : num);
			string text = "\n\nWisp clears mist <color=orange>" + Radius(num2) + " m</color> around you" + FogText(num2);
			if (UseLevels.Value && num2 < num)
			{
				text = text + "\nNext level: " + Radius(num2 + 1) + " m" + FogText(num2 + 1);
			}
			if (!EquipRequired.Value)
			{
				text += "\nWorks from your inventory; no need to equip it.";
			}
			__result += text;
		}
	}

	private static string Radius(int atLevel)
	{
		return Mathf.Max(1f, ListValue(RadiusPerLevel, atLevel - 1)).ToString("0", CultureInfo.InvariantCulture);
	}

	private static string FogText(int atLevel)
	{
		float num = Mathf.Clamp(ListValue(FogPerLevel, atLevel - 1), 0f, 100f);
		if (!ThinFog.Value || num >= 100f)
		{
			return "";
		}
		if (!(num <= 0f))
		{
			return ", " + num.ToString("0", CultureInfo.InvariantCulture) + "% of the Mistlands fog left";
		}
		return ", Mistlands fog thinned to clear weather";
	}

	[HarmonyPatch(typeof(SE_Demister), "UpdateStatusEffect")]
	[HarmonyPostfix]
	private static void AfterWispUpdate(SE_Demister __instance)
	{
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_012e: Unknown result type (might be due to invalid IL or missing references)
		Player localPlayer = Player.m_localPlayer;
		if ((Object)(object)localPlayer == (Object)null || (Object)(object)((StatusEffect)__instance).m_character != (Object)(object)localPlayer)
		{
			return;
		}
		GameObject val = BallInstance.Invoke(__instance);
		if ((Object)(object)val == (Object)null)
		{
			return;
		}
		if ((Object)(object)wisp == (Object)null || !((Component)wisp).transform.IsChildOf(val.transform))
		{
			wisp = val.GetComponentInChildren<Demister>(true);
			if ((Object)(object)wisp != (Object)null)
			{
				wispRest = ((Component)wisp).transform.localPosition;
			}
		}
		if (!((Object)(object)wisp == (Object)null) && !((Object)(object)wisp.m_forceField == (Object)null))
		{
			level = BestWisplight(localPlayer, EquipRequired.Value)?.m_quality ?? 1;
			int effectiveLevel = EffectiveLevel;
			float endRange = Mathf.Max(1f, ListValue(RadiusPerLevel, effectiveLevel - 1));
			wisp.m_forceField.endRange = endRange;
			bool flag = effectiveLevel >= 2 && !FastClear.Value;
			wisp.m_forceField.gravity = MinMaxCurve.op_Implicit(0f - (flag ? PushStrength.Value : 0.08f));
			wispSeen = Time.time;
			Centre(localPlayer);
			string text = "Wisplight level " + effectiveLevel + ": your wisp clears mist " + endRange + " m around it.";
			if (text != logged)
			{
				logged = text;
				Log.LogInfo((object)text);
			}
		}
	}

	[HarmonyPatch(typeof(ParticleMist), "Emit")]
	[HarmonyPrefix]
	private static bool BeforeEmit(ParticleMist __instance, Vector3 center, float radius, Demister pf)
	{
		//IL_001e: 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)
		if ((Object)(object)pf == (Object)null || (Object)(object)pf != (Object)(object)wisp)
		{
			return true;
		}
		float num = Vector3.Distance(((Component)__instance).transform.position, center);
		return radius <= num + __instance.m_maxDistance;
	}

	[HarmonyPatch(typeof(ParticleMist), "Update")]
	[HarmonyPostfix]
	private static void AfterMistUpdate(ParticleMist __instance)
	{
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: Invalid comparison between Unknown and I4
		//IL_009c: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_011b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0120: 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_0125: Unknown result type (might be due to invalid IL or missing references)
		//IL_0127: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0162: 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)
		//IL_0189: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
		if (!FastClear.Value || !WispActive || EffectiveLevel < 2)
		{
			return;
		}
		ParticleSystem val = MistParticles.Invoke(__instance);
		if ((Object)(object)val == (Object)null || val.particleCount == 0)
		{
			return;
		}
		int num = particles.Length;
		MainModule main = val.main;
		if (num < ((MainModule)(ref main)).maxParticles)
		{
			main = val.main;
			particles = (Particle[])(object)new Particle[((MainModule)(ref main)).maxParticles];
		}
		int num2 = val.GetParticles(particles);
		main = val.main;
		bool flag = (int)((MainModule)(ref main)).simulationSpace == 0;
		Transform transform = ((Component)val).transform;
		Vector3 position = ((Component)wisp).transform.position;
		float endRange = wisp.m_forceField.endRange;
		float num3 = endRange * endRange;
		bool flag2 = false;
		float value = ClearSeconds.Value;
		int num4 = ((value <= 0f) ? 255 : Mathf.Max(1, Mathf.CeilToInt(255f * Time.deltaTime / value)));
		for (int i = 0; i < num2; i++)
		{
			Vector3 val2 = (flag ? transform.TransformPoint(((Particle)(ref particles[i])).position) : ((Particle)(ref particles[i])).position) - position;
			if (!(((Vector3)(ref val2)).sqrMagnitude >= num3) && !(((Particle)(ref particles[i])).remainingLifetime <= 0f))
			{
				Color32 startColor = ((Particle)(ref particles[i])).startColor;
				if (startColor.a <= num4)
				{
					((Particle)(ref particles[i])).remainingLifetime = 0f;
				}
				else
				{
					startColor.a = (byte)(startColor.a - num4);
					((Particle)(ref particles[i])).startColor = startColor;
				}
				flag2 = true;
			}
		}
		if (flag2)
		{
			val.SetParticles(particles, num2);
		}
	}

	[HarmonyPatch(typeof(EnvMan), "SetEnv")]
	[HarmonyPostfix]
	private static void AfterSetEnv(EnvMan __instance, float dt)
	{
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Invalid comparison between Unknown and I4
		float num = Mathf.Clamp(ListValue(FogPerLevel, EffectiveLevel - 1), 0f, 100f) / 100f;
		bool flag = ThinFog.Value && WispActive && num < 1f && (int)__instance.GetCurrentBiome() == 512;
		fogBlend = Mathf.MoveTowards(fogBlend, flag ? 1f : 0f, dt);
		if (!(fogBlend <= 0f))
		{
			float fogDensity = RenderSettings.fogDensity;
			float num2 = Mathf.Min(fogDensity, Mathf.Max(fogDensity * num, FogDensity.Value));
			RenderSettings.fogDensity = Mathf.Lerp(fogDensity, num2, fogBlend);
		}
	}
}