Decompiled source of Duck It v1.0.0

DUckTextures.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.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("")]
[assembly: AssemblyCompany("Omniscye")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("DUckTextures")]
[assembly: AssemblyTitle("DUckTextures")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 DUckTextures
{
	[BepInPlugin("Omniscye.DUckTextures", "DUckTextures", "1.0")]
	public class DUckTextures : BaseUnityPlugin
	{
		internal static DUckTextures Instance { get; private set; }

		internal static ManualLogSource Logger => Instance._logger;

		private ManualLogSource _logger => ((BaseUnityPlugin)this).Logger;

		internal Harmony? Harmony { get; set; }

		private void Awake()
		{
			Instance = this;
			((Component)this).gameObject.transform.parent = null;
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			Patch();
			Logger.LogInfo((object)$"{((BaseUnityPlugin)this).Info.Metadata.GUID} v{((BaseUnityPlugin)this).Info.Metadata.Version} has loaded!");
		}

		internal void Patch()
		{
			//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_0021: Expected O, but got Unknown
			//IL_0026: Expected O, but got Unknown
			if (Harmony == null)
			{
				Harmony val = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID);
				Harmony val2 = val;
				Harmony = val;
			}
			Harmony.PatchAll();
		}

		internal void Unpatch()
		{
			Harmony? harmony = Harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		private void Update()
		{
		}
	}
}
namespace Empress.Duckify
{
	[BepInPlugin("com.empress.duckify", "Duckify: One-Shot On Level Build", "1.6.0")]
	public sealed class DuckifyPlugin : BaseUnityPlugin
	{
		private Harmony _harmony;

		private ConfigEntry<string> _bundleName;

		private ConfigEntry<string> _materialName;

		private ConfigEntry<string> _prefabName;

		private ConfigEntry<bool> _includeMap;

		private ConfigEntry<bool> _includeEnemies;

		private ConfigEntry<bool> _includeValuables;

		private ConfigEntry<bool> _includePhysObjects;

		private ConfigEntry<bool> _includeParticles;

		private ConfigEntry<bool> _includeSprites;

		private ConfigEntry<bool> _excludePlayers;

		private void Awake()
		{
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_025f: Expected O, but got Unknown
			_bundleName = ((BaseUnityPlugin)this).Config.Bind<string>("DuckAsset", "BundleFileName", "duck", "AssetBundle filename (e.g., 'duck.bundle').");
			_materialName = ((BaseUnityPlugin)this).Config.Bind<string>("DuckAsset", "MaterialName", "Duck", "Material name inside the bundle.");
			_prefabName = ((BaseUnityPlugin)this).Config.Bind<string>("DuckAsset", "PrefabName", "Duck", "Optional prefab that has a Renderer using the material.");
			_includeMap = ((BaseUnityPlugin)this).Config.Bind<bool>("Targets", "IncludeMap", true, "Duckify LevelGenerator.LevelParent (walls/floors).");
			_includeEnemies = ((BaseUnityPlugin)this).Config.Bind<bool>("Targets", "IncludeEnemies", true, "Duckify Enemy renderers.");
			_includeValuables = ((BaseUnityPlugin)this).Config.Bind<bool>("Targets", "IncludeValuables", true, "Duckify ValuableObject renderers.");
			_includePhysObjects = ((BaseUnityPlugin)this).Config.Bind<bool>("Targets", "IncludePhysObjects", true, "Duckify PhysGrabObject renderers.");
			_includeParticles = ((BaseUnityPlugin)this).Config.Bind<bool>("Filters", "IncludeParticles", false, "Also replace ParticleSystemRenderer materials.");
			_includeSprites = ((BaseUnityPlugin)this).Config.Bind<bool>("Filters", "IncludeSprites", false, "Also replace SpriteRenderer materials.");
			_excludePlayers = ((BaseUnityPlugin)this).Config.Bind<bool>("Filters", "ExcludePlayers", true, "Never touch player visuals and cameras.");
			string source;
			Material val = LoadDuckMaterial(out source);
			if ((Object)(object)val == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Duck material not found. Provide a bundle with a Material named 'Duck'.");
				return;
			}
			if ((Object)(object)val.shader == (Object)null || !val.shader.isSupported)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Duck material's shader unsupported on this platform.");
				return;
			}
			DuckCore.Log = ((BaseUnityPlugin)this).Logger;
			DuckCore.Duck = val;
			DuckCore.IncludeParticles = _includeParticles.Value;
			DuckCore.IncludeSprites = _includeSprites.Value;
			DuckCore.ExcludePlayers = _excludePlayers.Value;
			DuckCore.IncludeMap = _includeMap.Value;
			DuckCore.IncludeEnemies = _includeEnemies.Value;
			DuckCore.IncludeValuables = _includeValuables.Value;
			DuckCore.IncludePhysObjects = _includePhysObjects.Value;
			SceneManager.sceneLoaded += OnSceneLoaded;
			_harmony = new Harmony("com.empress.duckify.oneshot");
			_harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Duckify initialized. Source: " + source));
		}

		private void OnDestroy()
		{
			try
			{
				Harmony harmony = _harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
			}
			catch
			{
			}
			SceneManager.sceneLoaded -= OnSceneLoaded;
		}

		private void OnSceneLoaded(Scene s, LoadSceneMode m)
		{
			DuckCore.ResetProcessed();
			DuckCore.ComputeOverlayMasks();
			try
			{
				LevelGenerator instance = LevelGenerator.Instance;
				if ((Object)(object)instance != (Object)null && instance.Generated)
				{
					DuckCore.RunOneShotPass();
				}
			}
			catch
			{
			}
		}

		private Material LoadDuckMaterial(out string source)
		{
			source = "<none>";
			try
			{
				string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
				List<string> list = new List<string>();
				if (!string.IsNullOrEmpty(directoryName))
				{
					list.Add(Path.Combine(directoryName, _bundleName.Value));
					list.Add(Path.Combine(directoryName, _bundleName.Value + ".bundle"));
					list.Add(Path.Combine(directoryName, _bundleName.Value + ".assets"));
				}
				list.Add(Path.Combine(Paths.PluginPath, _bundleName.Value));
				list.Add(Path.Combine(Paths.PluginPath, _bundleName.Value + ".bundle"));
				list.Add(Path.Combine(Paths.PluginPath, _bundleName.Value + ".assets"));
				list.Add(Path.Combine(Paths.GameRootPath, _bundleName.Value));
				list.Add(Path.Combine(Paths.GameRootPath, _bundleName.Value + ".bundle"));
				list.Add(Path.Combine(Paths.GameRootPath, _bundleName.Value + ".assets"));
				string text = list.FirstOrDefault(File.Exists);
				if (string.IsNullOrEmpty(text))
				{
					return null;
				}
				AssetBundle val = AssetBundle.LoadFromFile(text);
				if ((Object)(object)val == (Object)null)
				{
					return null;
				}
				Material val2 = val.LoadAsset<Material>(_materialName.Value);
				if ((Object)(object)val2 != (Object)null)
				{
					source = "Material '" + _materialName.Value + "'";
					return val2;
				}
				GameObject val3 = val.LoadAsset<GameObject>(_prefabName.Value);
				if ((Object)(object)val3 != (Object)null)
				{
					Renderer componentInChildren = val3.GetComponentInChildren<Renderer>(true);
					if ((Object)(object)componentInChildren != (Object)null)
					{
						if ((Object)(object)componentInChildren.sharedMaterial != (Object)null)
						{
							source = "Prefab renderer material";
							return componentInChildren.sharedMaterial;
						}
						if (componentInChildren.sharedMaterials != null && componentInChildren.sharedMaterials.Length != 0)
						{
							source = "Prefab first sharedMaterial";
							return componentInChildren.sharedMaterials[0];
						}
					}
				}
				string[] allAssetNames = val.GetAllAssetNames();
				foreach (string text2 in allAssetNames)
				{
					if (text2.EndsWith(".mat", StringComparison.OrdinalIgnoreCase) && text2.IndexOf("duck", StringComparison.OrdinalIgnoreCase) >= 0)
					{
						Material val4 = val.LoadAsset<Material>(text2);
						if ((Object)(object)val4 != (Object)null)
						{
							source = "Material '" + text2 + "'";
							return val4;
						}
					}
				}
				return null;
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Duck material load failed: " + ex));
				return null;
			}
		}
	}
	internal static class DuckCore
	{
		public static ManualLogSource Log;

		public static Material Duck;

		public static bool IncludeParticles;

		public static bool IncludeSprites;

		public static bool ExcludePlayers;

		public static bool IncludeMap;

		public static bool IncludeEnemies;

		public static bool IncludeValuables;

		public static bool IncludePhysObjects;

		private static readonly HashSet<int> done = new HashSet<int>();

		private static int overlayOnlyMask = 0;

		private static int baseMask = -1;

		public static void ResetProcessed()
		{
			done.Clear();
		}

		public static void ComputeOverlayMasks()
		{
			overlayOnlyMask = 0;
			baseMask = -1;
			try
			{
				Camera[] allCameras = Camera.allCameras;
				if (allCameras == null || allCameras.Length == 0)
				{
					return;
				}
				Camera val = null;
				float num = float.PositiveInfinity;
				Camera[] array = allCameras;
				foreach (Camera val2 in array)
				{
					if (!((Object)(object)val2 == (Object)null) && ((Behaviour)val2).enabled && val2.depth < num)
					{
						num = val2.depth;
						val = val2;
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				baseMask = val.cullingMask;
				int num2 = 0;
				Camera[] array2 = allCameras;
				foreach (Camera val3 in array2)
				{
					if (!((Object)(object)val3 == (Object)null) && ((Behaviour)val3).enabled && !((Object)(object)val3 == (Object)(object)val) && val3.depth >= val.depth)
					{
						num2 |= val3.cullingMask;
					}
				}
				overlayOnlyMask = num2 & ~baseMask;
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogInfo((object)$"OverlayOnlyMask=0x{overlayOnlyMask:X}");
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log2 = Log;
				if (log2 != null)
				{
					log2.LogInfo((object)("ComputeOverlayMasks failed: " + ex.Message));
				}
			}
		}

		public static void RunOneShotPass()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Duck == (Object)null)
			{
				return;
			}
			try
			{
				Scene activeScene = SceneManager.GetActiveScene();
				if (!((Scene)(ref activeScene)).IsValid() || !((Scene)(ref activeScene)).isLoaded)
				{
					return;
				}
				if (IncludeMap)
				{
					GameObject val = TryGetLevelParent();
					if ((Object)(object)val != (Object)null)
					{
						DuckifyUnder(val);
					}
				}
				if (IncludeEnemies)
				{
					Enemy[] array = Object.FindObjectsOfType<Enemy>(true);
					foreach (Enemy val2 in array)
					{
						if (!((Object)(object)val2 == (Object)null) && !(((Component)val2).gameObject.scene != activeScene))
						{
							DuckifyUnder(((Component)val2).gameObject);
						}
					}
				}
				if (IncludeValuables)
				{
					ValuableObject[] array2 = Object.FindObjectsOfType<ValuableObject>(true);
					foreach (ValuableObject val3 in array2)
					{
						if (!((Object)(object)val3 == (Object)null) && !(((Component)val3).gameObject.scene != activeScene))
						{
							DuckifyUnder(((Component)val3).gameObject);
						}
					}
				}
				if (!IncludePhysObjects)
				{
					return;
				}
				PhysGrabObject[] array3 = Object.FindObjectsOfType<PhysGrabObject>(true);
				foreach (PhysGrabObject val4 in array3)
				{
					if (!((Object)(object)val4 == (Object)null) && !(((Component)val4).gameObject.scene != activeScene))
					{
						DuckifyUnder(((Component)val4).gameObject);
					}
				}
			}
			catch (Exception ex)
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogError((object)("One-shot pass failed: " + ex));
				}
			}
		}

		private static GameObject TryGetLevelParent()
		{
			try
			{
				LevelGenerator instance = LevelGenerator.Instance;
				if ((Object)(object)instance != (Object)null && (Object)(object)instance.LevelParent != (Object)null)
				{
					return instance.LevelParent;
				}
			}
			catch
			{
			}
			return null;
		}

		public static void DuckifyUnder(GameObject root)
		{
			if (!((Object)(object)Duck == (Object)null) && !((Object)(object)root == (Object)null))
			{
				Renderer[] componentsInChildren = root.GetComponentsInChildren<Renderer>(true);
				for (int i = 0; i < componentsInChildren.Length; i++)
				{
					Apply(componentsInChildren[i]);
				}
			}
		}

		public static void Apply(Renderer r)
		{
			if ((Object)(object)r == (Object)null || (Object)(object)Duck == (Object)null || (!IncludeParticles && r is ParticleSystemRenderer) || (!IncludeSprites && r is SpriteRenderer) || (ExcludePlayers && IsPlayerRelated(r)) || IsOverlayRelated(r) || IsUI(r))
			{
				return;
			}
			try
			{
				int num = 1 << ((Component)r).gameObject.layer;
				if ((overlayOnlyMask & num) != 0)
				{
					return;
				}
			}
			catch
			{
			}
			int instanceID = ((Object)r).GetInstanceID();
			if (done.Contains(instanceID))
			{
				return;
			}
			try
			{
				Material[] sharedMaterials = r.sharedMaterials;
				if (sharedMaterials == null || sharedMaterials.Length == 0)
				{
					r.sharedMaterial = Duck;
				}
				else
				{
					for (int i = 0; i < sharedMaterials.Length; i++)
					{
						sharedMaterials[i] = Duck;
					}
					r.sharedMaterials = sharedMaterials;
				}
				done.Add(instanceID);
			}
			catch (Exception ex)
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogInfo((object)("Skip '" + ((Object)r).name + "' (" + ((object)r).GetType().Name + "): " + ex.Message));
				}
			}
		}

		private static bool IsUI(Renderer r)
		{
			try
			{
				if ((Object)(object)((Component)r).GetComponentInParent<Canvas>(true) != (Object)null)
				{
					return true;
				}
			}
			catch
			{
			}
			return false;
		}

		private static bool IsOverlayRelated(Renderer r)
		{
			GameObject gameObject = ((Component)r).gameObject;
			if ((Object)(object)gameObject.GetComponentInParent<Camera>(true) != (Object)null)
			{
				return true;
			}
			if ((Object)(object)gameObject.GetComponentInParent<CameraOverlay>(true) != (Object)null)
			{
				return true;
			}
			if ((Object)(object)gameObject.GetComponentInParent<CameraTopFade>(true) != (Object)null)
			{
				return true;
			}
			if ((Object)(object)gameObject.GetComponentInParent<SpiralOnScreen>(true) != (Object)null)
			{
				return true;
			}
			return false;
		}

		private static bool IsPlayerRelated(Renderer r)
		{
			GameObject gameObject = ((Component)r).gameObject;
			try
			{
				if (gameObject.CompareTag("Player"))
				{
					return true;
				}
			}
			catch
			{
			}
			try
			{
				if (gameObject.layer == LayerMask.NameToLayer("Player"))
				{
					return true;
				}
			}
			catch
			{
			}
			if ((Object)(object)gameObject.GetComponentInParent<PlayerAvatarVisuals>(true) != (Object)null)
			{
				return true;
			}
			if ((Object)(object)gameObject.GetComponentInParent<PlayerAvatar>(true) != (Object)null)
			{
				return true;
			}
			if ((Object)(object)gameObject.GetComponentInParent<PlayerHealth>(true) != (Object)null)
			{
				return true;
			}
			if ((Object)(object)gameObject.GetComponentInParent<PlayerEyes>(true) != (Object)null)
			{
				return true;
			}
			if ((Object)(object)gameObject.GetComponentInParent<PlayerAvatarRightArm>(true) != (Object)null)
			{
				return true;
			}
			if ((Object)(object)gameObject.GetComponentInParent<PlayerAvatarLeftArm>(true) != (Object)null)
			{
				return true;
			}
			if ((Object)(object)gameObject.GetComponentInParent<PlayerAvatarEyelids>(true) != (Object)null)
			{
				return true;
			}
			if ((Object)(object)gameObject.GetComponentInParent<PlayerAvatarOverchargeVisuals>(true) != (Object)null)
			{
				return true;
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class Patches
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(LevelGenerator), "GenerateDone")]
		private static void LevelGenDone_Postfix()
		{
			DuckCore.ComputeOverlayMasks();
			DuckCore.RunOneShotPass();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(Enemy), "Awake")]
		private static void Enemy_Awake_Postfix(Enemy __instance)
		{
			if (!((Object)(object)__instance == (Object)null) && DuckCore.IncludeEnemies)
			{
				DuckCore.DuckifyUnder(((Component)__instance).gameObject);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ValuableObject), "Awake")]
		private static void Valuable_Awake_Postfix(ValuableObject __instance)
		{
			if (!((Object)(object)__instance == (Object)null) && DuckCore.IncludeValuables)
			{
				DuckCore.DuckifyUnder(((Component)__instance).gameObject);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PhysGrabObject), "Awake")]
		private static void Phys_Awake_Postfix(PhysGrabObject __instance)
		{
			if (!((Object)(object)__instance == (Object)null) && DuckCore.IncludePhysObjects)
			{
				DuckCore.DuckifyUnder(((Component)__instance).gameObject);
			}
		}
	}
}