Decompiled source of Helldiver Minions v1.0.0

Helldiver_Minions.dll

Decompiled a day 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.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using MonoMod.RuntimeDetour.HookGen;
using RoR2;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace Helldiver_Minions;

[BepInPlugin("com.KrononConpsirator.Helldiver_Minions", "Helldiver_Minions", "1.0.0")]
public class Helldiver_MinionsPlugin : BaseUnityPlugin
{
	public class SkinAddedArgs : EventArgs
	{
		public SkinDef skinDef { get; }

		public GameObject bodyPrefab { get; }

		public SkinAddedArgs(SkinDef newSkinDef, GameObject newGameObject)
		{
			skinDef = newSkinDef;
			bodyPrefab = newGameObject;
		}
	}

	public class MinionSkinDefInjector
	{
		public static class SkinFinder
		{
			public static SkinDef FindSkin(string bodyname, int skinindex)
			{
				GameObject val = BodyCatalog.FindBodyPrefab(bodyname);
				if (!Object.op_Implicit((Object)(object)val))
				{
					return null;
				}
				ModelLocator component = val.GetComponent<ModelLocator>();
				Transform val2 = ((component != null) ? component.modelTransform : null);
				if (!Object.op_Implicit((Object)(object)val2))
				{
					return null;
				}
				SkinDef[] array = ((Component)val2).GetComponent<ModelSkinController>()?.skins;
				if (array == null || skinindex < 0 || skinindex >= array.Length)
				{
					return null;
				}
				return array[skinindex];
			}

			public static SkinDefParams FindSkinParams(string bodyname, int skinindex)
			{
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_0046: Unknown result type (might be due to invalid IL or missing references)
				SkinDef val = FindSkin(bodyname, skinindex);
				if (!Object.op_Implicit((Object)(object)val))
				{
					return null;
				}
				if (Object.op_Implicit((Object)(object)val.skinDefParams))
				{
					return val.skinDefParams;
				}
				AssetReferenceT<SkinDefParams> skinDefParamsAddress = val.skinDefParamsAddress;
				if (skinDefParamsAddress == null || !((AssetReference)skinDefParamsAddress).RuntimeKeyIsValid())
				{
					return null;
				}
				val.skinDefParams = Addressables.LoadAssetAsync<SkinDefParams>(((AssetReference)skinDefParamsAddress).RuntimeKey).WaitForCompletion();
				return val.skinDefParams;
			}

			public static void AddMinionReplacement(string bodyname, int skinindex, string minionBodyName, SkinDef minionSkin)
			{
				//IL_005d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				SkinDefParams val = FindSkinParams(bodyname, skinindex);
				GameObject minionBody = BodyCatalog.FindBodyPrefab(minionBodyName);
				if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)minionBody) && Object.op_Implicit((Object)(object)minionSkin))
				{
					MinionSkinReplacement[] source = val.minionSkinReplacements ?? Array.Empty<MinionSkinReplacement>();
					val.minionSkinReplacements = source.Where((MinionSkinReplacement r) => (Object)(object)r.minionBodyPrefab != (Object)(object)minionBody).Append(new MinionSkinReplacement
					{
						minionBodyPrefab = minionBody,
						minionSkin = minionSkin
					}).ToArray();
				}
			}
		}

		internal void BeforeBodyCatalogInit()
		{
			BeetleGuardBodyTermanid_BGuardSkinDefSkinAddedEvent += delegate(object sender, SkinAddedArgs args)
			{
				BeetleGuardDefSkin = args.skinDef;
			};
		}

		internal void AfterBodyCatalogInit()
		{
			SkinFinder.AddMinionReplacement("HelldiversBody", 0, "BeetleGuardAllyBody", BeetleGuardDefSkin);
			SkinFinder.AddMinionReplacement("HelldiversBody", 1, "BeetleGuardAllyBody", BeetleGuardDefSkin);
			SkinFinder.AddMinionReplacement("HelldiversBody", 2, "BeetleGuardAllyBody", BeetleGuardDefSkin);
			SkinFinder.AddMinionReplacement("HelldiversBody", 3, "BeetleGuardAllyBody", BeetleGuardDefSkin);
			SkinFinder.AddMinionReplacement("HelldiversBody", 4, "BeetleGuardAllyBody", BeetleGuardDefSkin);
			SkinFinder.AddMinionReplacement("HelldiversBody", 5, "BeetleGuardAllyBody", BeetleGuardDefSkin);
			SkinFinder.AddMinionReplacement("HelldiversBody", 6, "BeetleGuardAllyBody", BeetleGuardDefSkin);
		}
	}

	public static AssetBundle assetBundle;

	private static readonly List<Material> materialsWithRoRShader = new List<Material>();

	private static MinionSkinDefInjector _MinionSkinDefInjector = new MinionSkinDefInjector();

	public static SkinDef BeetleGuardDefSkin;

	internal static Helldiver_MinionsPlugin Instance { get; private set; }

	internal static ManualLogSource InstanceLogger
	{
		get
		{
			Helldiver_MinionsPlugin instance = Instance;
			if (instance == null)
			{
				return null;
			}
			return ((BaseUnityPlugin)instance).Logger;
		}
	}

	private static event EventHandler<SkinAddedArgs> BeetleGuardBodyTermanid_BGuardSkinDefSkinAddedEvent;

	private void Start()
	{
		Instance = this;
		BeforeStart();
		using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Helldiver_Minions.krononconpsiratorhelldiver_minions"))
		{
			assetBundle = AssetBundle.LoadFromStream(stream);
		}
		((ResourceAvailability)(ref BodyCatalog.availability)).CallWhenAvailable((Action)BodyCatalogInit);
		HookEndpointManager.Add((MethodBase)typeof(Language).GetMethod("LoadStrings"), (Delegate)new Action<Action<Language>, Language>(LanguageLoadStrings));
		ReplaceShaders();
		AfterStart();
	}

	private void BeforeStart()
	{
	}

	private void AfterStart()
	{
	}

	private static void BeforeBodyCatalogInit()
	{
		try
		{
			_MinionSkinDefInjector.BeforeBodyCatalogInit();
		}
		catch (Exception ex)
		{
			ManualLogSource instanceLogger = InstanceLogger;
			if (instanceLogger != null)
			{
				instanceLogger.LogError((object)("MaterialDuplicator AfterBodyCatalogInit failed: " + ex));
			}
		}
	}

	private static void AfterBodyCatalogInit()
	{
		try
		{
			_MinionSkinDefInjector.AfterBodyCatalogInit();
		}
		catch (Exception ex)
		{
			ManualLogSource instanceLogger = InstanceLogger;
			if (instanceLogger != null)
			{
				instanceLogger.LogError((object)("MaterialDuplicator AfterBodyCatalogInit failed: " + ex));
			}
		}
	}

	private static void ReplaceShaders()
	{
		LoadMaterialsWithReplacedShader("RoR2/Base/Shaders/HGStandard.shader", "Assets/Skins/SkinAsset/Vanilla/Enemy_BeetleGuard/Helldiver_Termanid/Helldiver_BGuard_Termanid_Mat.mat");
	}

	private static void LoadMaterialsWithReplacedShader(string shaderPath, params string[] materialPaths)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		Shader shader = Addressables.LoadAssetAsync<Shader>((object)shaderPath).WaitForCompletion();
		foreach (string text in materialPaths)
		{
			Material val = assetBundle.LoadAsset<Material>(text);
			val.shader = shader;
			materialsWithRoRShader.Add(val);
		}
	}

	private static void LanguageLoadStrings(Action<Language> orig, Language self)
	{
		orig(self);
		self.SetStringByToken("KRONONCONPSIRATOR_SKIN_TERMANID_BGUARDSKINDEF_NAME", "Termanid");
	}

	private static void BodyCatalogInit()
	{
		BeforeBodyCatalogInit();
		AddBeetleGuardAllyBodyTermanid_BGuardSkinDefSkin();
		AfterBodyCatalogInit();
	}

	private static void BeetleGuardAllyBodyTermanid_BGuardSkinDefSkinAdded(SkinDef skinDef, GameObject bodyPrefab)
	{
		Helldiver_MinionsPlugin.BeetleGuardBodyTermanid_BGuardSkinDefSkinAddedEvent?.Invoke(Instance, new SkinAddedArgs(skinDef, bodyPrefab));
	}

	private static SkinDef CreateBeetleGuardAllyBodyTermanid_BGuardSkinDefSkin(GameObject mdl, ModelSkinController skinController)
	{
		Renderer[] renderers = mdl.GetComponentsInChildren<Renderer>(true);
		mdl.GetComponentsInChildren<Light>(true);
		SkinDef skin = ScriptableObject.CreateInstance<SkinDef>();
		SkinDefParams skinParams = ScriptableObject.CreateInstance<SkinDefParams>();
		skin.skinDefParams = skinParams;
		((Object)skin).name = "Termanid_BGuardSkinDef";
		skin.nameToken = "KRONONCONPSIRATOR_SKIN_TERMANID_BGUARDSKINDEF_NAME";
		skin.rootObject = mdl;
		Helpers.TryCatchThrow("Icon", delegate
		{
			skin.icon = assetBundle.LoadAsset<Sprite>("Assets\\SkinMods\\Helldiver_Minions\\Icons\\Termanid_BGuardSkinDefIcon.png");
		});
		Helpers.TryCatchThrow("Unlockable Name", delegate
		{
			skin.unlockableDef = null;
		});
		Helpers.TryCatchThrow("Base Skins", delegate
		{
			skin.baseSkins = (SkinDef[])(object)new SkinDef[1] { Helpers.ThrowIfOutOfBounds(0, "Index 0 is out of bounds of skins array", skinController.skins, 0) };
		});
		Helpers.TryCatchThrow("Game Object Activations", delegate
		{
			skinParams.gameObjectActivations = Array.Empty<GameObjectActivation>();
		});
		Helpers.TryCatchThrow("Renderer Infos", delegate
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: 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_0089: Unknown result type (might be due to invalid IL or missing references)
			skinParams.rendererInfos = (RendererInfo[])(object)new RendererInfo[1]
			{
				new RendererInfo
				{
					defaultMaterial = assetBundle.LoadAsset<Material>("Assets/Skins/SkinAsset/Vanilla/Enemy_BeetleGuard/Helldiver_Termanid/Helldiver_BGuard_Termanid_Mat.mat"),
					defaultShadowCastingMode = (ShadowCastingMode)1,
					ignoreOverlays = false,
					renderer = Helpers.ThrowIfNull<Renderer>(0, "There is no renderer with the name \"BeetleGuardMesh\"", ((IEnumerable<Renderer>)renderers).FirstOrDefault((Func<Renderer, bool>)((Renderer r) => ((Object)r).name == "BeetleGuardMesh"))),
					hideOnDeath = false,
					ignoresMaterialOverrides = false
				}
			};
		});
		Helpers.TryCatchThrow("MeshReplacements", delegate
		{
			//IL_0010: 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_0069: Unknown result type (might be due to invalid IL or missing references)
			skinParams.meshReplacements = (MeshReplacement[])(object)new MeshReplacement[1]
			{
				new MeshReplacement
				{
					mesh = assetBundle.LoadAsset<Mesh>("Assets\\SkinMods\\Helldiver_Minions\\Meshes\\TermanidMesh.mesh"),
					renderer = Helpers.ThrowIfNull<Renderer>(0, "There is no renderer with the name \"BeetleGuardMesh\"", ((IEnumerable<Renderer>)renderers).FirstOrDefault((Func<Renderer, bool>)((Renderer r) => ((Object)r).name == "BeetleGuardMesh")))
				}
			};
		});
		Helpers.TryCatchThrow("Light Infos", delegate
		{
			skinParams.lightReplacements = Array.Empty<LightInfo>();
		});
		Helpers.TryCatchThrow("Minion Skin Replacements", delegate
		{
			skinParams.minionSkinReplacements = Array.Empty<MinionSkinReplacement>();
		});
		Helpers.TryCatchThrow("Projectile Ghost Replacements", delegate
		{
			skinParams.projectileGhostReplacements = Array.Empty<ProjectileGhostReplacement>();
		});
		return skin;
	}

	private static void AddBeetleGuardAllyBodyTermanid_BGuardSkinDefSkin()
	{
		string text = "BeetleGuardAllyBody";
		string text2 = "Termanid_BGuardSkinDef";
		GameObject val = BodyCatalog.FindBodyPrefab(text);
		if (!Object.op_Implicit((Object)(object)val))
		{
			InstanceLogger.LogWarning((object)("Failed to add \"" + text2 + "\" skin because \"" + text + "\" doesn't exist"));
			return;
		}
		try
		{
			ModelLocator component = val.GetComponent<ModelLocator>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				InstanceLogger.LogWarning((object)("Failed to add \"" + text2 + "\" skin to \"" + text + "\" because it doesn't have \"ModelLocator\" component"));
				return;
			}
			GameObject gameObject = ((Component)component.modelTransform).gameObject;
			ModelSkinController val2 = (Object.op_Implicit((Object)(object)gameObject) ? gameObject.GetComponent<ModelSkinController>() : null);
			if (!Object.op_Implicit((Object)(object)val2))
			{
				InstanceLogger.LogWarning((object)("Failed to add \"" + text2 + "\" skin to \"" + text + "\" because it doesn't have \"ModelSkinController\" component"));
			}
			else
			{
				SkinDef val3 = CreateBeetleGuardAllyBodyTermanid_BGuardSkinDefSkin(gameObject, val2);
				Array.Resize(ref val2.skins, val2.skins.Length + 1);
				val2.skins[val2.skins.Length - 1] = val3;
				BeetleGuardAllyBodyTermanid_BGuardSkinDefSkinAdded(val3, val);
			}
		}
		catch (FieldException ex)
		{
			if (ex.InnerException is ElementException ex2)
			{
				InstanceLogger.LogWarning((object)("Failed to add \"" + text2 + "\" skin to \"" + text + "\""));
				InstanceLogger.LogWarning((object)$"Field causing issue: {ex.Message}, element: {ex2.Index}");
				InstanceLogger.LogWarning((object)ex2.Message);
				InstanceLogger.LogError((object)ex.InnerException);
			}
			else
			{
				InstanceLogger.LogWarning((object)("Failed to add \"" + text2 + "\" skin to \"" + text + "\""));
				InstanceLogger.LogWarning((object)("Field causing issue: " + ex.Message));
				InstanceLogger.LogError((object)ex.InnerException);
			}
		}
		catch (Exception ex3)
		{
			InstanceLogger.LogWarning((object)("Failed to add \"" + text2 + "\" skin to \"" + text + "\""));
			InstanceLogger.LogError((object)ex3);
		}
	}
}
public static class Helpers
{
	private static GameObject prefabHolder;

	public static GameObject ClonePrefab(GameObject gameObject)
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Expected O, but got Unknown
		if (!Object.op_Implicit((Object)(object)prefabHolder))
		{
			prefabHolder = new GameObject("PrefabHolder");
			Object.DontDestroyOnLoad((Object)(object)prefabHolder);
			prefabHolder.SetActive(false);
		}
		GameObject obj = Object.Instantiate<GameObject>(gameObject, prefabHolder.transform);
		obj.AddComponent<RemoveClone>();
		((Object)obj).name = ((Object)gameObject).name;
		return obj;
	}

	public static GameObject GetChildGameObject(GameObject fromGameObject, string withName)
	{
		Transform[] componentsInChildren = fromGameObject.GetComponentsInChildren<Transform>();
		foreach (Transform val in componentsInChildren)
		{
			if (((Object)val).name.StartsWith(withName))
			{
				return ((Component)val).gameObject;
			}
		}
		return null;
	}

	public static Transform GetChild(this Transform transform, int index, out Transform child)
	{
		return child = transform.GetChild(index);
	}

	public static GameObject WithComponent<T>(this GameObject gameObject, Action<T> modifier = null) where T : Component
	{
		T obj = gameObject.AddComponent<T>();
		modifier?.Invoke(obj);
		return gameObject;
	}

	public static GameObject WithTryComponent<T>(this GameObject gameObject, Action<T> modifier = null) where T : Component
	{
		if (Object.op_Implicit((Object)(object)gameObject) && !Object.op_Implicit((Object)(object)gameObject.GetComponent<T>()))
		{
			T obj = gameObject.AddComponent<T>();
			modifier?.Invoke(obj);
		}
		return gameObject;
	}

	public static T ThrowIfEquals<T>(int index, string message, T value, T expected) where T : Enum
	{
		if (value.Equals(expected))
		{
			throw new ElementException(index, message);
		}
		return value;
	}

	public static T ThrowIfOutOfBounds<T>(int index, string message, T[] array, int elementIndex) where T : class
	{
		if (array == null || array.Length <= elementIndex)
		{
			throw new ElementException(index, message);
		}
		return array[elementIndex];
	}

	public static T ThrowIfNull<T>(int index, string message, T value) where T : class
	{
		if (value == null)
		{
			throw new ElementException(index, message);
		}
		return value;
	}

	public static void TryCatchThrow(string message, Action action)
	{
		try
		{
			action?.Invoke();
		}
		catch (Exception innerException)
		{
			throw new FieldException(message, innerException);
		}
	}
}
public class RemoveClone : MonoBehaviour
{
	public void Awake()
	{
		((Object)this).name = ((Object)this).name[..^7];
	}
}
public class FieldException : Exception
{
	public FieldException(string message, Exception innerException)
		: base(message, innerException)
	{
	}
}
public class ElementException : Exception
{
	public int Index { get; }

	public ElementException(int index, string message)
		: base(message)
	{
		Index = index;
	}
}
public class InsertBones : MonoBehaviour
{
	private readonly List<SkinnedMeshRenderer> modifiedRenderers = new List<SkinnedMeshRenderer>();

	public List<string> rendererPaths = new List<string>();

	public List<Transform> newBones = new List<Transform>();

	public string afterPath;

	public void Awake()
	{
		Transform transform = ((Component)((Component)this).GetComponentInParent<ModelSkinController>()).transform;
		Transform value = ((Component)transform).transform.Find(afterPath);
		foreach (string rendererPath in rendererPaths)
		{
			Transform obj = transform.Find(rendererPath);
			SkinnedMeshRenderer val = ((obj != null) ? ((Component)obj).GetComponent<SkinnedMeshRenderer>() : null);
			if (Object.op_Implicit((Object)(object)val))
			{
				Transform[] array = val.bones;
				int num = Array.IndexOf(array, value) + 1;
				if (num != 0)
				{
					Array.Resize(ref array, array.Length + newBones.Count);
					Array.Copy(array, num, array, num + newBones.Count, array.Length - newBones.Count - num);
					newBones.CopyTo(array, num);
					val.bones = array;
					modifiedRenderers.Add(val);
				}
			}
		}
	}

	public void OnDestroy()
	{
		foreach (SkinnedMeshRenderer modifiedRenderer in modifiedRenderers)
		{
			if (Object.op_Implicit((Object)(object)modifiedRenderer))
			{
				Transform[] array = modifiedRenderer.bones;
				int num = Array.IndexOf(array, ((Component)this).transform);
				Array.Copy(array, num + newBones.Count, array, num, array.Length - num - newBones.Count);
				Array.Resize(ref array, array.Length - newBones.Count);
				modifiedRenderer.bones = array;
			}
		}
		modifiedRenderers.Clear();
	}
}
public class AddDynamicColliders : MonoBehaviour
{
	public List<string> paths = new List<string>();

	public void Awake()
	{
		Transform transform = ((Component)((Component)this).GetComponentInParent<ModelSkinController>()).transform;
		List<DynamicBoneCollider> list = new List<DynamicBoneCollider>();
		foreach (string path in paths)
		{
			Transform val = transform.Find(path);
			if (Object.op_Implicit((Object)(object)val))
			{
				list.AddRange(((Component)val).GetComponents<DynamicBoneCollider>());
			}
		}
		DynamicBone[] components = ((Component)this).GetComponents<DynamicBone>();
		for (int i = 0; i < components.Length; i++)
		{
			components[i].m_Colliders.AddRange(list);
		}
	}
}