Decompiled source of ValheimPerformanceEngine v1.3.1

ValheimPerformanceEngine.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Jobs.LowLevel.Unsafe;
using UnityEngine;
using UnityEngine.PostProcessing;
using UnityEngine.Scripting;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ValheimPerformanceEngine")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: AssemblyInformationalVersion("1.2.0")]
[assembly: AssemblyProduct("ValheimPerformanceEngine")]
[assembly: AssemblyTitle("ValheimPerformanceEngine")]
[assembly: AssemblyVersion("1.2.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[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 ValheimPerformanceEngine
{
	[BepInPlugin("com.filipenunes.valheimperformanceengine", "Valheim Performance Engine", "1.3.1")]
	public class PerformanceEnginePlugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.filipenunes.valheimperformanceengine";

		public const string PluginName = "Valheim Performance Engine";

		public const string PluginVersion = "1.3.1";

		public const string PluginAuthor = "Filipe Nunes";

		private Harmony m_harmony;

		public static int InstancedMaterialsCount;

		public static int FixedShadersCount;

		public static int WorkerThreadsConfigured;

		public static long SkippedCoverChecksCount;

		private float m_fpsTimer;

		private int m_fpsFrames;

		private float m_visualsTimer;

		private static bool m_nightVision;

		public static ConfigEntry<bool> EnableGlobalShaderResolver;

		public static ConfigEntry<bool> EnableGpuInstancing;

		public static ConfigEntry<bool> EnableCleanVisuals;

		public static ConfigEntry<KeyCode> NightVisionHotkey;

		public static ConfigEntry<KeyCode> TelemetryHotkey;

		private static PostProcessingBehaviour s_cachedBehaviour;

		private static Camera s_cachedCamera;

		public static PerformanceEnginePlugin Instance { get; private set; }

		public static ManualLogSource ModLog { get; private set; }

		public static float CurrentFPS { get; private set; }

		private void Awake()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			Instance = this;
			ModLog = ((BaseUnityPlugin)this).Logger;
			ModLog.LogInfo((object)"[Valheim Performance Engine] Initializing v1.3.1 by Filipe Nunes...");
			InitConfig();
			ApplyEngineUncap();
			VulkanShaderResolver.InitializeNativeShaders();
			try
			{
				m_harmony = new Harmony("com.filipenunes.valheimperformanceengine");
				m_harmony.PatchAll(Assembly.GetExecutingAssembly());
				ModLog.LogInfo((object)"[Valheim Performance Engine] Global Harmony patches applied successfully.");
			}
			catch (Exception arg)
			{
				ModLog.LogError((object)string.Format("[{0}] Failed to apply Harmony patches: {1}", "Valheim Performance Engine", arg));
			}
		}

		private void InitConfig()
		{
			EnableGlobalShaderResolver = ((BaseUnityPlugin)this).Config.Bind<bool>("Graphics.Shaders", "EnableGlobalShaderResolver", true, "Intercepta e substitui shaders DirectX incompatíveis com a plataforma Vulkan no Linux.");
			EnableGpuInstancing = ((BaseUnityPlugin)this).Config.Bind<bool>("Graphics.Optimization", "EnableGpuInstancing", true, "Habilita GPU Instancing automático em todos os materiais de peças e itens.");
			EnableCleanVisuals = ((BaseUnityPlugin)this).Config.Bind<bool>("Graphics.PostProcessing", "EnableCleanVisuals", true, "Remove desfoque, névoa pesada e melhora nitidez e claridade.");
			NightVisionHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Controls", "NightVisionHotkey", (KeyCode)288, "Tecla para alternar o modo Visão Noturna / Clareza Máxima.");
			TelemetryHotkey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Controls", "TelemetryHotkey", (KeyCode)289, "Tecla para exibir as métricas de performance no HUD.");
		}

		private void Start()
		{
			ApplyEngineUncap();
			if (EnableGpuInstancing.Value)
			{
				InstancingManager.ProcessAllMaterials();
			}
			if (EnableCleanVisuals.Value)
			{
				EnhanceVisuals();
			}
		}

		private void Update()
		{
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			m_fpsFrames++;
			m_fpsTimer += Time.unscaledDeltaTime;
			if (m_fpsTimer >= 1f)
			{
				CurrentFPS = (float)m_fpsFrames / m_fpsTimer;
				m_fpsFrames = 0;
				m_fpsTimer = 0f;
			}
			if (EnableCleanVisuals.Value)
			{
				m_visualsTimer += Time.unscaledDeltaTime;
				if (m_visualsTimer >= 5f)
				{
					m_visualsTimer = 0f;
					EnhanceVisuals();
				}
			}
			if (ZInput.GetKeyDown(NightVisionHotkey.Value, true))
			{
				m_nightVision = !m_nightVision;
				EnhanceVisuals();
				string text = (m_nightVision ? "[Performance Engine] Modo Clareza Máxima (Night Vision): ATIVADO (+75% Luz)" : "[Performance Engine] Modo Clareza Normal: ATIVADO (+38% Luz)");
				if ((Object)(object)MessageHud.instance != (Object)null)
				{
					MessageHud.instance.ShowMessage((MessageType)1, text, 0, (Sprite)null, false, true);
				}
			}
			if (ZInput.GetKeyDown(TelemetryHotkey.Value, true))
			{
				ShowTelemetry();
			}
		}

		public void ApplyEngineUncap()
		{
			try
			{
				Debug.unityLogger.filterLogType = (LogType)2;
				ICollection<ILogListener> listeners = Logger.Listeners;
				List<ILogListener> list = new List<ILogListener>();
				foreach (ILogListener item in listeners)
				{
					if (((object)item).GetType().Name.Contains("UnityLogListener"))
					{
						list.Add(item);
					}
				}
				foreach (ILogListener item2 in list)
				{
					listeners.Remove(item2);
					ModLog.LogInfo((object)("[Valheim Performance Engine] Removed " + ((object)item2).GetType().Name + " to stop Player.log I/O bottleneck."));
				}
			}
			catch (Exception ex)
			{
				ModLog.LogWarning((object)("[Valheim Performance Engine] Note on logger filter: " + ex.Message));
			}
			try
			{
				int num = (WorkerThreadsConfigured = (JobsUtility.JobWorkerCount = Math.Clamp(Environment.ProcessorCount / 3, 4, 8)));
				ModLog.LogInfo((object)string.Format("[{0}] Unity Jobs Worker Threads configured to {1} (balanced for Xeon).", "Valheim Performance Engine", num));
			}
			catch (Exception ex2)
			{
				ModLog.LogWarning((object)("[Valheim Performance Engine] Could not set JobsUtility.JobWorkerCount: " + ex2.Message));
			}
			try
			{
				Application.targetFrameRate = -1;
				QualitySettings.maxQueuedFrames = 2;
				QualitySettings.asyncUploadTimeSlice = 4;
				QualitySettings.asyncUploadBufferSize = 64;
				LightLod.m_shadowLimit = 2;
				LightLod.m_lightLimit = 25;
				ModLog.LogInfo((object)"[Valheim Performance Engine] Engine frame rate uncapped, queue optimized, LightLod shadows clamped to 2.");
			}
			catch (Exception ex3)
			{
				ModLog.LogWarning((object)("[Valheim Performance Engine] Error configuring QualitySettings: " + ex3.Message));
			}
			try
			{
				GarbageCollector.GCMode = (Mode)1;
				GarbageCollector.incrementalTimeSliceNanoseconds = 8000000uL;
				ModLog.LogInfo((object)"[Valheim Performance Engine] Incremental GC configured with 8ms time slice.");
			}
			catch (Exception ex4)
			{
				ModLog.LogWarning((object)("[Valheim Performance Engine] Error configuring GarbageCollector: " + ex4.Message));
			}
		}

		public static void EnhanceVisuals()
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: 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_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Color ambientLight = (m_nightVision ? new Color(0.28f, 0.28f, 0.35f) : new Color(0.16f, 0.16f, 0.2f));
				Color ambientLight2 = RenderSettings.ambientLight;
				if (((Color)(ref ambientLight2)).grayscale < ((Color)(ref ambientLight)).grayscale)
				{
					RenderSettings.ambientLight = ambientLight;
				}
				Camera main = Camera.main;
				if ((Object)(object)main != (Object)null && ((Object)(object)s_cachedCamera != (Object)(object)main || (Object)(object)s_cachedBehaviour == (Object)null))
				{
					s_cachedCamera = main;
					s_cachedBehaviour = ((Component)main).GetComponent<PostProcessingBehaviour>();
				}
				if ((Object)(object)s_cachedBehaviour == (Object)null && (Object)(object)GameCamera.instance != (Object)null)
				{
					s_cachedBehaviour = ((Component)GameCamera.instance).GetComponent<PostProcessingBehaviour>();
				}
				if (!((Object)(object)s_cachedBehaviour == (Object)null) && !((Object)(object)s_cachedBehaviour.profile == (Object)null))
				{
					PostProcessingProfile profile = s_cachedBehaviour.profile;
					((PostProcessingModel)profile.depthOfField).enabled = false;
					((PostProcessingModel)profile.motionBlur).enabled = false;
					((PostProcessingModel)profile.chromaticAberration).enabled = false;
					((PostProcessingModel)profile.grain).enabled = false;
					((PostProcessingModel)profile.vignette).enabled = false;
					((PostProcessingModel)profile.bloom).enabled = false;
					Settings settings = profile.colorGrading.settings;
					settings.basic.saturation = 1.18f;
					settings.basic.contrast = 1f;
					settings.basic.postExposure = (m_nightVision ? 0.75f : 0.38f);
					profile.colorGrading.settings = settings;
					((PostProcessingModel)profile.colorGrading).enabled = true;
				}
			}
			catch
			{
			}
		}

		public void ShowTelemetry()
		{
			int num = ((WearNTear.GetAllInstances() != null) ? WearNTear.GetAllInstances().Count : 0);
			string text = "[Performance Engine - Filipe Nunes]\n" + $"FPS: {CurrentFPS:F1} | Base Pieces: {num}\n" + $"GPU Instanced Materials: {InstancedMaterialsCount}\n" + $"Vulkan Shader Fallbacks: {FixedShadersCount}\n" + $"CPU Worker Threads: {WorkerThreadsConfigured}\n" + $"Skipped Cover Checks: {SkippedCoverChecksCount}\n" + "Clarity: Blur/DoF/Bloom OFF, GC Slice: 8ms";
			ModLog.LogInfo((object)text);
			if ((Object)(object)MessageHud.instance != (Object)null)
			{
				MessageHud.instance.ShowMessage((MessageType)1, text, 0, (Sprite)null, false, true);
			}
		}

		private void OnDestroy()
		{
			Harmony harmony = m_harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	public static class VulkanShaderResolver
	{
		private static Shader s_pieceShader;

		private static Shader s_creatureShader;

		private static Shader s_particleAlphaShader;

		private static Shader s_particleAdditiveShader;

		private static Shader s_standardShader;

		private static Shader s_playerShader;

		private static readonly Dictionary<string, Shader> s_nativeShaderCache = new Dictionary<string, Shader>(StringComparer.OrdinalIgnoreCase);

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

		private static bool s_initialized = false;

		public static void InitializeNativeShaders()
		{
			if (s_initialized)
			{
				return;
			}
			try
			{
				Shader[] array = Resources.FindObjectsOfTypeAll<Shader>();
				if (array != null)
				{
					Shader[] array2 = array;
					foreach (Shader val in array2)
					{
						if ((Object)(object)val != (Object)null && val.isSupported && !string.IsNullOrEmpty(((Object)val).name) && !s_nativeShaderCache.ContainsKey(((Object)val).name))
						{
							s_nativeShaderCache[((Object)val).name] = val;
						}
					}
				}
			}
			catch
			{
			}
			s_pieceShader = GetSupportedShader("Custom/Piece") ?? GetSupportedShader("Standard");
			s_creatureShader = GetSupportedShader("Custom/Creature") ?? s_pieceShader;
			s_playerShader = GetSupportedShader("Custom/Player") ?? s_pieceShader;
			s_particleAlphaShader = GetSupportedShader("Particles/Standard Unlit") ?? GetSupportedShader("Sprites/Default") ?? GetSupportedShader("UI/Default") ?? GetSupportedShader("Standard");
			s_particleAdditiveShader = GetSupportedShader("Particles/Standard Unlit") ?? s_particleAlphaShader;
			s_standardShader = GetSupportedShader("Standard") ?? s_pieceShader;
			if ((Object)(object)s_pieceShader != (Object)null)
			{
				s_initialized = true;
			}
		}

		public static Shader GetSupportedShader(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return null;
			}
			if (s_nativeShaderCache.TryGetValue(name, out var value) && (Object)(object)value != (Object)null && value.isSupported)
			{
				return value;
			}
			Shader val = Shader.Find(name);
			if ((Object)(object)val != (Object)null && val.isSupported)
			{
				s_nativeShaderCache[name] = val;
				return val;
			}
			return null;
		}

		public static Shader ClassifySemanticShader(string shaderName, string matName)
		{
			if (!s_initialized)
			{
				InitializeNativeShaders();
			}
			if (!string.IsNullOrEmpty(shaderName) && s_nativeShaderCache.TryGetValue(shaderName, out var value) && (Object)(object)value != (Object)null && value.isSupported)
			{
				return value;
			}
			if (shaderName.IndexOf("Additive", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Additive", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return s_particleAdditiveShader;
			}
			if (shaderName.IndexOf("Particle", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Particle", StringComparison.OrdinalIgnoreCase) >= 0 || shaderName.IndexOf("Alpha", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Smoke", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Fire", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Spark", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Flame", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return s_particleAlphaShader;
			}
			if (shaderName.IndexOf("Player", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Player", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Armor", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Chest", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Legs", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Helm", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Cape", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Pants", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return s_playerShader ?? s_pieceShader;
			}
			if (shaderName.IndexOf("Creature", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Creature", StringComparison.OrdinalIgnoreCase) >= 0 || matName.IndexOf("Monster", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return s_creatureShader;
			}
			if (shaderName.IndexOf("Rock", StringComparison.OrdinalIgnoreCase) >= 0 || shaderName.IndexOf("Piece", StringComparison.OrdinalIgnoreCase) >= 0 || shaderName.IndexOf("Tar", StringComparison.OrdinalIgnoreCase) >= 0 || shaderName.IndexOf("Rug", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				return s_pieceShader;
			}
			return s_pieceShader ?? s_playerShader ?? s_standardShader;
		}

		public static void FixMaterial(Material m)
		{
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: 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)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)m == (Object)null)
			{
				return;
			}
			int instanceID = ((Object)m).GetInstanceID();
			if (s_processedMaterials.Contains(instanceID))
			{
				return;
			}
			s_processedMaterials.Add(instanceID);
			if (!((Object)(object)m.shader == (Object)null) && m.shader.isSupported)
			{
				return;
			}
			string shaderName = (((Object)(object)m.shader != (Object)null) ? ((Object)m.shader).name : "");
			string matName = ((((Object)m).name != null) ? ((Object)m).name : "");
			Shader val = ClassifySemanticShader(shaderName, matName);
			if ((Object)(object)val == (Object)null || !val.isSupported)
			{
				val = Shader.Find("Custom/Piece") ?? Shader.Find("Standard") ?? Shader.Find("Particles/Standard Unlit");
			}
			if (!((Object)(object)val != (Object)null) || !val.isSupported)
			{
				return;
			}
			Texture val2 = null;
			Texture val3 = null;
			Color val4 = Color.white;
			bool flag = false;
			try
			{
				if (m.HasProperty("_MainTex"))
				{
					val2 = m.GetTexture("_MainTex");
				}
				if (m.HasProperty("_BumpMap"))
				{
					val3 = m.GetTexture("_BumpMap");
				}
				if (m.HasProperty("_Color"))
				{
					val4 = m.GetColor("_Color");
					flag = true;
				}
			}
			catch
			{
			}
			m.shader = val;
			try
			{
				if ((Object)(object)val2 != (Object)null && m.HasProperty("_MainTex"))
				{
					m.SetTexture("_MainTex", val2);
				}
				if ((Object)(object)val3 != (Object)null && m.HasProperty("_BumpMap"))
				{
					m.SetTexture("_BumpMap", val3);
				}
				if (flag && m.HasProperty("_Color"))
				{
					m.SetColor("_Color", val4);
				}
			}
			catch
			{
			}
			PerformanceEnginePlugin.FixedShadersCount++;
		}
	}
	public static class InstancingManager
	{
		private static readonly HashSet<int> ProcessedRenderers = new HashSet<int>();

		public static void ProcessRenderer(GameObject go)
		{
			if ((Object)(object)go == (Object)null)
			{
				return;
			}
			Renderer[] componentsInChildren = go.GetComponentsInChildren<Renderer>(true);
			if (componentsInChildren == null)
			{
				return;
			}
			Renderer[] array = componentsInChildren;
			foreach (Renderer val in array)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				int instanceID = ((Object)val).GetInstanceID();
				if (ProcessedRenderers.Contains(instanceID))
				{
					continue;
				}
				ProcessedRenderers.Add(instanceID);
				Material[] sharedMaterials = val.sharedMaterials;
				if (sharedMaterials == null)
				{
					continue;
				}
				Material[] array2 = sharedMaterials;
				foreach (Material val2 in array2)
				{
					if (!((Object)(object)val2 != (Object)null))
					{
						continue;
					}
					try
					{
						if (PerformanceEnginePlugin.EnableGpuInstancing.Value)
						{
							val2.enableInstancing = true;
							PerformanceEnginePlugin.InstancedMaterialsCount++;
						}
						if (PerformanceEnginePlugin.EnableGlobalShaderResolver.Value)
						{
							VulkanShaderResolver.FixMaterial(val2);
						}
					}
					catch
					{
					}
				}
			}
		}

		public static void ProcessAllMaterials()
		{
			try
			{
				VulkanShaderResolver.InitializeNativeShaders();
				Material[] array = Resources.FindObjectsOfTypeAll<Material>();
				if (array == null)
				{
					return;
				}
				Material[] array2 = array;
				foreach (Material val in array2)
				{
					if (!((Object)(object)val != (Object)null))
					{
						continue;
					}
					try
					{
						if (PerformanceEnginePlugin.EnableGpuInstancing.Value)
						{
							val.enableInstancing = true;
							PerformanceEnginePlugin.InstancedMaterialsCount++;
						}
						if (PerformanceEnginePlugin.EnableGlobalShaderResolver.Value)
						{
							VulkanShaderResolver.FixMaterial(val);
						}
					}
					catch
					{
					}
				}
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(Shader), "Find")]
	public static class ShaderFindGlobalPatch
	{
		private static bool Prefix(string name, ref Shader __result)
		{
			if (!PerformanceEnginePlugin.EnableGlobalShaderResolver.Value || string.IsNullOrEmpty(name))
			{
				return true;
			}
			if (name.StartsWith("Legacy Shaders/", StringComparison.OrdinalIgnoreCase) || name.IndexOf("DX11", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("D3D", StringComparison.OrdinalIgnoreCase) >= 0)
			{
				Shader val = VulkanShaderResolver.ClassifySemanticShader(name, "");
				if ((Object)(object)val != (Object)null && val.isSupported)
				{
					__result = val;
					return false;
				}
			}
			return true;
		}
	}
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	public static class MaterialShaderConstructorPatch
	{
		private static void Postfix(Material __instance)
		{
			if (PerformanceEnginePlugin.EnableGlobalShaderResolver.Value && (Object)(object)__instance != (Object)null)
			{
				VulkanShaderResolver.FixMaterial(__instance);
			}
		}
	}
	[HarmonyPatch(typeof(ZNetScene), "CreateObject")]
	public static class ZNetSceneCreateObjectPatch
	{
		private static void Postfix(GameObject __result)
		{
			if ((Object)(object)__result != (Object)null)
			{
				InstancingManager.ProcessRenderer(__result);
			}
		}
	}
	[HarmonyPatch(typeof(AssetBundle), "LoadAsset_Internal")]
	public static class AssetBundleLoadAssetPatch
	{
		private static void Postfix(ref Object __result)
		{
			if (__result == (Object)null)
			{
				return;
			}
			Object obj = __result;
			GameObject val = (GameObject)(object)((obj is GameObject) ? obj : null);
			if (val != null)
			{
				InstancingManager.ProcessRenderer(val);
				return;
			}
			Object obj2 = __result;
			Material val2 = (Material)(object)((obj2 is Material) ? obj2 : null);
			if (val2 != null)
			{
				VulkanShaderResolver.FixMaterial(val2);
			}
		}
	}
	[HarmonyPatch(typeof(AssetBundle), "LoadAssetWithSubAssets_Internal")]
	public static class AssetBundleLoadSubAssetsPatch
	{
		private static void Postfix(ref Object[] __result)
		{
			if (__result == null)
			{
				return;
			}
			for (int i = 0; i < __result.Length; i++)
			{
				Object val = __result[i];
				if (val == (Object)null)
				{
					continue;
				}
				GameObject val2 = (GameObject)(object)((val is GameObject) ? val : null);
				if (val2 != null)
				{
					InstancingManager.ProcessRenderer(val2);
					continue;
				}
				Material val3 = (Material)(object)((val is Material) ? val : null);
				if (val3 != null)
				{
					VulkanShaderResolver.FixMaterial(val3);
				}
			}
		}
	}
	[HarmonyPatch(typeof(ZNetScene), "Awake")]
	public static class ZNetSceneInstancingPatch
	{
		private static void Postfix(ZNetScene __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			try
			{
				if (__instance.m_prefabs != null)
				{
					foreach (GameObject prefab in __instance.m_prefabs)
					{
						InstancingManager.ProcessRenderer(prefab);
					}
				}
				InstancingManager.ProcessAllMaterials();
				PerformanceEnginePlugin.EnhanceVisuals();
				ManualLogSource modLog = PerformanceEnginePlugin.ModLog;
				if (modLog != null)
				{
					modLog.LogInfo((object)string.Format("[{0}] GPU Instancing injected into {1} materials ({2} Vulkan shader fallbacks applied).", "Valheim Performance Engine", PerformanceEnginePlugin.InstancedMaterialsCount, PerformanceEnginePlugin.FixedShadersCount));
				}
			}
			catch (Exception ex)
			{
				ManualLogSource modLog2 = PerformanceEnginePlugin.ModLog;
				if (modLog2 != null)
				{
					modLog2.LogWarning((object)("[Valheim Performance Engine] Instancing injection error: " + ex.Message));
				}
			}
		}
	}
	[HarmonyPatch(typeof(ObjectDB), "Awake")]
	public static class ObjectDBInstancingPatch
	{
		private static void Postfix(ObjectDB __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			try
			{
				if (__instance.m_items != null)
				{
					foreach (GameObject item in __instance.m_items)
					{
						InstancingManager.ProcessRenderer(item);
					}
				}
				InstancingManager.ProcessAllMaterials();
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "Awake")]
	public static class FejdStartupInstancingPatch
	{
		private static void Postfix()
		{
			try
			{
				InstancingManager.ProcessAllMaterials();
			}
			catch
			{
			}
		}
	}
	[HarmonyPatch(typeof(WearNTear), "UpdateCover")]
	public static class WearNTearUpdateCoverPatch
	{
		private static bool Prefix(WearNTear __instance, bool ___m_inAshlands)
		{
			if (__instance.m_noRoofWear && !___m_inAshlands)
			{
				PerformanceEnginePlugin.SkippedCoverChecksCount++;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(WearNTear), "UpdateAshlandsMaterialValues")]
	public static class WearNTearUpdateAshlandsPatch
	{
		private static bool Prefix(WearNTear __instance, float ___m_ashDamageTime, float ___m_burnDamageTime, float ___m_lavaTimer, bool ___m_inAshlands)
		{
			if (!___m_inAshlands && ___m_ashDamageTime <= 0f && ___m_burnDamageTime <= 0f && ___m_lavaTimer <= 0f)
			{
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(LightLod), "Awake")]
	public static class LightLodAwakePatch
	{
		private static void Postfix(LightLod __instance)
		{
			LightLod.m_shadowLimit = 2;
			LightLod.m_lightLimit = 25;
			if ((Object)(object)__instance != (Object)null)
			{
				__instance.m_shadowDistance = 15f;
			}
		}
	}
	[HarmonyPatch(typeof(LightLod), "UpdateLights")]
	public static class LightLodUpdateLightsPatch
	{
		private static void Prefix()
		{
			if (LightLod.m_shadowLimit != 2)
			{
				LightLod.m_shadowLimit = 2;
				LightLod.m_lightLimit = 25;
			}
		}
	}
	[HarmonyPatch(typeof(ObjectDB), "Awake")]
	[HarmonyPriority(800)]
	public static class ObjectDBProfilingPrefix
	{
		public static Stopwatch Stopwatch = new Stopwatch();

		private static void Prefix()
		{
			Stopwatch.Restart();
			PerformanceEnginePlugin.ModLog.LogMessage((object)"[PROFILER] >>> ObjectDB.Awake STARTED...");
		}
	}
	[HarmonyPatch(typeof(ObjectDB), "Awake")]
	[HarmonyPriority(0)]
	public static class ObjectDBProfilingPostfix
	{
		private static void Postfix()
		{
			ObjectDBProfilingPrefix.Stopwatch.Stop();
			long elapsedMilliseconds = ObjectDBProfilingPrefix.Stopwatch.ElapsedMilliseconds;
			PerformanceEnginePlugin.ModLog.LogMessage((object)$"[PROFILER] <<< ObjectDB.Awake FINISHED in {elapsedMilliseconds} ms ({(double)elapsedMilliseconds / 1000.0:F2}s).");
		}
	}
	[HarmonyPatch(typeof(ZNetScene), "Awake")]
	[HarmonyPriority(800)]
	public static class ZNetSceneProfilingPrefix
	{
		public static Stopwatch Stopwatch = new Stopwatch();

		private static void Prefix()
		{
			Stopwatch.Restart();
			PerformanceEnginePlugin.ModLog.LogMessage((object)"[PROFILER] >>> ZNetScene.Awake STARTED...");
		}
	}
	[HarmonyPatch(typeof(ZNetScene), "Awake")]
	[HarmonyPriority(0)]
	public static class ZNetSceneProfilingPostfix
	{
		private static void Postfix()
		{
			ZNetSceneProfilingPrefix.Stopwatch.Stop();
			long elapsedMilliseconds = ZNetSceneProfilingPrefix.Stopwatch.ElapsedMilliseconds;
			PerformanceEnginePlugin.ModLog.LogMessage((object)$"[PROFILER] <<< ZNetScene.Awake FINISHED in {elapsedMilliseconds} ms ({(double)elapsedMilliseconds / 1000.0:F2}s).");
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "Awake")]
	[HarmonyPriority(0)]
	public static class StartupBenchmarkReportPatch
	{
		private static void Postfix()
		{
			PerformanceEnginePlugin.ModLog.LogMessage((object)"==================================================================");
			PerformanceEnginePlugin.ModLog.LogMessage((object)"[PROFILER REPORT] Menu Inicial (FejdStartup) Alcançado!");
			PerformanceEnginePlugin.ModLog.LogMessage((object)$"[PROFILER REPORT] Tempo Total da Unity desde o Boot: {Time.realtimeSinceStartup:F2} segundos.");
			PerformanceEnginePlugin.ModLog.LogMessage((object)$"[PROFILER REPORT] Total Shaders Auto-Corrigidos para Vulkan: {PerformanceEnginePlugin.FixedShadersCount}");
			PerformanceEnginePlugin.ModLog.LogMessage((object)"==================================================================");
		}
	}
}