Decompiled source of TextureToolbox v1.5.0

BepInEx/plugins/TextureToolboxV2.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
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: AssemblyTitle("TextureToolboxSimplified")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TextureToolboxSimplified")]
[assembly: AssemblyCopyright("Copyright ©  2026")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("96735e38-c955-454c-824d-2af01409d200")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
public static class FolderBootstrap
{
	public static bool Ensure(string parent, string folder, out string path, string readme = null)
	{
		path = null;
		bool result = false;
		try
		{
			string text = Path.Combine(parent, folder);
			if (!Directory.Exists(text))
			{
				Directory.CreateDirectory(text);
				result = true;
			}
			path = text;
		}
		catch (Exception)
		{
			try
			{
				path = Path.Combine(Paths.PluginPath, folder);
			}
			catch
			{
				path = folder;
			}
			try
			{
				Directory.CreateDirectory(path);
			}
			catch
			{
			}
		}
		if (!string.IsNullOrEmpty(readme))
		{
			try
			{
				string path2 = Path.Combine(path, "README.txt");
				if (!File.Exists(path2))
				{
					File.WriteAllText(path2, readme);
				}
			}
			catch
			{
			}
		}
		return result;
	}
}
namespace TextureToolbox;

public static class ImageVault
{
	public class Entry
	{
		public string Name;

		public string RawName;

		public int PropId;

		public bool Atlas;

		public Texture2D Tex;

		public byte[] Bytes;

		public DateTime Stamp;
	}

	private static Dictionary<string, Entry> _byKey = new Dictionary<string, Entry>(StringComparer.OrdinalIgnoreCase);

	private static readonly Dictionary<string, List<Texture>> _liveByName = new Dictionary<string, List<Texture>>(StringComparer.OrdinalIgnoreCase);

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

	private static readonly ConcurrentQueue<(string file, byte[] data)> _decodeQueue = new ConcurrentQueue<(string, byte[])>();

	private static readonly HashSet<string> _seenKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

	private static readonly List<string> _dropScratch = new List<string>(16);

	private static bool _diskDone = true;

	private static readonly int MainTexId = Shader.PropertyToID("_MainTex");

	private static readonly int BaseMapId = Shader.PropertyToID("_BaseMap");

	private static bool _finishing;

	public static bool Loading => !_diskDone || !_decodeQueue.IsEmpty;

	public static int Count => _byKey.Count;

	private static bool ParseFileName(string fileName, out string baseName, out string rawName, out int propId, out bool atlas)
	{
		string text = Path.GetFileNameWithoutExtension(fileName);
		atlas = false;
		if (text.StartsWith("ATLAS-", StringComparison.OrdinalIgnoreCase) || text.StartsWith("ATLAS_", StringComparison.OrdinalIgnoreCase))
		{
			atlas = true;
			text = text.Substring(6);
		}
		rawName = text.Trim();
		propId = MainTexId;
		int num = text.LastIndexOf('_');
		if (num > 0 && num < text.Length - 1)
		{
			string key = text.Substring(num + 1);
			if (Plugin.SuffixProps.TryGetValue(key, out var value))
			{
				propId = value;
				text = text.Substring(0, num);
			}
		}
		baseName = text.Trim();
		return baseName.Length > 0;
	}

	public static void ReloadAll()
	{
		_diskDone = false;
		string dir = Plugin.ImagePath;
		Task.Run(delegate
		{
			List<(string, byte[], DateTime)> list = new List<(string, byte[], DateTime)>();
			try
			{
				string[] files = Directory.GetFiles(dir, "*.png", SearchOption.AllDirectories);
				foreach (string text in files)
				{
					try
					{
						list.Add((text, File.ReadAllBytes(text), File.GetLastWriteTimeUtc(text)));
					}
					catch (Exception ex)
					{
						Plugin.Log.LogWarning((object)("CustomImages: read failed for " + text + ": " + ex.Message));
					}
				}
			}
			catch (Exception ex2)
			{
				Plugin.Log.LogWarning((object)("CustomImages: scan failed: " + ex2.Message));
			}
			_seenKeys.Clear();
			foreach (var item in list)
			{
				if (ParseFileName(Path.GetFileName(item.Item1), out var baseName, out var rawName, out var propId, out var _))
				{
					string text2 = baseName + "|" + propId;
					_seenKeys.Add(text2);
					_seenKeys.Add(rawName + "|" + propId);
					if (!_byKey.TryGetValue(text2, out var value) || !(value.Stamp == item.Item3) || !((Object)(object)value.Tex != (Object)null))
					{
						_decodeQueue.Enqueue((item.Item1, item.Item2));
					}
				}
			}
			_diskDone = true;
		});
	}

	public static void Tick()
	{
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Expected O, but got Unknown
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		if (_decodeQueue.IsEmpty)
		{
			return;
		}
		Stopwatch stopwatch = Stopwatch.StartNew();
		(string, byte[]) result;
		while (stopwatch.ElapsedMilliseconds < 5 && _decodeQueue.TryDequeue(out result))
		{
			if (!ParseFileName(Path.GetFileName(result.Item1), out var baseName, out var rawName, out var propId, out var atlas))
			{
				continue;
			}
			try
			{
				Texture2D val = new Texture2D(2, 2, (TextureFormat)4, true);
				if (!ImageConversion.LoadImage(val, result.Item2))
				{
					Object.Destroy((Object)(object)val);
					continue;
				}
				((Object)val).name = baseName + (atlas ? " [atlas]" : "");
				((Texture)val).filterMode = Plugin.TextureFilterMode.Value;
				if (Plugin.CompressTextures.Value)
				{
					val.Compress(false);
				}
				val.Apply(true, true);
				OptimizationCore.CustomTextureIDs.Add(((Object)val).GetInstanceID());
				string text = baseName + "|" + propId;
				Entry value = new Entry
				{
					Name = baseName,
					RawName = rawName,
					PropId = propId,
					Atlas = atlas,
					Tex = val,
					Bytes = result.Item2,
					Stamp = File.GetLastWriteTimeUtc(result.Item1)
				};
				if (_byKey.TryGetValue(text, out var value2) && (Object)(object)value2.Tex != (Object)null)
				{
					Object.Destroy((Object)(object)value2.Tex);
				}
				_byKey[text] = value;
				string text2 = rawName + "|" + propId;
				if (!string.Equals(text2, text, StringComparison.OrdinalIgnoreCase))
				{
					_byKey[text2] = value;
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("CustomImages: decode failed " + result.Item1 + ": " + ex.Message));
			}
		}
		if (_diskDone && _decodeQueue.IsEmpty)
		{
			FinishReload();
		}
	}

	private static void FinishReload()
	{
		if (_finishing)
		{
			return;
		}
		_finishing = true;
		_dropScratch.Clear();
		foreach (KeyValuePair<string, Entry> item in _byKey)
		{
			if (!_seenKeys.Contains(item.Key))
			{
				_dropScratch.Add(item.Key);
			}
		}
		for (int i = 0; i < _dropScratch.Count; i++)
		{
			if (_byKey.TryGetValue(_dropScratch[i], out var value))
			{
				if ((Object)(object)value.Tex != (Object)null)
				{
					OptimizationCore.CustomTextureIDs.Remove(((Object)value.Tex).GetInstanceID());
					Object.Destroy((Object)(object)value.Tex);
					value.Tex = null;
				}
				_byKey.Remove(_dropScratch[i]);
			}
		}
		ApplyPendingAtlases();
		OptimizationCore.ProcessedMaterialIDs.Clear();
		OptimizationCore.MatSlotToCustomTexture.Clear();
		OptimizationCore.TextureIDToCustomTexture.Clear();
		RendererManager.TriggerImmediateSweep();
		Plugin.Log.LogMessage((object)$"Texture vault: {_byKey.Count} textures ready.");
		_finishing = false;
	}

	public static void RegisterLive(Texture orig)
	{
		if (!((Object)(object)orig == (Object)null))
		{
			string text = OptimizationCore.CleanName(((Object)orig).name);
			if (!_liveByName.TryGetValue(text, out var value))
			{
				value = new List<Texture>(2);
				_liveByName[text] = value;
			}
			if (!value.Contains(orig))
			{
				value.Add(orig);
			}
			TryApplyAtlasTo(orig, text);
		}
	}

	public static bool TryMatch(Texture orig, int slotId, out Entry e)
	{
		e = null;
		if ((Object)(object)orig == (Object)null || _byKey.Count == 0)
		{
			return false;
		}
		string text = OptimizationCore.CleanName(((Object)orig).name);
		if (_byKey.TryGetValue(text + "|" + slotId, out e))
		{
			return true;
		}
		if (slotId == MainTexId || slotId == BaseMapId)
		{
			Dictionary<string, Entry> byKey = _byKey;
			int mainTexId = MainTexId;
			if (byKey.TryGetValue(text + "|" + mainTexId, out e))
			{
				return true;
			}
			Dictionary<string, Entry> byKey2 = _byKey;
			mainTexId = BaseMapId;
			if (byKey2.TryGetValue(text + "|" + mainTexId, out e))
			{
				return true;
			}
		}
		return false;
	}

	public static bool TryMatch(Texture orig, out Entry e)
	{
		e = null;
		if ((Object)(object)orig == (Object)null)
		{
			return false;
		}
		string text = OptimizationCore.CleanName(((Object)orig).name);
		Dictionary<string, Entry> byKey = _byKey;
		int mainTexId = MainTexId;
		if (byKey.TryGetValue(text + "|" + mainTexId, out e))
		{
			return true;
		}
		Dictionary<string, Entry> byKey2 = _byKey;
		mainTexId = BaseMapId;
		if (byKey2.TryGetValue(text + "|" + mainTexId, out e))
		{
			return true;
		}
		return false;
	}

	private static void TryApplyAtlasTo(Texture orig, string cleanName)
	{
		int instanceID = ((Object)orig).GetInstanceID();
		if (_atlasApplied.Contains(instanceID))
		{
			return;
		}
		foreach (KeyValuePair<string, Entry> item in _byKey)
		{
			Entry value = item.Value;
			if (!value.Atlas || (!string.Equals(value.Name, cleanName, StringComparison.OrdinalIgnoreCase) && !string.Equals(value.RawName, cleanName, StringComparison.OrdinalIgnoreCase)))
			{
				continue;
			}
			Texture2D val = (Texture2D)(object)((orig is Texture2D) ? orig : null);
			if (val != null)
			{
				try
				{
					ImageConversion.LoadImage(val, value.Bytes);
					val.Apply(true, false);
					_atlasApplied.Add(instanceID);
					Plugin.Log.LogInfo((object)$"ATLAS '{value.Name}' rewritten in place on texture id {instanceID} ({((Texture)val).width}x{((Texture)val).height}).");
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("ATLAS '" + value.Name + "' in-place failed: " + ex.Message + " — falling back to slot swap."));
				}
			}
		}
	}

	private static void ApplyPendingAtlases()
	{
		foreach (KeyValuePair<string, List<Texture>> item in _liveByName)
		{
			for (int num = item.Value.Count - 1; num >= 0; num--)
			{
				Texture val = item.Value[num];
				if ((Object)(object)val == (Object)null)
				{
					item.Value.RemoveAt(num);
				}
				else
				{
					TryApplyAtlasTo(val, item.Key);
				}
			}
		}
	}

	public static void OnSceneUnload()
	{
		_liveByName.Clear();
		_atlasApplied.Clear();
	}
}
public static class OptimizationCore
{
	public static readonly Dictionary<int, string> TextureSlots = new Dictionary<int, string>();

	public static readonly HashSet<int> EmissionSlots = new HashSet<int>();

	public static readonly HashSet<int> NormalSlots = new HashSet<int>();

	public static readonly HashSet<int> ProcessedMaterialIDs = new HashSet<int>();

	public static readonly Dictionary<long, Texture2D> MatSlotToCustomTexture = new Dictionary<long, Texture2D>();

	public static readonly Dictionary<int, Texture2D> TextureIDToCustomTexture = new Dictionary<int, Texture2D>();

	public static readonly HashSet<int> CustomTextureIDs = new HashSet<int>();

	public static void Init()
	{
		RegisterSlot("_MainTex");
		RegisterSlot("_BaseMap");
		int item = RegisterSlot("_EmissionMap");
		int item2 = RegisterSlot("_EmissionTex");
		EmissionSlots.Add(item);
		EmissionSlots.Add(item2);
		int item3 = RegisterSlot("_BumpMap");
		NormalSlots.Add(item3);
		RegisterSlot("_DetailAlbedoMap");
		RegisterSlot("_MetallicGlossMap");
		RegisterSlot("_SpecGlossMap");
		RegisterSlot("_OcclusionMap");
		RegisterSlot("_ParallaxMap");
		SceneManager.sceneLoaded += OnSceneLoaded;
	}

	private static int RegisterSlot(string name)
	{
		int num = Shader.PropertyToID(name);
		TextureSlots[num] = name;
		return num;
	}

	private static void OnSceneLoaded(Scene scene, LoadSceneMode mode)
	{
		ProcessedMaterialIDs.Clear();
		MatSlotToCustomTexture.Clear();
		ImageVault.OnSceneUnload();
		RendererManager.TriggerImmediateSweep();
	}

	public static void ClearAllCaches()
	{
		ProcessedMaterialIDs.Clear();
		MatSlotToCustomTexture.Clear();
		TextureIDToCustomTexture.Clear();
		CustomTextureIDs.Clear();
	}

	public static string CleanName(string name)
	{
		if (string.IsNullOrEmpty(name))
		{
			return name;
		}
		if (name.EndsWith(" (Instance)"))
		{
			return name.Substring(0, name.Length - 11);
		}
		if (name.EndsWith("(Instance)"))
		{
			return name.Substring(0, name.Length - 10);
		}
		return name;
	}
}
public static class MaterialProcessor
{
	public static void Process(Material mat)
	{
		if (!Object.op_Implicit((Object)(object)mat))
		{
			return;
		}
		int instanceID = ((Object)mat).GetInstanceID();
		if (OptimizationCore.ProcessedMaterialIDs.Contains(instanceID))
		{
			return;
		}
		string text = null;
		foreach (KeyValuePair<int, string> textureSlot in OptimizationCore.TextureSlots)
		{
			int key = textureSlot.Key;
			if (!mat.HasProperty(key))
			{
				continue;
			}
			Texture texture = mat.GetTexture(key);
			if (!Object.op_Implicit((Object)(object)texture))
			{
				continue;
			}
			long key2 = ((long)instanceID << 32) | (uint)key;
			if (OptimizationCore.MatSlotToCustomTexture.TryGetValue(key2, out var value))
			{
				if ((Object)(object)value != (Object)null)
				{
					ApplyTextureToMaterial(mat, key, value);
				}
				continue;
			}
			ImageVault.RegisterLive(texture);
			if (text == null)
			{
				text = OptimizationCore.CleanName(((Object)mat).name);
			}
			if (ImageVault.TryMatch(texture, key, out var e))
			{
				if (e.Atlas)
				{
					OptimizationCore.MatSlotToCustomTexture[key2] = null;
					continue;
				}
				ApplyTextureToMaterial(mat, key, e.Tex);
				OptimizationCore.MatSlotToCustomTexture[key2] = e.Tex;
			}
			else
			{
				OptimizationCore.MatSlotToCustomTexture[key2] = null;
			}
		}
		OptimizationCore.ProcessedMaterialIDs.Add(instanceID);
	}

	private static void ApplyTextureToMaterial(Material mat, int slotID, Texture2D tex)
	{
		//IL_0028: 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)
		mat.SetTexture(slotID, (Texture)(object)tex);
		if (OptimizationCore.EmissionSlots.Contains(slotID))
		{
			mat.EnableKeyword("_EMISSION");
			mat.globalIlluminationFlags = (MaterialGlobalIlluminationFlags)(mat.globalIlluminationFlags & -5);
		}
		else if (OptimizationCore.NormalSlots.Contains(slotID))
		{
			mat.EnableKeyword("_NORMALMAP");
		}
	}
}
public static class RendererHandler
{
	private static readonly List<Material> _matsBuffer = new List<Material>(16);

	public static void Process(Renderer renderer)
	{
		if (!Object.op_Implicit((Object)(object)renderer))
		{
			return;
		}
		renderer.GetSharedMaterials(_matsBuffer);
		for (int i = 0; i < _matsBuffer.Count; i++)
		{
			if (Object.op_Implicit((Object)(object)_matsBuffer[i]))
			{
				MaterialProcessor.Process(_matsBuffer[i]);
			}
		}
		_matsBuffer.Clear();
	}
}
public static class RendererManager
{
	private static bool _forceSweepNow;

	public static void TriggerImmediateSweep()
	{
		_forceSweepNow = true;
	}

	public static IEnumerator FastSelfHealingSweep()
	{
		yield return (object)new WaitForSeconds(1f);
		while (true)
		{
			if (!_forceSweepNow)
			{
				yield return (object)new WaitForSeconds(Mathf.Max(Plugin.SweepInterval.Value, 1f));
			}
			_forceSweepNow = false;
			Renderer[] allRenderers = Object.FindObjectsOfType<Renderer>();
			int batch = 0;
			foreach (Renderer r in allRenderers)
			{
				if (Object.op_Implicit((Object)(object)r))
				{
					RendererHandler.Process(r);
				}
				int num = batch + 1;
				batch = num;
				if (num >= 50)
				{
					batch = 0;
					yield return null;
				}
			}
		}
	}
}
internal static class Hooks
{
	private static readonly List<Renderer> _rendererBuffer = new List<Renderer>(128);

	[HarmonyPatch(typeof(Object), "Instantiate", new Type[] { typeof(Object) })]
	[HarmonyPostfix]
	public static void Instantiate1(Object __result)
	{
		ProcessSpawn(__result);
	}

	[HarmonyPatch(typeof(Object), "Instantiate", new Type[]
	{
		typeof(Object),
		typeof(Transform)
	})]
	[HarmonyPostfix]
	public static void Instantiate2(Object __result)
	{
		ProcessSpawn(__result);
	}

	[HarmonyPatch(typeof(Object), "Instantiate", new Type[]
	{
		typeof(Object),
		typeof(Transform),
		typeof(bool)
	})]
	[HarmonyPostfix]
	public static void Instantiate3(Object __result)
	{
		ProcessSpawn(__result);
	}

	[HarmonyPatch(typeof(Object), "Instantiate", new Type[]
	{
		typeof(Object),
		typeof(Vector3),
		typeof(Quaternion)
	})]
	[HarmonyPostfix]
	public static void Instantiate4(Object __result)
	{
		ProcessSpawn(__result);
	}

	[HarmonyPatch(typeof(Object), "Instantiate", new Type[]
	{
		typeof(Object),
		typeof(Vector3),
		typeof(Quaternion),
		typeof(Transform)
	})]
	[HarmonyPostfix]
	public static void Instantiate5(Object __result)
	{
		ProcessSpawn(__result);
	}

	private static void ProcessSpawn(Object result)
	{
		if (result == (Object)null || ImageVault.Count == 0)
		{
			return;
		}
		GameObject val = (GameObject)(object)((result is GameObject) ? result : null);
		if ((Object)(object)val == (Object)null)
		{
			Component val2 = (Component)(object)((result is Component) ? result : null);
			if (val2 != null)
			{
				val = val2.gameObject;
			}
		}
		if (!((Object)(object)val == (Object)null))
		{
			val.GetComponentsInChildren<Renderer>(true, _rendererBuffer);
			for (int i = 0; i < _rendererBuffer.Count; i++)
			{
				RendererHandler.Process(_rendererBuffer[i]);
			}
			_rendererBuffer.Clear();
		}
	}

	[HarmonyPatch(typeof(Material), "SetTexture", new Type[]
	{
		typeof(int),
		typeof(Texture)
	})]
	[HarmonyPrefix]
	public static void SetTextureInt(Material __instance, int nameID, ref Texture value)
	{
		if (!((Object)(object)value == (Object)null) && !OptimizationCore.CustomTextureIDs.Contains(((Object)value).GetInstanceID()))
		{
			ImageVault.RegisterLive(value);
			long key = ((long)((Object)__instance).GetInstanceID() << 32) | (uint)nameID;
			if (ImageVault.TryMatch(value, nameID, out var e) && !e.Atlas)
			{
				value = (Texture)(object)e.Tex;
				OptimizationCore.MatSlotToCustomTexture[key] = e.Tex;
				HandleKeywords(__instance, nameID);
			}
		}
	}

	[HarmonyPatch(typeof(Material), "SetTexture", new Type[]
	{
		typeof(string),
		typeof(Texture)
	})]
	[HarmonyPrefix]
	public static void SetTextureString(Material __instance, string name, ref Texture value)
	{
		SetTextureInt(__instance, Shader.PropertyToID(name), ref value);
	}

	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	[HarmonyPrefix]
	public static void MainTextureSetter(Material __instance, ref Texture value)
	{
		SetTextureInt(__instance, Shader.PropertyToID("_MainTex"), ref value);
	}

	private static void HandleKeywords(Material mat, int slotID)
	{
		if (OptimizationCore.EmissionSlots.Contains(slotID))
		{
			mat.EnableKeyword("_EMISSION");
		}
		else if (OptimizationCore.NormalSlots.Contains(slotID))
		{
			mat.EnableKeyword("_NORMALMAP");
		}
	}

	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	[HarmonyPostfix]
	public static void SetMaterial(Material value)
	{
		if (Object.op_Implicit((Object)(object)value))
		{
			MaterialProcessor.Process(value);
		}
	}

	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	[HarmonyPostfix]
	public static void SetSharedMaterial(Material value)
	{
		if (Object.op_Implicit((Object)(object)value))
		{
			MaterialProcessor.Process(value);
		}
	}

	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	[HarmonyPostfix]
	public static void SetMaterials(Material[] value)
	{
		if (value == null)
		{
			return;
		}
		for (int i = 0; i < value.Length; i++)
		{
			if (Object.op_Implicit((Object)(object)value[i]))
			{
				MaterialProcessor.Process(value[i]);
			}
		}
	}

	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	[HarmonyPostfix]
	public static void SetSharedMaterials(Material[] value)
	{
		if (value == null)
		{
			return;
		}
		for (int i = 0; i < value.Length; i++)
		{
			if (Object.op_Implicit((Object)(object)value[i]))
			{
				MaterialProcessor.Process(value[i]);
			}
		}
	}

	[HarmonyPatch(typeof(CanvasRenderer), "SetTexture")]
	[HarmonyPrefix]
	public static void SetUITexture(ref Texture texture)
	{
		if (!((Object)(object)texture == (Object)null))
		{
			ImageVault.RegisterLive(texture);
			if (ImageVault.TryMatch(texture, out var e) && !e.Atlas)
			{
				texture = (Texture)(object)e.Tex;
			}
		}
	}

	[HarmonyPatch(typeof(Resources), "Load", new Type[]
	{
		typeof(string),
		typeof(Type)
	})]
	[HarmonyPostfix]
	public static void ResourcesLoad(ref Object __result)
	{
		Object obj = __result;
		Texture val = (Texture)(object)((obj is Texture) ? obj : null);
		if (val != null)
		{
			ImageVault.RegisterLive(val);
			if (ImageVault.TryMatch(val, out var e) && !e.Atlas)
			{
				__result = (Object)(object)e.Tex;
			}
		}
	}

	[HarmonyPatch(typeof(AssetBundle), "LoadAsset", new Type[]
	{
		typeof(string),
		typeof(Type)
	})]
	[HarmonyPostfix]
	public static void AssetBundleLoad(ref Object __result)
	{
		Object obj = __result;
		Texture val = (Texture)(object)((obj is Texture) ? obj : null);
		if (val != null)
		{
			ImageVault.RegisterLive(val);
			if (ImageVault.TryMatch(val, out var e) && !e.Atlas)
			{
				__result = (Object)(object)e.Tex;
			}
		}
	}
}
[BepInPlugin("com.thehalfbunny.texturetoolbox", "TextureToolbox", "2.1.0")]
public class Plugin : BaseUnityPlugin
{
	public static ManualLogSource Log;

	public static Plugin Instance;

	public static readonly Dictionary<string, int> SuffixProps = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
	{
		["maintex"] = Shader.PropertyToID("_MainTex"),
		["albedo"] = Shader.PropertyToID("_MainTex"),
		["diffuse"] = Shader.PropertyToID("_MainTex"),
		["basemap"] = Shader.PropertyToID("_BaseMap"),
		["basecolor"] = Shader.PropertyToID("_BaseMap"),
		["emissive"] = Shader.PropertyToID("_EmissionMap"),
		["emission"] = Shader.PropertyToID("_EmissionMap"),
		["normal"] = Shader.PropertyToID("_BumpMap"),
		["normalmap"] = Shader.PropertyToID("_BumpMap"),
		["bump"] = Shader.PropertyToID("_BumpMap"),
		["metallic"] = Shader.PropertyToID("_MetallicGlossMap"),
		["metallicgloss"] = Shader.PropertyToID("_MetallicGlossMap"),
		["specular"] = Shader.PropertyToID("_SpecGlossMap"),
		["specgloss"] = Shader.PropertyToID("_SpecGlossMap"),
		["occlusion"] = Shader.PropertyToID("_OcclusionMap"),
		["ao"] = Shader.PropertyToID("_OcclusionMap"),
		["height"] = Shader.PropertyToID("_ParallaxMap"),
		["parallax"] = Shader.PropertyToID("_ParallaxMap"),
		["detail"] = Shader.PropertyToID("_DetailAlbedoMap"),
		["detailalbedo"] = Shader.PropertyToID("_DetailAlbedoMap")
	};

	public static ConfigEntry<bool> CompressTextures;

	public static ConfigEntry<FilterMode> TextureFilterMode;

	public static ConfigEntry<float> SweepInterval;

	public static ConfigEntry<KeyboardShortcut> ReloadKey;

	public static string ImagePath;

	private void Awake()
	{
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		Instance = this;
		CompressTextures = ((BaseUnityPlugin)this).Config.Bind<bool>("Performance", "CompressTextures", true, "Compresses images in VRAM. Greatly reduces memory usage but increases initial load time slightly.");
		TextureFilterMode = ((BaseUnityPlugin)this).Config.Bind<FilterMode>("Visuals", "TextureFilterMode", (FilterMode)0, "Point = Pixelated/Retro. Bilinear/Trilinear = Smooth.");
		SweepInterval = ((BaseUnityPlugin)this).Config.Bind<float>("Performance", "SweepInterval", 10f, "How often (in seconds) the Janitor sweeps for unpatched renderers. Set higher for better performance.");
		ReloadKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Hotkeys", "ReloadTextures", new KeyboardShortcut((KeyCode)291, Array.Empty<KeyCode>()), "Hot-reload CustomImages (new/changed/deleted files, reapplies instantly)");
		string path;
		bool flag = FolderBootstrap.Ensure(Paths.ConfigPath, "CustomImages", out path, "TextureToolbox — drop PNGs here.\r\n  Name.png            = replaces texture 'Name' in its main/albedo slot\r\n  Name_Emissive.png   = replaces it in the emission slot\r\n  ATLAS-Name.png      = rewrites the original texture IN PLACE\r\n                        (atlas-safe: sprites/UI keep working)\r\nProperty suffixes: _MainTex _Albedo _BaseMap _BaseColor _Emissive\r\n  _Emission _Normal _Bump _Metallic _Specular _Occlusion _AO\r\n  _Height _Detail (dashes in names are fine — suffix read off the end)\r\nHotkey: F10 reloads this folder (rebindable in TextureToolbox.cfg)\r\n");
		ImagePath = path;
		if (flag)
		{
			Log.LogInfo((object)("Created CustomImages folder: " + ImagePath));
		}
		OptimizationCore.Init();
		ImageVault.ReloadAll();
		((MonoBehaviour)this).StartCoroutine(RendererManager.FastSelfHealingSweep());
		Harmony val = new Harmony("com.thehalfbunny.texturetoolbox.hooks");
		try
		{
			val.PatchAll(typeof(Hooks));
			Log.LogInfo((object)"TextureToolbox loaded!");
		}
		catch (Exception ex)
		{
			Log.LogError((object)("Harmony Failure: " + ex.Message));
		}
	}

	private void Update()
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: 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_0034: Unknown result type (might be due to invalid IL or missing references)
		KeyboardShortcut value = ReloadKey.Value;
		if (((KeyboardShortcut)(ref value)).IsDown())
		{
			if (!ImageVault.Loading)
			{
				ManualLogSource log = Log;
				value = ReloadKey.Value;
				log.LogWarning((object)(((KeyboardShortcut)(ref value)).Serialize() + " pressed: hot-reloading fuckass textures.."));
				ImageVault.ReloadAll();
			}
			else
			{
				Log.LogWarning((object)"Calm the fuck down, it's loading..");
			}
		}
		ImageVault.Tick();
	}
}