Decompiled source of FullBright v1.2.0

Fullbright.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
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.Rendering;

[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: AssemblyCompany("Omniscye")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+d216d558a3455c46361d703c10f5dc5bf63d31fb")]
[assembly: AssemblyProduct("Fullbright")]
[assembly: AssemblyTitle("Fullbright")]
[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 Fullbright
{
	[BepInPlugin("Omniscye.Fullbright", "Fullbright", "1.2")]
	public class Fullbright : BaseUnityPlugin
	{
		private ConfigEntry<bool> _enableCullingOverride = null;

		private ConfigEntry<bool> _disableOcclusionCulling = null;

		private ConfigEntry<float> _nearClipTarget = null;

		private ConfigEntry<float> _farClipTarget = null;

		private ConfigEntry<float> _perLayerCullDistance = null;

		private ConfigEntry<bool> _forceEverythingMask = null;

		private ConfigEntry<bool> _onlyMainCamera = null;

		internal static Fullbright Instance { get; private set; }

		internal static ManualLogSource Logger => Instance._logger;

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

		internal Harmony? Harmony { get; set; }

		private void Awake()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Expected O, but got Unknown
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			Instance = this;
			((Component)this).gameObject.transform.parent = null;
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			BindConfig();
			Camera.onPreCull = (CameraCallback)Delegate.Remove((Delegate?)(object)Camera.onPreCull, (Delegate?)new CameraCallback(HandleCameraPreCull));
			Camera.onPreCull = (CameraCallback)Delegate.Combine((Delegate?)(object)Camera.onPreCull, (Delegate?)new CameraCallback(HandleCameraPreCull));
			RenderPipelineManager.beginCameraRendering -= HandleBeginCameraRendering;
			RenderPipelineManager.beginCameraRendering += HandleBeginCameraRendering;
			Patch();
			Logger.LogInfo((object)$"{((BaseUnityPlugin)this).Info.Metadata.GUID} v{((BaseUnityPlugin)this).Info.Metadata.Version} loaded — culling overrides armed.");
		}

		private void OnDestroy()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			Camera.onPreCull = (CameraCallback)Delegate.Remove((Delegate?)(object)Camera.onPreCull, (Delegate?)new CameraCallback(HandleCameraPreCull));
			RenderPipelineManager.beginCameraRendering -= HandleBeginCameraRendering;
			Unpatch();
		}

		private void BindConfig()
		{
			_enableCullingOverride = ((BaseUnityPlugin)this).Config.Bind<bool>("Culling", "EnableOverride", true, "Master switch for all camera culling overrides.");
			_disableOcclusionCulling = ((BaseUnityPlugin)this).Config.Bind<bool>("Culling", "DisableOcclusionCulling", true, "Forces Camera.useOcclusionCulling = false.");
			_nearClipTarget = ((BaseUnityPlugin)this).Config.Bind<float>("Culling", "NearClip", 0.01f, "Near clip plane to enforce (minimum).");
			_farClipTarget = ((BaseUnityPlugin)this).Config.Bind<float>("Culling", "FarClip", 100000f, "Far clip plane to enforce (maximum).");
			_perLayerCullDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Culling", "PerLayerCullDistance", 1000000f, "Per-layer cull distance for all 32 layers.");
			_forceEverythingMask = ((BaseUnityPlugin)this).Config.Bind<bool>("Culling", "ForceEverythingMask", false, "If true, forces cullingMask to Everything (~0).");
			_onlyMainCamera = ((BaseUnityPlugin)this).Config.Bind<bool>("Culling", "OnlyMainCamera", false, "If true, only touches Camera.main. False = apply to any rendering camera.");
		}

		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 HandleCameraPreCull(Camera cam)
		{
			ApplyOverrides(cam);
		}

		private void HandleBeginCameraRendering(ScriptableRenderContext ctx, Camera cam)
		{
			ApplyOverrides(cam);
		}

		private void ApplyOverrides(Camera cam)
		{
			if (!_enableCullingOverride.Value || (Object)(object)cam == (Object)null || (_onlyMainCamera.Value && (Object)(object)cam != (Object)(object)Camera.main))
			{
				return;
			}
			try
			{
				if (_disableOcclusionCulling.Value)
				{
					cam.useOcclusionCulling = false;
				}
				if (_nearClipTarget.Value > 0f)
				{
					cam.nearClipPlane = Mathf.Min(cam.nearClipPlane, _nearClipTarget.Value);
				}
				if (_farClipTarget.Value > 0f)
				{
					cam.farClipPlane = Mathf.Max(cam.farClipPlane, _farClipTarget.Value);
				}
				float num = Mathf.Max(0f, _perLayerCullDistance.Value);
				if (cam.layerCullDistances == null || cam.layerCullDistances.Length != 32)
				{
					cam.layerCullDistances = new float[32];
				}
				float[] layerCullDistances = cam.layerCullDistances;
				for (int i = 0; i < 32; i++)
				{
					layerCullDistances[i] = num;
				}
				cam.layerCullDistances = layerCullDistances;
				cam.layerCullSpherical = true;
				if (_forceEverythingMask.Value)
				{
					cam.cullingMask = -1;
				}
			}
			catch (Exception ex)
			{
				Logger.LogWarning((object)("Camera override failed on '" + (((cam != null) ? ((Object)cam).name : null) ?? "null") + "': " + ex.Message));
			}
		}

		private void Update()
		{
		}
	}
}
namespace EmpressMods.REPOFullbright
{
	[BepInPlugin("com.empress.repo.fullbright", "Empress Fullbright", "1.4.0")]
	public class EmpressFullbrightPlugin : BaseUnityPlugin
	{
		private sealed class FilteringLogHandler : ILogHandler
		{
			private readonly ILogHandler _inner;

			private readonly Func<LogType, string, bool> _predicate;

			public FilteringLogHandler(ILogHandler inner, Func<LogType, string, bool> predicate)
			{
				_inner = inner;
				_predicate = predicate;
			}

			public void LogFormat(LogType logType, Object context, string format, params object[] args)
			{
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0045: Unknown result type (might be due to invalid IL or missing references)
				string arg;
				try
				{
					arg = ((args != null && args.Length != 0) ? string.Format(format, args) : format);
				}
				catch
				{
					arg = format;
				}
				if (_predicate == null || !_predicate(logType, arg))
				{
					_inner.LogFormat(logType, context, format, args);
				}
			}

			public void LogException(Exception exception, Object context)
			{
				_inner.LogException(exception, context);
			}
		}

		public const string PluginGuid = "com.empress.repo.fullbright";

		public const string PluginName = "Empress Fullbright";

		public const string PluginVersion = "1.4.0";

		internal static EmpressFullbrightPlugin Instance;

		internal static ManualLogSource Log;

		internal static bool Enabled;

		private static Harmony _harmony;

		private ConfigEntry<KeyboardShortcut> _toggleKey;

		internal ConfigEntry<bool> _disableFog;

		internal ConfigEntry<bool> _disableOcclusion;

		private ConfigEntry<bool> _debugLog;

		private ConfigEntry<bool> _muteUnityWarnings;

		private ConfigEntry<bool> _muteOnlyWhenEnabled;

		private ConfigEntry<string> _mutePatterns;

		private CameraHook _cameraHook;

		private float _nextToggleTime;

		private const float AMBIENT_BOOST = 1.5f;

		private ILogHandler _originalHandler;

		private FilteringLogHandler _filterHandler;

		private void Awake()
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger ?? Logger.CreateLogSource("com.empress.repo.fullbright");
			_toggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("General", "ToggleKey", new KeyboardShortcut((KeyCode)120, Array.Empty<KeyCode>()), "Hotkey");
			_disableFog = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "DisableFog", true, "Fog");
			_disableOcclusion = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "DisableOcclusionCulling", true, "Occlusion");
			_debugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "VerboseLogging", false, "Verbose");
			_muteUnityWarnings = ((BaseUnityPlugin)this).Config.Bind<bool>("LogFilter", "MuteUnityWarnings", true, "Mute");
			_muteOnlyWhenEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("LogFilter", "OnlyWhenFullbrightEnabled", true, "Scoped");
			_mutePatterns = ((BaseUnityPlugin)this).Config.Bind<string>("LogFilter", "Patterns", "JobTempAlloc has allocations that are more than the maximum lifespan of 4 frames old|diag-job-temp-memory-leak-validation", "Patterns");
			_cameraHook = new GameObject("EmpressFullbrightCameraHook").AddComponent<CameraHook>();
			Object.DontDestroyOnLoad((Object)(object)((Component)_cameraHook).gameObject);
			_cameraHook.SyncFromConfig(this);
			Enabled = true;
			_harmony = new Harmony("com.empress.repo.fullbright");
			_harmony.PatchAll();
			_originalHandler = Debug.unityLogger.logHandler;
			_filterHandler = new FilteringLogHandler(_originalHandler, ShouldMute);
			if (_muteUnityWarnings.Value)
			{
				Debug.unityLogger.logHandler = (ILogHandler)(object)_filterHandler;
			}
			Log.LogInfo((object)"Empress Fullbright 1.4.0 loaded.");
		}

		private void OnDestroy()
		{
			try
			{
				Harmony harmony = _harmony;
				if (harmony != null)
				{
					harmony.UnpatchSelf();
				}
			}
			catch
			{
			}
			if (Object.op_Implicit((Object)(object)_cameraHook))
			{
				Object.Destroy((Object)(object)((Component)_cameraHook).gameObject);
			}
			if (Debug.unityLogger.logHandler == _filterHandler)
			{
				Debug.unityLogger.logHandler = _originalHandler;
			}
		}

		private void Update()
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				KeyboardShortcut value = _toggleKey.Value;
				if ((!((KeyboardShortcut)(ref value)).IsDown() && !Input.GetKeyDown((KeyCode)120)) || !(Time.unscaledTime >= _nextToggleTime))
				{
					return;
				}
				_nextToggleTime = Time.unscaledTime + 0.3f;
				Enabled = !Enabled;
				if (!Enabled)
				{
					_cameraHook.RestoreGlobals();
				}
				if (_debugLog.Value)
				{
					ManualLogSource log = Log;
					if (log != null)
					{
						log.LogInfo((object)("Fullbright => " + (Enabled ? "ON" : "OFF")));
					}
				}
			}
			catch
			{
			}
		}

		internal float GetAmbientBoost()
		{
			return 1.5f;
		}

		private bool ShouldMute(LogType type, string msg)
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Invalid comparison between Unknown and I4
			if (!_muteUnityWarnings.Value)
			{
				return false;
			}
			if (_muteOnlyWhenEnabled.Value && !Enabled)
			{
				return false;
			}
			if ((int)type != 2)
			{
				return false;
			}
			if (string.IsNullOrEmpty(msg))
			{
				return false;
			}
			string[] array = _mutePatterns.Value.Split(new char[1] { '|' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length != 0 && msg.IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0)
				{
					return true;
				}
			}
			return false;
		}
	}
	internal sealed class CameraHook : MonoBehaviour
	{
		private struct Saved
		{
			public Color ambient;

			public float fogEnd;

			public bool fogEnabled;

			public bool useOcclusion;
		}

		private readonly Dictionary<int, Saved> _perCamSaved = new Dictionary<int, Saved>();

		public bool DisableFog = true;

		public bool DisableOcclusion = true;

		public void SyncFromConfig(EmpressFullbrightPlugin p)
		{
			DisableFog = p._disableFog.Value;
			DisableOcclusion = p._disableOcclusion.Value;
		}

		private void OnEnable()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			Camera.onPreCull = (CameraCallback)Delegate.Combine((Delegate?)(object)Camera.onPreCull, (Delegate?)new CameraCallback(CamPreCull));
			Camera.onPostRender = (CameraCallback)Delegate.Combine((Delegate?)(object)Camera.onPostRender, (Delegate?)new CameraCallback(CamPostRender));
		}

		private void OnDisable()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			Camera.onPreCull = (CameraCallback)Delegate.Remove((Delegate?)(object)Camera.onPreCull, (Delegate?)new CameraCallback(CamPreCull));
			Camera.onPostRender = (CameraCallback)Delegate.Remove((Delegate?)(object)Camera.onPostRender, (Delegate?)new CameraCallback(CamPostRender));
		}

		private void CamPreCull(Camera cam)
		{
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			if (EmpressFullbrightPlugin.Enabled && !((Object)(object)cam == (Object)null))
			{
				int instanceID = ((Object)cam).GetInstanceID();
				if (!_perCamSaved.ContainsKey(instanceID))
				{
					_perCamSaved[instanceID] = new Saved
					{
						ambient = RenderSettings.ambientLight,
						fogEnd = RenderSettings.fogEndDistance,
						fogEnabled = RenderSettings.fog,
						useOcclusion = cam.useOcclusionCulling
					};
				}
				float ambientBoost = EmpressFullbrightPlugin.Instance.GetAmbientBoost();
				RenderSettings.ambientMode = (AmbientMode)3;
				RenderSettings.ambientLight = new Color(ambientBoost, ambientBoost, ambientBoost, 1f);
				if (DisableFog)
				{
					RenderSettings.fogEndDistance = 500f;
				}
				if (DisableOcclusion)
				{
					cam.useOcclusionCulling = false;
				}
			}
		}

		private void CamPostRender(Camera cam)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)cam == (Object)null))
			{
				int instanceID = ((Object)cam).GetInstanceID();
				if (_perCamSaved.TryGetValue(instanceID, out var value))
				{
					RenderSettings.ambientLight = value.ambient;
					RenderSettings.fogEndDistance = value.fogEnd;
					RenderSettings.fog = value.fogEnabled;
					cam.useOcclusionCulling = value.useOcclusion;
					_perCamSaved.Remove(instanceID);
				}
			}
		}

		public void RestoreGlobals()
		{
			try
			{
				RenderSettings.ambientMode = (AmbientMode)1;
				RenderSettings.fog = true;
				Camera[] allCameras = Camera.allCameras;
				foreach (Camera val in allCameras)
				{
					if (!((Object)(object)val == (Object)null))
					{
						val.useOcclusionCulling = true;
					}
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(EnvironmentDirector), "Update")]
	internal static class Patch_EnvironmentDirector_Update
	{
		private static void Postfix()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			if (!EmpressFullbrightPlugin.Enabled)
			{
				return;
			}
			try
			{
				float ambientBoost = EmpressFullbrightPlugin.Instance.GetAmbientBoost();
				RenderSettings.ambientMode = (AmbientMode)3;
				RenderSettings.ambientLight = new Color(ambientBoost, ambientBoost, ambientBoost, 1f);
				EmpressFullbrightPlugin instance = EmpressFullbrightPlugin.Instance;
				if (instance != null && instance._disableFog.Value)
				{
					RenderSettings.fogEndDistance = 500f;
				}
			}
			catch
			{
			}
		}
	}
}