using System;
using System.Collections;
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.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Logging;
using Discord;
using HarmonyLib;
using Sandbox;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Video;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("TexturePatcher")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("TexturePatcher")]
[assembly: AssemblyTitle("TexturePatcher")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace TexturePatcher
{
public static class Cheats
{
public static string GetCheatName(string cheat)
{
return cheat switch
{
"ultrakill.keep-enabled" => "Mantener activo",
"ultrakill.spawner-arm" => "Brazo Spawner",
"ultrakill.teleport-menu" => "Teletransporte",
"ultrakill.full-bright" => "Brillo al máximo",
"ultrakill.invincibility" => "Invencibilidad",
"ultrakill.noclip" => "Noclip",
"ultrakill.flight" => "Volar",
"ultrakill.infinite-wall-jumps" => "Saltos de pared infinitos",
"ultrakill.no-weapon-cooldown" => "Sin enfriamiento de arma",
"ultrakill.infinite-power-ups" => "Potenciadores infinitos",
"ultrakill.blind-enemies" => "Enemigos ciegos",
"ultrakill.enemy-hate-enemy" => "Los enemigos se atacan entre sí",
"ultrakill.enemy-ignore-player" => "Los enemigos ignoran al jugador",
"ultrakill.disable-enemy-spawns" => "Desactivar spawn enemigo",
"ultrakill.invincible-enemies" => "Enemigos invencibles",
"ultrakill.kill-all-enemies" => "Matar a todos los enemigos",
"ultrakill.sandbox.quick-save" => "Guardado rápido",
"ultrakill.sandbox.quick-load" => "Carga rápida",
"ultrakill.sandbox.save-menu" => "Organizar saves",
"ultrakill.sandbox.clear" => "Limpiar",
"ultrakill.sandbox.rebuild-nav" => "Navegación enemigo",
"ultrakill.sandbox.snapping" => "Chasquido",
"ultrakill.sandbox.physics" => "Física",
"ultrakill.clash-mode" => "Modo Clash",
"ultrakill.hide-weapons" => "Ocultar armas",
"ultrakill.hide-ui" => "Ocultar UI",
"ultrakill.ghost-drone-mode" => "Drones embrujados",
_ => cheat,
};
}
}
[HarmonyPatch(typeof(CheatsManager))]
public static class CheatsManagerPatch
{
private const string Navmesh1 = "NAVMESH DESACTUALIZADO";
private const string Navmesh2 = "(Reconstruir la navegación en el menú de trucos)";
[HarmonyPatch("RebuildMenu")]
[HarmonyPostfix]
public static void RebuildMenu_Postfix()
{
GameObject val = GameObject.Find("Canvas");
if (!((Object)(object)val == (Object)null))
{
Transform obj = val.transform.Find("Cheat Menu/Cheats Manager/Scroll View/Viewport");
GameObject val2 = ((obj != null) ? ((Component)obj).gameObject : null);
if (!((Object)(object)val2 == (Object)null))
{
}
}
}
[HarmonyPatch("RenderCheatsInfo")]
[HarmonyPrefix]
public static bool RenderCheatsInfo_MyPatch(CheatsManager __instance, Dictionary<string, List<ICheat>> ___allRegisteredCheats)
{
StringBuilder stringBuilder = new StringBuilder();
SandboxNavmesh instance = MonoSingleton<SandboxNavmesh>.Instance;
if (instance != null && instance.isDirty)
{
stringBuilder.AppendLine("<color=red>NAVMESH DESACTUALIZADO\n<size=12>(Reconstruir la navegación en el menú de trucos)</size></color>\n");
}
if (__instance.GetCheatState("ultrakill.spawner-arm"))
{
stringBuilder.AppendLine("<color=#C2D7FF>Brazo spawner en el slot 6</color>\n");
}
foreach (KeyValuePair<string, List<ICheat>> ___allRegisteredCheat in ___allRegisteredCheats)
{
foreach (ICheat item in ___allRegisteredCheat.Value)
{
if (item.IsActive)
{
string text = MonoSingleton<CheatBinds>.Instance.ResolveCheatKey(item.Identifier);
string text2 = (string.IsNullOrEmpty(text) ? " " : text.ToUpper());
string cheatName = Cheats.GetCheatName(item.Identifier);
stringBuilder.AppendLine("[<color=orange>" + text2 + "</color>] <color=white>" + cheatName + "</color>");
}
}
}
MonoSingleton<CheatsController>.Instance.cheatsInfo.text = stringBuilder.ToString();
return false;
}
}
public static class Core
{
private static bool _hudPatched;
private static CoreCoroutineRunner _runner;
private static Coroutine _patchCoroutine;
public static void HandleSceneSwitch(Scene scene, ref GameObject canvas)
{
//IL_0061: Unknown result type (might be due to invalid IL or missing references)
//IL_0089: Unknown result type (might be due to invalid IL or missing references)
//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
if (_patchCoroutine != null && (Object)(object)_runner != (Object)null)
{
((MonoBehaviour)_runner).StopCoroutine(_patchCoroutine);
_patchCoroutine = null;
}
string name = ((Scene)(ref scene)).name;
if (!(name == "Intro") && !(name == "Bootstrap"))
{
_hudPatched = false;
GameObject val = (canvas = GetInactiveRootObject(scene, "Canvas"));
if ((Object)(object)val == (Object)null)
{
Debug.LogWarning((object)"[TexturePatcher] Canvas no encontrado.");
StartPostInit(scene);
}
else if (name == "Main Menu")
{
PatchFrontEnd(val);
}
else
{
StartPostInit(scene);
}
}
}
private static void StartPostInit(Scene scene)
{
//IL_0034: 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_001c: Expected O, but got Unknown
if ((Object)(object)_runner == (Object)null)
{
GameObject val = new GameObject("TexturePatcher.CoreRunner");
Object.DontDestroyOnLoad((Object)(object)val);
_runner = val.AddComponent<CoreCoroutineRunner>();
}
_patchCoroutine = ((MonoBehaviour)_runner).StartCoroutine(PostInitPatches(scene));
}
private static IEnumerator PostInitPatches(Scene scene)
{
//IL_0007: Unknown result type (might be due to invalid IL or missing references)
//IL_0008: Unknown result type (might be due to invalid IL or missing references)
yield return (object)new WaitForSecondsRealtime(0.3f);
if (_hudPatched || !((Scene)(ref scene)).IsValid() || !((Scene)(ref scene)).isLoaded)
{
_patchCoroutine = null;
yield break;
}
GameObject canvasObj = GetInactiveRootObject(scene, "Canvas");
if ((Object)(object)canvasObj == (Object)null)
{
Debug.LogWarning((object)"[TexturePatcher] Canvas todavía no existe.");
_patchCoroutine = null;
yield break;
}
try
{
Debug.Log((object)"[TexturePatcher] Aplicando MiscHUDPatch.");
MiscHUDPatch.PatchMisc(canvasObj);
_hudPatched = true;
}
catch (Exception ex)
{
Debug.LogError((object)("[TexturePatcher] Error parcheando HUD: " + ex));
}
_patchCoroutine = null;
}
public static void PatchFrontEnd(GameObject frontEnd)
{
}
private static GameObject GetInactiveRootObject(Scene scene, string objectName)
{
//IL_0092: Unknown result type (might be due to invalid IL or missing references)
//IL_0098: Invalid comparison between Unknown and I4
//IL_00be: Unknown result type (might be due to invalid IL or missing references)
//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
if (!((Scene)(ref scene)).IsValid() || !((Scene)(ref scene)).isLoaded)
{
return null;
}
GameObject[] rootGameObjects = ((Scene)(ref scene)).GetRootGameObjects();
foreach (GameObject val in rootGameObjects)
{
if ((Object)(object)val != (Object)null && ((Object)val).name == objectName)
{
return val;
}
}
GameObject[] array = Resources.FindObjectsOfTypeAll<GameObject>();
foreach (GameObject val2 in array)
{
if (!((Object)(object)val2 == (Object)null) && (int)((Object)val2).hideFlags <= 0 && !((Object)(object)val2.transform.parent != (Object)null))
{
Scene scene2 = val2.scene;
if (((Scene)(ref scene2)).handle == ((Scene)(ref scene)).handle && ((Object)val2).name == objectName)
{
return val2;
}
}
}
return null;
}
public static GameObject GetGameObjectChild(GameObject parent, string childName)
{
object result;
if (parent == null)
{
result = null;
}
else
{
Transform obj = parent.transform.Find(childName);
result = ((obj != null) ? ((Component)obj).gameObject : null);
}
return (GameObject)result;
}
public static TextMeshProUGUI GetTextMeshProUGUI(GameObject obj)
{
return (obj != null) ? obj.GetComponent<TextMeshProUGUI>() : null;
}
public static string GetCurrentSceneName()
{
return SceneHelper.CurrentScene;
}
}
internal sealed class CoreCoroutineRunner : MonoBehaviour
{
}
[HarmonyPatch(typeof(DiscordController), "SendActivity")]
public static class PatchDiscordActivity
{
public static class LevelNames
{
private static readonly Dictionary<string, string> LevelMap = new Dictionary<string, string>
{
{ "mag.indulgence.thedeathofparadigm", "I-1: LA MUERTE DEL PARADIGMA" },
{ "mag.indulgence.level2", "I-2: SI NO EXISTIERA EL TRUENO" },
{ "mag.indulgence.thehallofpain", "CRÉDITOS" },
{ "raifulostfieldsenvyb", "E-1: DONDE YACÍA EL ORO" },
{ "raifuenvypalaceforbundle", "E-2: PALACIO DE AGUJAS CINERÉS" },
{ "raifucastlemaniacthereal", "E-3: ENROQUE MANÍACO" },
{ "raifueverystarintheskyreal", "E-4: POR CADA ESTRELLA NOCTURNA" },
{ "main menu", "MENÚ PRINCIPAL" },
{ "tutorial", "TUTORIAL" },
{ "endless", "THE CYBER GRIND" },
{ "uk_construct", "SANDBOX" },
{ "creditsmuseum2", "SALON DE LA FAMA: LOS DEVS DE ULTRAKILL" },
{ "0-1", "0-1: EN EL FUEGO" },
{ "0-2", "0-2: LA PICADORA DE CARNE" },
{ "0-3", "0-3: MÁS ABAJO" },
{ "0-4", "0-4: EJÉRCITO DE UNA MÁQUINA" },
{ "0-5", "0-5: CERBERO" },
{ "0-s", "0-S: ALGO MALO" },
{ "1-1", "1-1: CORAZÓN DEL AMANECER" },
{ "1-2", "1-2: EL MUNDO EN LLAMAS" },
{ "1-3", "1-3: SALONES DE RESTOS SAGRADOS" },
{ "1-4", "1-4: CLAIR DE LUNE" },
{ "1-s", "1-S: EL INGENIO" },
{ "2-1", "2-1: EL CORTA LAZOS" },
{ "2-2", "2-2: MUERTE A 20,000 VOLTIOS" },
{ "2-3", "2-3: CERTERO ATAQUE AL CORAZÓN" },
{ "2-4", "2-4: LA CORTE DEL REY CADÁVER" },
{ "2-s", "2-S: UNA CANCIÓN DE AMOR TOTALMENTE IMPERFECTA" },
{ "3-1", "3-1: EL VIENTRE DE LA BESTIA" },
{ "3-2", "3-2: EN CARNE Y HUESO" },
{ "4-1", "4-1: ESCLAVOS DE PODER" },
{ "4-2", "4-2: MALDITO SEA EL SOL" },
{ "4-3", "4-3: UN DISPARO A CIEGAS" },
{ "4-4", "4-4: CLAIR DE SOLEIL" },
{ "4-s", "4-S: LUCHA DE BRANDICOOTS" },
{ "5-1", "5-1: EN EL DESPERTAR DE POSEIDÓN" },
{ "5-2", "5-2: OLAS DE UN MAR SIN ESTRELLAS" },
{ "5-3", "5-3: BARCO DE NECIOS" },
{ "5-4", "5-4: LEVIATÁN" },
{ "5-s", "5-S: SÓLO DIGO MAÑANA" },
{ "6-1", "6-1: LLANTO DEL LLORÓN" },
{ "6-2", "6-2: ESTÉTICAS DEL ODIO" },
{ "7-1", "7-1: JARDÍN DE SENDEROS BIFURCADOS" },
{ "7-2", "7-2: ILUMINA LA NOCHE" },
{ "7-3", "7-3: SIN SONIDO, SIN MEMORIA" },
{ "7-4", "7-4: ...COMO ANTENAS HACIA EL CIELO" },
{ "7-s", "7-S: EL INFIERNO NO TIENE FURIA" },
{ "8-1", "8-1: MARAVILLAS DEL DESGARRO" },
{ "8-2", "8-2: A TRAVÉS DEL ESPEJO" },
{ "8-3", "8-3: BUCLE DE DESINTEGRACIÓN" },
{ "8-4", "8-4: VUELO FINAL" },
{ "p-1", "P-1: ESPÍRITU DE SUPERVIVIENTE" },
{ "p-2", "P-2: EL ESPERAR DEL MUNDO" },
{ "p-3", "P-3: ???" },
{ "9-1", "9-1: ???" },
{ "9-2", "9-2: ???" },
{ "0-e", "0-E: ESTE CALOR, UN CALOR MALIGNO" },
{ "1-e", "1-E: ...Y CAYERON LAS CENIZAS" },
{ "2-e", "2-E: ???" },
{ "3-e", "3-E: ???" },
{ "4-e", "4-E: ???" },
{ "5-e", "5-E: ???" },
{ "6-e", "6-E: ???" },
{ "7-e", "7-E: ???" },
{ "8-e", "8-E: ???" },
{ "9-e", "9-E: ???" },
{ "intermission", "???" },
{ "earlyaccessend", "???" }
};
public static string GetDiscordLevelName(string missionName)
{
if (string.IsNullOrEmpty(missionName))
{
return "Desconocido";
}
missionName = missionName.ToLowerInvariant();
foreach (KeyValuePair<string, string> item in LevelMap)
{
if (missionName.Contains(item.Key))
{
return item.Value;
}
}
return missionName;
}
}
[Serializable]
[CompilerGenerated]
private sealed class <>c
{
public static readonly <>c <>9 = new <>c();
public static UpdateActivityHandler <>9__2_0;
internal void <SendActivity_MyPatch>b__2_0(Result _)
{
}
}
private static readonly Dictionary<string, string> DiffNamesMap = new Dictionary<string, string>
{
{ "HARMLESS", "INOFENSIVO" },
{ "LENIENT", "INDULGENTE" },
{ "STANDARD", "ESTÁNDAR" },
{ "VIOLENT", "VIOLENTO" },
{ "BRUTAL", "BRUTAL" },
{ "ULTRAKILL MUST DIE", "ULTRAKILL DEBE MORIR" }
};
private static readonly Dictionary<string, string> StyleNamesMap = new Dictionary<string, string>
{
{ "Destructive", "DESTRUCTIVO" },
{ "Chaotic", "CAÓTICO" },
{ "Brutal", "BRUTAL" },
{ "Anarchic", "ANÁRQUICO" },
{ "Supreme", "SUPREMO" },
{ "SSadistic", "SSÁDICO" },
{ "SSShitstorm", "SSSUBLIME" },
{ "ULTRAKILL", "ULTRAKILL" }
};
[HarmonyPrefix]
public static bool SendActivity_MyPatch(DiscordController __instance, Activity ___cachedActivity, RankIcon[] ___rankIcons, ActivityManager ___activityManager)
{
//IL_002d: Unknown result type (might be due to invalid IL or missing references)
//IL_0138: Unknown result type (might be due to invalid IL or missing references)
//IL_0139: Unknown result type (might be due to invalid IL or missing references)
//IL_0185: Unknown result type (might be due to invalid IL or missing references)
//IL_019a: Unknown result type (might be due to invalid IL or missing references)
//IL_019f: Unknown result type (might be due to invalid IL or missing references)
//IL_01a5: Expected O, but got Unknown
if (___activityManager == null)
{
return false;
}
try
{
string currentSceneName = GetCurrentSceneName();
if (currentSceneName != "endless")
{
string[] array = ___cachedActivity.Details?.Split(new char[1] { ' ' });
if (array != null && array.Length > 1)
{
if (array[0] == "STYLE:")
{
___cachedActivity.Details = "ESTILO: " + array[1];
}
else if (array[0] == "WAVE:")
{
___cachedActivity.Details = "OLEADA: " + array[1];
}
}
}
else
{
___cachedActivity.Details = string.Empty;
}
if (currentSceneName == "Main Menu")
{
___cachedActivity.State = "MENÚ PRINCIPAL";
}
else
{
int num = MonoSingleton<PrefsManager>.Instance.GetInt("difficulty", 0);
string text = MonoSingleton<PresenceController>.Instance.diffNames[num];
if (DiffNamesMap.TryGetValue(text, out var value))
{
text = value;
}
___cachedActivity.State = "DIFICULTAD: " + text;
}
string smallText = ___cachedActivity.Assets.SmallText;
if (!string.IsNullOrEmpty(smallText) && StyleNamesMap.TryGetValue(smallText, out var value2))
{
___cachedActivity.Assets.SmallText = value2;
}
___cachedActivity.Assets.LargeText = LevelNames.GetDiscordLevelName(currentSceneName);
Activity val = ___cachedActivity;
object obj = <>c.<>9__2_0;
if (obj == null)
{
UpdateActivityHandler val2 = delegate
{
};
<>c.<>9__2_0 = val2;
obj = (object)val2;
}
___activityManager.UpdateActivity(val, (UpdateActivityHandler)obj);
return false;
}
catch (Exception arg)
{
Debug.LogWarning((object)$"Error en PatchDiscordActivity: {arg}");
return false;
}
}
public static string GetCurrentSceneName()
{
return SceneHelper.CurrentScene;
}
}
[HarmonyPatch(typeof(FinalRank), "SetInfo")]
public static class LocalizeFinalRankInfo
{
[HarmonyPrefix]
public static bool SetInfo_MyPatch(int restarts, bool damage, bool majorUsed, bool cheatsUsed, FinalRank __instance, ref bool ___noRestarts, ref bool ___majorAssists, ref bool ___noDamage)
{
StringBuilder stringBuilder = new StringBuilder();
int num = 1;
if (!damage)
{
num++;
}
if (majorUsed)
{
num++;
}
if (cheatsUsed)
{
num++;
}
if (cheatsUsed)
{
stringBuilder.AppendLine("- <color=#44FF45>TRUCOS USADOS</color>");
}
if (majorUsed)
{
stringBuilder.AppendLine("- <color=#4C99E6>AYUDAS MAYORES USADAS</color>");
___majorAssists = true;
}
if (restarts == 0)
{
if (num >= 3)
{
stringBuilder.AppendLine("+ SIN REINICIOS");
}
else
{
stringBuilder.AppendLine("+ SIN REINICIOS\n (+500<color=orange>P</color>)");
}
___noRestarts = true;
}
else
{
stringBuilder.AppendLine($"- <color=red>{restarts}</color> REINICIOS");
}
if (!damage)
{
if (num >= 3)
{
stringBuilder.AppendLine("+ <color=orange>SIN DAÑOS</color>");
}
else
{
stringBuilder.AppendLine("+ <color=orange>SIN DAÑOS</color>\n (+5,000<color=orange>P</color>)");
}
___noDamage = true;
}
if ((Object)(object)__instance.extraInfo != (Object)null)
{
__instance.extraInfo.text = stringBuilder.ToString();
}
return false;
}
}
[HarmonyPatch(typeof(CrateCounter), "CoinsToPoints")]
public static class LocalizeCoinTranslation
{
private const string TargetSceneHash = "388594c020ef7c240afc673f062e6425";
[HarmonyPrefix]
public static bool CoinsToPoints_MyPatch(CrateCounter __instance, ref int ___savedCoins)
{
//IL_0001: Unknown result type (might be due to invalid IL or missing references)
//IL_0006: Unknown result type (might be due to invalid IL or missing references)
Scene activeScene = SceneManager.GetActiveScene();
if (((Scene)(ref activeScene)).name == "388594c020ef7c240afc673f062e6425")
{
int num = ___savedCoins * 100;
GameProgressSaver.AddMoney(num);
string arg = StatsManager.DivideMoney(num);
string text = $"<color=grey>TRANSACCIÓN COMPLETA:</color> {___savedCoins} MONEDAS <color=orange>=></color> {arg}<color=orange>P</color>";
MonoSingleton<HudMessageReceiver>.Instance.SendHudMessage(text, "", "", 0, false, false, true);
___savedCoins = 0;
}
return false;
}
}
public static class MiscHUDPatch
{
public static void PatchMisc(GameObject canvasObj)
{
if (!((Object)(object)canvasObj == (Object)null))
{
GameObject child = GetChild(GetChild(GetChild(canvasObj, "Crosshair Filler"), "AltHud"), "Filler");
GameObject child2 = GetChild(GetChild(GetChild(canvasObj, "Crosshair Filler"), "AltHud (2)"), "Filler");
if ((Object)(object)child != (Object)null)
{
SetText(GetChild(GetChild(child, "Health"), "Title"), "SALUD");
SetText(GetChild(GetChild(child, "Stamina"), "Title"), "RESISTENCIA");
SetText(GetChild(GetChild(child, "Weapon"), "Title"), "ARMA");
SetText(GetChild(GetChild(child, "Arm"), "Title"), "BRAZO");
SetText(GetChild(GetChild(child, "RailcannonMeter (1)"), "Title"), "RAILCANNON");
SetText(GetChild(GetChild(child, "Speedometer"), "Title"), "VELOCIDAD");
}
if ((Object)(object)child2 != (Object)null)
{
SetText(GetChild(GetChild(child2, "Health (1)"), "Title"), "SALUD");
SetText(GetChild(GetChild(child2, "Stamina (1)"), "Title"), "RESISTENCIA");
SetText(GetChild(GetChild(child2, "Weapon (1)"), "Title"), "ARMA");
SetText(GetChild(GetChild(child2, "Arm (1)"), "Title"), "BRAZO");
SetText(GetChild(GetChild(child2, "RailcannonMeter (2)"), "Title"), "RAILCANNON");
SetText(GetChild(GetChild(child2, "Speedometer"), "Title"), "VELOCIDAD");
}
Debug.Log((object)"[TexturePatcher] Classic HUD parcheado correctamente.");
}
}
private static GameObject GetChild(GameObject parent, string childName)
{
if ((Object)(object)parent == (Object)null)
{
return null;
}
Transform val = parent.transform.Find(childName);
return ((Object)(object)val != (Object)null) ? ((Component)val).gameObject : null;
}
private static void SetText(GameObject obj, string text)
{
if (!((Object)(object)obj == (Object)null))
{
TextMeshProUGUI component = obj.GetComponent<TextMeshProUGUI>();
if ((Object)(object)component != (Object)null)
{
((TMP_Text)component).text = text;
}
}
}
}
[BepInPlugin("com.lukah.texturepatcher", "Texture Patcher", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
internal static ManualLogSource LoggerInstance;
private static Harmony _harmony;
internal static Plugin Instance { get; private set; }
private void Awake()
{
//IL_0034: Unknown result type (might be due to invalid IL or missing references)
//IL_003e: Expected O, but got Unknown
Instance = this;
LoggerInstance = ((BaseUnityPlugin)this).Logger;
LoggerInstance.LogInfo((object)"[TexturePatcher] Plugin iniciado correctamente.");
Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
_harmony = new Harmony("com.lukah.texturepatcher");
ApplyHarmonyPatchesIndividually();
try
{
VideoPatcher.Initialize();
LoggerInstance.LogInfo((object)"[TexturePatcher] VideoPatcher inicializado correctamente.");
}
catch (Exception ex)
{
LoggerInstance.LogError((object)("[TexturePatcher] Error inicializando VideoPatcher:\n" + ex));
}
LoggerInstance.LogInfo((object)"[TexturePatcher] Inicialización completada.");
}
private void ApplyHarmonyPatchesIndividually()
{
Assembly executingAssembly = Assembly.GetExecutingAssembly();
Type[] types = executingAssembly.GetTypes();
foreach (Type type in types)
{
if (!(type == typeof(Plugin)) && HasHarmonyPatchAttribute(type))
{
try
{
_harmony.CreateClassProcessor(type).Patch();
}
catch (Exception ex)
{
LoggerInstance.LogError((object)("[TexturePatcher] ERROR en Harmony: " + type.FullName + "\n" + ex));
}
}
}
}
private static bool HasHarmonyPatchAttribute(Type type)
{
return type.GetCustomAttributes(typeof(HarmonyPatch), inherit: true).Length != 0;
}
}
[HarmonyPatch(typeof(StatsDisplay), "UpdateDisplay")]
public static class StatsPatchclass
{
[HarmonyPostfix]
public static void StatsPostfix(StatsDisplay __instance, TMP_Text ___textContent)
{
if (!((Object)(object)SteamController.Instance == (Object)null))
{
SandboxStats sandboxStats = SteamController.Instance.GetSandboxStats();
string arg = "TOTAL DE CAJAS CONSTRUIDAS";
string arg2 = "TOTAL DE ACCESORIOS COLOCADOS";
string arg3 = "TOTAL DE ENEMIGOS GENERADOS";
string arg4 = "TIEMPO TOTAL EN SANDBOX";
___textContent.text = $"<color=orange>{sandboxStats.brushesBuilt}</color> - {arg}\n" + $"<color=orange>{sandboxStats.propsSpawned}</color> - {arg2}\n" + $"<color=orange>{sandboxStats.enemiesSpawned}</color> - {arg3}\n" + $"<color=orange>{sandboxStats.hoursSpend:F1}h</color> - {arg4}\n";
}
}
}
public static class LevelNames
{
[HarmonyPatch(typeof(SaveSlotMenu))]
public static class SlotLevelAndDifficultyPatch
{
[HarmonyPatch("UpdateSlotState")]
[HarmonyPostfix]
public static void UpdateSlotState_Postfix(SlotRowPanel targetPanel, SlotData data)
{
targetPanel.stateLabel.text = BuildSlotText(data.exists, data.highestLvlNumber, data.highestDifficulty);
}
private static string BuildSlotText(bool exists, int highestLvlNumber, int highestDifficulty)
{
if (!exists)
{
return "SLOT VACÍO";
}
string text = MonoSingleton<PresenceController>.Instance.diffNames[highestDifficulty] switch
{
"HARMLESS" => "INOFENSIVO",
"LENIENT" => "INDULGENTE",
"STANDARD" => "ESTÁNDAR",
"VIOLENT" => "VIOLENTO",
"BRUTAL" => "BRUTAL",
"ULTRAKILL MUST DIE" => "ULTRAKILL DEBE MORIR",
_ => "DIFICULTAD DESCONOCIDA",
};
return GetLevelName(highestLvlNumber) + " " + ((highestLvlNumber <= 0) ? string.Empty : ("(" + text + ")"));
}
}
public static string GetLevelName(int missionNum, string levelname = "None")
{
return missionNum switch
{
0 => "MENÚ PRINCIPAL",
1 => "0-1: EN EL FUEGO",
2 => "0-2: LA PICADORA DE CARNE",
3 => "0-3: MÁS ABAJO",
4 => "0-4: EJÉRCITO DE UNA MÁQUINA",
5 => "0-5: CERBERO",
6 => "1-1: CORAZÓN DEL AMANECER",
7 => "1-2: EL MUNDO EN LLAMAS",
8 => "1-3: SALONES DE RESTOS SAGRADOS",
9 => "1-4: CLAIR DE LUNE",
10 => "2-1: EL CORTA LAZOS",
11 => "2-2: MUERTE A 20,000 VOLTIOS",
12 => "2-3: CERTERO ATAQUE AL CORAZÓN",
13 => "2-4: LA CORTE DEL REY CADÁVER",
14 => "3-1: EL VIENTRE DE LA BESTIA",
15 => "3-2: EN CARNE Y HUESO",
16 => "4-1: ESCLAVOS DE PODER",
17 => "4-2: MALDITO SEA EL SOL",
18 => "4-3: UN DISPARO A CIEGAS",
19 => "4-4: CLAIR DE SOLEIL",
20 => "5-1: EN EL DESPERTAR DE POSEIDÓN",
21 => "5-2: OLAS DE UN MAR SIN ESTRELLAS",
22 => "5-3: BARCO DE NECIOS",
23 => "5-4: LEVIATÁN",
24 => "6-1: LLANTO DEL LLORÓN",
25 => "6-2: ESTÉTICAS DEL ODIO",
26 => "7-1: JARDÍN DE SENDEROS BIFURCADOS",
27 => "7-2: ILUMINA LA NOCHE",
28 => "7-3: SIN SONIDO, SIN MEMORIA",
29 => "7-4: ...COMO ANTENAS HACIA EL CIELO",
30 => "8-1: MARAVILLAS DEL DESGARRO",
31 => "8-2: A TRAVÉS DEL ESPEJO",
32 => "8-3: BUCLE DE DESINTEGRACIÓN",
33 => "8-4: VUELO FINAL",
34 => "9-1: ???",
35 => "9-2: ???",
100 => "0-E: ESTE CALOR, UN CALOR MALIGNO",
101 => "1-E: ...Y CAYERON LAS CENIZAS",
102 => "2-E: ???",
103 => "3-E: ???",
104 => "4-E: ???",
105 => "5-E: ???",
106 => "6-E: ???",
107 => "7-E: ???",
108 => "8-E: ???",
109 => "9-E: ???",
666 => "P-1: ESPÍRITU DE SUPERVIVIENTE",
667 => "P-2: EL ESPERAR DEL MUNDO",
668 => "P-3: ???",
_ => levelname,
};
}
}
[HarmonyPatch(typeof(GunColorTypeGetter), "OnEnable")]
public static class GunColorTypeShopPatch
{
[HarmonyPostfix]
public static void OnEnablePostfix(GunColorTypeGetter __instance, TMP_Text[] ___templateTexts)
{
for (int i = 1; i < 5; i++)
{
if (GameProgressSaver.GetTotalSecretsFound() < GunColorController.requiredSecrets[i])
{
___templateTexts[i].text = "ORBES DE ALMA: " + GameProgressSaver.GetTotalSecretsFound() + " / " + GunColorController.requiredSecrets[i];
}
}
}
}
[HarmonyPatch(typeof(Speedometer), "FixedUpdate")]
public static class SpeedometerPatch
{
[HarmonyPrefix]
public static bool FixedUpdate_Prefix(TimeSince ___lastUpdate, bool ___classicVersion, TextMeshProUGUI ___textMesh, int ___type)
{
//IL_0045: Unknown result type (might be due to invalid IL or missing references)
//IL_004a: Unknown result type (might be due to invalid IL or missing references)
//IL_0062: Unknown result type (might be due to invalid IL or missing references)
//IL_0067: Unknown result type (might be due to invalid IL or missing references)
//IL_006c: Unknown result type (might be due to invalid IL or missing references)
//IL_0071: Unknown result type (might be due to invalid IL or missing references)
//IL_0089: Unknown result type (might be due to invalid IL or missing references)
//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
float num = 0f;
string arg = "";
if (!___classicVersion)
{
Vector3 val;
switch (___type)
{
case 0:
return false;
case 1:
val = MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(true);
num = ((Vector3)(ref val)).magnitude;
arg = "u";
break;
case 2:
val = Vector3.ProjectOnPlane(MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(true), Vector3.up);
num = ((Vector3)(ref val)).magnitude;
arg = "hu";
break;
case 3:
num = Mathf.Abs(MonoSingleton<PlayerTracker>.Instance.GetPlayerVelocity(true).y);
arg = "vu";
break;
}
if (TimeSince.op_Implicit(___lastUpdate) > 0.064f)
{
((TMP_Text)___textMesh).text = $"VELOCIDAD: {num:0.00} {arg}/s";
___lastUpdate = TimeSince.op_Implicit(0f);
}
return false;
}
return true;
}
}
public static class StyleBonusStrings
{
private static Dictionary<string, string> BonusDictionary;
private static HashSet<string> HiddenBonuses;
private static Dictionary<string, string> DynamicTranslations;
static StyleBonusStrings()
{
BonusDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "ultrakill.airslam", "<color=#00ffff>IMPACTO AÉREO</color>" },
{ "ultrakill.airshot", "<color=#00ffffff>DISPARO AÉREO</color>" },
{ "ultrakill.attripator", "<color=#00ffff>ATRACTOR</color>" },
{ "ultrakill.arsenal", "<color=#00ffff>ARSENAL</color>" },
{ "ultrakill.bigheadshot", "GRAN HEADSHOT" },
{ "ultrakill.bigkill", "GRAN MUERTE" },
{ "ultrakill.bigfistkill", "GOLPE MORTAL" },
{ "ultrakill.bipolar", "ENTRE POLOS" },
{ "ultrakill.cannonballed", "CAÑONAZO" },
{ "ultrakill.cannonballedfrombounce", "<color=green>REMATE</color>" },
{ "ultrakill.cannonboost", "<color=green>CAÑÓN IMPULSADO</color>" },
{ "ultrakill.catapulted", "<color=#00ffff>CATAPULTADO</color>" },
{ "ultrakill.chargeback", "DEVOLUCIÓN" },
{ "ultrakill.compressed", "COMPRIMIDO" },
{ "ultrakill.criticalpunch", "IMPACTO CRÍTICO" },
{ "ultrakill.disrespect", "IRRESPETUOSO" },
{ "ultrakill.doublekill", "<color=orange>DOBLE MUERTE</color>" },
{ "ultrakill.downtosize", "<color=#00ffff>A SU MEDIDA</color>" },
{ "ultrakill.drillpunch", "<color=green>DESATORNILLADO</color>" },
{ "ultrakill.drillpunchkill", "<color=green>TALADRADO</color>" },
{ "ultrakill.enraged", "<color=red>ENFURECIDO</color>" },
{ "ultrakill.exploded", "EXPLOTADO" },
{ "ultrakill.finishedoff", "<color=#00ffff>REMATADO</color>" },
{ "ultrakill.fireworks", "<color=#00ffff>FUEGOS ARTIFICIALES</color>" },
{ "ultrakill.fireworksweak", "<color=#00ffff>MALABARES</color>" },
{ "ultrakill.fistfullofdollar", "<color=#00ffff>INFLACIÓN</color>" },
{ "ultrakill.fried", "INCINERADO" },
{ "ultrakill.friendlyfire", "FUEGO AMIGO" },
{ "ultrakill.groundslam", "PISOTÓN" },
{ "ultrakill.halfoff", "<color=#00ffff>A LA MITAD</color>" },
{ "ultrakill.hammerhitgreen", "CONTUSIÓN" },
{ "ultrakill.hammerhitheavy", "FUERZA BRUTA" },
{ "ultrakill.hammerhitred", "IMPACTO PURO" },
{ "ultrakill.hammerhityellow", "IMPACTO PESADO" },
{ "ultrakill.headshot", "HEADSHOT" },
{ "ultrakill.headshotcombo", "<color=#00ffff>COMBO DE HEADSHOTS</color>" },
{ "ultrakill.homerun", "BATAZO" },
{ "ultrakill.iconoclasm", "ROMPE ÍDOLOS" },
{ "ultrakill.heartbreak", "ROMPE CORAZONES" },
{ "ultrakill.instakill", "<color=green>MUERTE INSTANTÁNEA</color>" },
{ "ultrakill.insurrknockdown", "<color=green>TIEMPO FUERA</color>" },
{ "ultrakill.interruption", "<color=green>INTERRUPCIÓN</color>" },
{ "ultrakill.kill", "MUERTE" },
{ "ultrakill.landyours", "TODA TUYA" },
{ "ultrakill.lightningbolt", "<color=green>PARARRAYOS</color>" },
{ "ultrakill.limbhit", "DESMEMBRADO" },
{ "ultrakill.mauriced", "MAURICIDIO" },
{ "ultrakill.multikill", "<color=orange>MUERTE MÚLTIPLE</color>" },
{ "ultrakill.nailbombed", "BOMBA DE METRALLA" },
{ "ultrakill.nailbombedalive", "<color=grey>METRALLA</color>" },
{ "ultrakill.overkill", "EXAGERADO" },
{ "ultrakill.parry", "<color=green>DESVÍO</color>" },
{ "ultrakill.projectileboost", "<color=green>PROYECTIL IMPULSADO</color>" },
{ "ultrakill.quickdraw", "<color=#00ffff>DESENFUNDE RÁPIDO</color>" },
{ "ultrakill.ricoshot", "<color=#00ffff>REBOTE</color>" },
{ "ultrakill.secret", "<color=#00ffff>SECRETO</color>" },
{ "ultrakill.serve", "<color=#00ffff>SERVIDO</color>" },
{ "ultrakill.strike", "<color=#00ffff>¡CHUZA!</color>" },
{ "ultrakill.splattered", "SALPICADERO" },
{ "ultrakill.triplekill", "<color=orange>TRIPLE MUERTE</color>" },
{ "ultrakill.rocketreturn", "<color=#00FFFF>COHETE DEVUELTO</color>" },
{ "ultrakill.roundtrip", "<color=green>IDA Y VUELTA</color>" },
{ "ultrakill.terminalvelocity", "VELOCIDAD TERMINAL" },
{ "ultrakill.insurrstomp", "PISADO" }
};
HiddenBonuses = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "ultrakill.drillhit", "ultrakill.hammerhit", "ultrakill.firehit", "ultrakill.shotgunhit", "ultrakill.nailhit", "ultrakill.explosionhit", "ultrakill.zapperhit" };
DynamicTranslations = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "CONDUCTOR", "<color=#00ffff>CONDUCCIÓN</color>" },
{ "CRUSHED", "APLASTADO" },
{ "FALL", "CAÍDA" },
{ "FRIED", "INCINERADO" },
{ "GROOVY", "REBANADO" },
{ "GUARD BREAK", "<color=green>GUARDIA ROTA</color>" },
{ "HEAVY LIGHT", "LUZ PESADA" },
{ "MINCED", "PICADO" },
{ "NO-NO", "YOYÓ" },
{ "OUT OF BOUNDS", "FUERA DE LOS LÍMITES" },
{ "RE-NO-NO", "RE-YOYÓ" },
{ "PANCAKED", "APLANADO" },
{ "RICOSHOT", "REBOTE" },
{ "ROADKILL", "ATROPELLADO" },
{ "SCREWED", "PERFORADO" },
{ "SHREDDED", "TRITURADO" },
{ "SLIPPED", "RESBALADO" },
{ "TRAMPLED", "PISOTEADO" },
{ "UNCHAINEDSAW", "MOTOSIERRA LOCA" },
{ "OSHA VIOLATION", "NEGLIGENCIA LABORAL" },
{ "why are you even using this weapon", "¿Por qué estás usando esta arma?" },
{ "why are you even spawning enemies here", "¿Por qué estás generando enemigos?" },
{ "BOILED", "HERVIDO" },
{ "FOR THEE", "PARA VOS" },
{ "LOST", "PERDIDO" },
{ "LONG WAY DOWN", "LARGO CAMINO HACIA ABAJO" },
{ "M.A.D.", "L.O.C.O." },
{ "TRASHED", "BASURA" },
{ "ENVIROKILL", "MUERTE AMBIENTAL" },
{ "SCRONGLED", "LICUADO" },
{ "SCRONGBONGLED", "DESGUAZADO" },
{ "SCRINDONGULODED", "DESINTEGRADO" },
{ "ZAPPED", "ELECTROCUTADO" },
{ "BISHOP CAPTURE", "<color=green>ALFIL CAPTURADO</color>" },
{ "BISHOP PROMOTION", "<color=green>ASCENSO A ALFIL</color>" },
{ "BLACK WINS", "<color=orange>PIEZAS NEGRAS GANAN</color>" },
{ "BONGCLOUD", "<color=orange>BONGCLOUD</color>" },
{ "CASTLED", "<color=blue>ENROQUE</color>" },
{ "EN PASSANT", "<color=blue>EN PASSANT</color>" },
{ "FOOLS MATE", "<color=red>JAQUE AL TONTO</color>" },
{ "KNIGHT CAPTURE", "<color=green>CABALLO CAPTURADO</color>" },
{ "KNIGHT PROMOTION", "<color=green>ASCENSO A CABALLO</color>" },
{ "PAWN CAPTURE", "PEÓN CAPTURADO" },
{ "QUEEN CAPTURE", "<color=red>REINA CAPTURADA</color>" },
{ "QUEEN PROMOTION", "<color=green>ASCENSO A REINA</color>" },
{ "ROOK CAPTURE", "<color=orange>TORRE CAPTURADA</color>" },
{ "ROOK PROMOTION", "<color=green>ASCENSO A TORRE</color>" },
{ "STOP HITTING YOURSELF", "<color=red>DEJA DE GOLPEARTE</color>" },
{ "ULTRAVICTORY", "<color=red>ULTRAVICTORIA</color>" },
{ "WHITE WINS", "<color=orange>PIEZAS BLANCAS GANAN</color>" },
{ "STARSTRUCK", "IMPACTO ESTELAR" },
{ "LOST IN SPACE", "PERDIDO EN EL ESPACIO" },
{ "GONE SWIMMING", "A NADAR" },
{ "RAISON D'ETRE", "RAISON D'ETRE" },
{ "HYPERDRATION", "EMPAPADO" },
{ "SLICED", "REBANADO" },
{ "DICED", "DESPEDAZADO" },
{ "THRICED", "TROCEADO" },
{ "LONG HAUL", "LARGO VIAJE" },
{ "DETAINED", "RECLUIDO" }
};
}
public static string TranslateBonus(string inputBonus)
{
if (string.IsNullOrEmpty(inputBonus))
{
return string.Empty;
}
if (HiddenBonuses.Contains(inputBonus))
{
return string.Empty;
}
string text = inputBonus;
text = text.Replace("<color=orange>ULTRA</color>", "<color=orange>ULTRA</color> ").Replace("<color=red>COUNTER</color>", "<color=red>CONTRA</color> ");
string key = Regex.Replace(text, "<[^>]*>", "");
if (BonusDictionary.TryGetValue(key, out var value))
{
text = value;
}
else if (DynamicTranslations.TryGetValue(key, out value))
{
text = value;
}
return text;
}
}
[HarmonyPatch(typeof(StyleHUD), "GetLocalizedName")]
public static class LocalizeStyleHud
{
[HarmonyPrefix]
public static bool GetLocalizedName_MyPatch(string id, StyleHUD __instance, Dictionary<string, string> ___idNameDict, ref string __result)
{
string text = (___idNameDict[id] = StyleBonusStrings.TranslateBonus(id));
__result = text;
return false;
}
}
[HarmonyPatch(typeof(StyleHUD), "AscendRank")]
public static class StyleHUD_AscendRankPatch
{
[HarmonyPrefix]
public static void Prefix(StyleHUD __instance)
{
try
{
int num = Mathf.Clamp(__instance.rankIndex, 0, 7);
int num2 = Mathf.Clamp(__instance.rankIndex + 1, 0, 7);
if (num != num2)
{
}
}
catch (Exception ex)
{
Debug.Log((object)("[TexturePatcher] Error en AscendRankPatch: " + ex.Message));
}
}
}
[HarmonyPatch(typeof(StyleHUD), "DescendRank")]
public static class StyleHUD_DescendRankPatch
{
[HarmonyPrefix]
public static void Prefix(StyleHUD __instance)
{
try
{
int num = Mathf.Clamp(__instance.rankIndex, 0, 7);
int num2 = Mathf.Clamp(__instance.rankIndex - 1, 0, 7);
if (num != num2)
{
}
}
catch (Exception ex)
{
Debug.Log((object)("[TexturePatcher] Error en DescendRankPatch: " + ex.Message));
}
}
}
[HarmonyPatch(typeof(Nailgun))]
public static class NailgunPatch
{
[HarmonyPatch("Start")]
[HarmonyPostfix]
public static void NailgunStartPostfix(Nailgun __instance)
{
if (((Object)((Component)__instance).gameObject).name.ToLower().Contains("magnet"))
{
__instance.ammoText.fontSize = 220;
}
}
[HarmonyPatch("UpdateZapHud")]
[HarmonyPostfix]
public static void ZapperPostfix(Nailgun __instance, Zapper ___currentZapper, CameraController ___cc, TMP_Text ___statusText, GameObject ___rechargingOverlay)
{
//IL_0075: Unknown result type (might be due to invalid IL or missing references)
//IL_0082: Unknown result type (might be due to invalid IL or missing references)
//IL_008d: Unknown result type (might be due to invalid IL or missing references)
if (!((Object)((Component)__instance).gameObject).name.ToLower().Contains("zapper"))
{
return;
}
if ((Object)(object)___rechargingOverlay != (Object)null && ___rechargingOverlay.activeSelf)
{
TextMeshProUGUI componentInChildren = ___rechargingOverlay.GetComponentInChildren<TextMeshProUGUI>(true);
if ((Object)(object)componentInChildren != (Object)null)
{
((TMP_Text)componentInChildren).text = "RECARGANDO...";
}
}
if ((Object)(object)___currentZapper == (Object)null)
{
int num = LayerMask.op_Implicit(LayerMaskDefaults.Get((LMD)3));
RaycastHit val = default(RaycastHit);
if (Physics.Raycast(___cc.GetDefaultPos(), ((Component)___cc).transform.forward, ref val, 1000f, num))
{
EnemyIdentifierIdentifier val2 = default(EnemyIdentifierIdentifier);
if (((Component)((RaycastHit)(ref val)).collider).gameObject.layer != 8 && ((Component)((RaycastHit)(ref val)).collider).gameObject.layer != 24 && ((Component)((RaycastHit)(ref val)).collider).TryGetComponent<EnemyIdentifierIdentifier>(ref val2) && (Object)(object)val2.eid != (Object)null && !val2.eid.dead)
{
float num2 = __instance.zapper.maxDistance - 5f;
___statusText.text = ((((RaycastHit)(ref val)).distance < num2) ? "LISTO" : "FUERA DE RANGO");
}
else
{
___statusText.text = "SIN OBJETIVO";
}
}
else
{
___statusText.text = "SIN OBJETIVO";
}
}
else if (___currentZapper.distance > ___currentZapper.maxDistance || ___currentZapper.raycastBlocked)
{
___statusText.text = (___currentZapper.raycastBlocked ? "BLOQUEADO" : "FUERA DE RANGO");
}
else
{
string text = (__instance.altVersion ? "" : "DISTANCIA: ");
___statusText.text = text + ___currentZapper.distance.ToString("F1");
}
}
}
[HarmonyPatch]
public static class TexturesPatch
{
private class DummyMonoBehaviour : MonoBehaviour
{
private void OnDestroy()
{
cancellationTokenSource?.Cancel();
currentLevel = null;
currentReplacements = null;
textureCache.Clear();
Plugin.LoggerInstance.LogInfo((object)"[TexturePatcher] Coroutine destroyed and cache cleared");
}
}
private static bool initialized = false;
private static Dictionary<string, Dictionary<string, (string filename, string type)>> levelTextureMappings;
private static Dictionary<string, Texture2D> textureCache = new Dictionary<string, Texture2D>();
private static MonoBehaviour coroutineStarter;
private static Dictionary<string, Texture2D> currentReplacements;
private static string currentLevel = string.Empty;
private static bool isProcessing = false;
private static CancellationTokenSource cancellationTokenSource;
private static readonly HashSet<int> processedObjectIds = new HashSet<int>();
private static readonly HashSet<int> processedRawImages = new HashSet<int>();
private static Coroutine backgroundChecker;
private static readonly Dictionary<string, Texture2D> batchTextureCache = new Dictionary<string, Texture2D>();
private static readonly Dictionary<string, Rect> batchRegionCache = new Dictionary<string, Rect>();
private static readonly Dictionary<string, Dictionary<string, Rect>> manualBatchRegions = new Dictionary<string, Dictionary<string, Rect>> {
{
"45addc6c3730dae418321e00af1116c5",
new Dictionary<string, Rect>
{
{
"VendingMachine",
new Rect(0f, 0f, 256f, 256f)
},
{
"ad_fox_1",
new Rect(0f, 0f, 256f, 256f)
},
{
"ad_clothes_1",
new Rect(0f, 0f, 256f, 256f)
},
{
"ad_wing_1",
new Rect(0f, 0f, 256f, 256f)
}
}
} };
private static readonly List<string> IgnoredPathPatterns = new List<string> { "Leaderboard" };
private static readonly Dictionary<string, (string filename, string type)> globalTextureReplacements = new Dictionary<string, (string, string)>
{
{
"checkpoint",
("Checkpoint", "texture")
},
{
"spawnpoint",
("spawnpoint", "texture")
},
{
"T_ShopTerminal",
("T_ShopTerminal", "texture")
},
{
"T_ShopTerminal_Emission",
("T_ShopTerminal_Emission", "texture")
},
{
"T_Gabe_SpledorJustice",
("T_Gabe_SpledorJustice", "texture")
},
{
"bombtexture4",
("bombtexture4", "texture")
},
{
"bombtexture5",
("bombtexture5", "texture")
}
};
private static readonly HashSet<string> ignoredScenes = new HashSet<string> { "Bootstrap", "Intro", "Loading" };
private static readonly string[] TextureProps = new string[6] { "_MainTex", "_BaseMap", "_DetailAlbedoMap", "_Texture", "_MainTexture", "_EmissiveTex" };
private static readonly int[] TexturePropIDs = ((IEnumerable<string>)TextureProps).Select((Func<string, int>)Shader.PropertyToID).ToArray();
private static string texturesFolder
{
get
{
string text = Path.Combine(Paths.PluginPath, "ESP_TEAM-ULTRAKILL_IN_SPANISH");
char directorySeparatorChar = Path.DirectorySeparatorChar;
return text + directorySeparatorChar;
}
}
private static void EnsureTexturesFolderExists()
{
if (!Directory.Exists(texturesFolder))
{
Directory.CreateDirectory(texturesFolder);
Plugin.LoggerInstance.LogInfo((object)("[TexturePatcher] Created texture folder: " + texturesFolder));
}
}
[HarmonyPrepare]
private static void Prepare()
{
cancellationTokenSource = new CancellationTokenSource();
EnsureTexturesFolderExists();
InitializeTextureMappings();
Plugin.LoggerInstance.LogInfo((object)"[TexturePatcher] Module initialized");
}
private static void InitializeTextureMappings()
{
if (!initialized)
{
levelTextureMappings = new Dictionary<string, Dictionary<string, (string, string)>>
{
{
"4f8ecffaa98c2614f89922daf31fa22d",
new Dictionary<string, (string, string)> {
{
"",
("Batch Tutorial", "texture")
} }
},
{
"eb57c9574cb2e624799753de0f8ffcad",
new Dictionary<string, (string, string)>
{
{
"SignSecurityInstructions",
("SignSecurityInstructions", "texture")
},
{
"SignWarning",
("SignWarning", "texture")
},
{
"SignCoolingChamber",
("SignCoolingChamber", "texture")
},
{
"SignSecurityLockdown",
("SignSecurityLockdown", "texture")
},
{
"SignSecurityCheckpoint",
("SignSecurityCheckpoint", "texture")
}
}
},
{
"7927c42db92e4164cae682a55e6b7725",
new Dictionary<string, (string, string)>
{
{
"SignSecurityInstructions",
("SignSecurityInstructions", "texture")
},
{
"SignWarning",
("SignWarning", "texture")
},
{
"SignCoolingChamber",
("SignCoolingChamber", "texture")
},
{
"SignSecurityLockdown",
("SignSecurityLockdown", "texture")
},
{
"SignSecurityCheckpoint",
("SignSecurityCheckpoint", "texture")
}
}
},
{
"5bcb2e0461e7fce408badfcb6778c271",
new Dictionary<string, (string, string)>
{
{
"SignSecurityInstructions",
("SignSecurityInstructions", "texture")
},
{
"SignWarning",
("SignWarning", "texture")
},
{
"SignCoolingChamber",
("SignCoolingChamber", "texture")
},
{
"SignSecurityLockdown",
("SignSecurityLockdown", "texture")
},
{
"SignSecurityCheckpoint",
("SignSecurityCheckpoint", "texture")
}
}
},
{
"3e978dea8d12a0146b46cb0c302d66e2",
new Dictionary<string, (string, string)>
{
{
"SignSecurityInstructions",
("SignSecurityInstructions", "texture")
},
{
"SignWarning",
("SignWarning", "texture")
},
{
"SignCoolingChamber",
("SignCoolingChamber", "texture")
},
{
"SignSecurityLockdown",
("SignSecurityLockdown", "texture")
},
{
"SignSecurityCheckpoint",
("SignSecurityCheckpoint", "texture")
}
}
},
{
"5541f073d290f4348884fa3f76072afd",
new Dictionary<string, (string, string)>
{
{
"abandonhope2",
("abandonhope2", "texture")
},
{
"SignSecurityInstructions",
("SignSecurityInstructions", "texture")
},
{
"SignWarning",
("SignWarning", "texture")
},
{
"SignCoolingChamber",
("SignCoolingChamber", "texture")
},
{
"SignSecurityLockdown",
("SignSecurityLockdown", "texture")
},
{
"SignSecurityCheckpoint",
("SignSecurityCheckpoint", "texture")
}
}
},
{
"8038b251ea4683b4db4ef432205184f6",
new Dictionary<string, (string, string)> {
{
"electricitybox",
("electricitybox", "texture")
} }
},
{
"36abcaae9708abc4d9e89e6ec73a2846",
new Dictionary<string, (string, string)> {
{
"forgiveme",
("forgiveme", "texture")
} }
},
{
"6440445a799e22842babe18edf7da792",
new Dictionary<string, (string, string)>
{
{
"electricitybox",
("electricitybox", "texture")
},
{
"",
("Batch 2-2", "texture")
}
}
},
{
"4e039f071c1fba04a82a7b6b44feadc2",
new Dictionary<string, (string, string)>
{
{
"",
("Batch 2-3", "texture")
},
{
"watercontrol1",
("watercontrol1", "texture")
},
{
"watercontrol2",
("watercontrol2", "texture")
}
}
},
{
"38748a67bc9e67a43956a92f87d1e742",
new Dictionary<string, (string, string)>
{
{
"traitor",
("traitor", "texture")
},
{
"",
("Batch 4-3", "texture")
}
}
},
{
"fba3bcfce7b99ae4d90356c81c5586b3",
new Dictionary<string, (string, string)>
{
{
"WaterProcessingAttention",
("WaterProcessingAttention", "texture")
},
{
"",
("Batch 5-1", "texture")
}
}
},
{
"1567f75bc4488644684d7a25471dbe95",
new Dictionary<string, (string, string)>
{
{
"",
("Batch 5-S", "texture")
},
{
"Bait Label",
("Bait Label", "texture")
}
}
},
{
"aa55551f768b5224997a4b5e0ef315ea",
new Dictionary<string, (string, string)>
{
{
"",
("Batch 7-2", "texture")
},
{
"exit",
("exit", "texture")
}
}
},
{
"7a11d5684479d2446a735fa154d6bc7c",
new Dictionary<string, (string, string)> {
{
"marble_inverted 3",
("marble_inverted 3", "texture")
} }
},
{
"6e981b1865c649749a610aafc471e198",
new Dictionary<string, (string, string)>
{
{
"T_Cent_PlantRoom",
("T_Cent_PlantRoom", "texture")
},
{
"electricitybox",
("electricitybox", "texture")
},
{
"T_DawgControls_Emissive",
("T_DawgControls_Emissive", "texture")
},
{
"T_DawgControls_EmissiveOff",
("T_DawgControls_EmissiveOff", "texture")
}
}
},
{
"aa8b84f8b1443ef4783afbc6b1db1e30",
new Dictionary<string, (string, string)>
{
{
"T_Placard",
("T_Placard", "texture")
},
{
"T_TrailSign",
("T_TrailSign", "texture")
}
}
},
{
"36c5b4853d1d63d4686ea9a23ca61f8c",
new Dictionary<string, (string, string)>
{
{
"exit",
("exit", "texture")
},
{
"abandonhope2",
("abandonhope2", "texture")
},
{
"SignSecurityInstructions",
("SignSecurityInstructions", "texture")
},
{
"SignWarning",
("SignWarning", "texture")
},
{
"SignCoolingChamber",
("SignCoolingChamber", "texture")
},
{
"SignSecurityLockdown",
("SignSecurityLockdown", "texture")
},
{
"SignSecurityCheckpoint",
("SignSecurityCheckpoint", "texture")
}
}
},
{
"e92f893de47503a4f959f7d5bca84261",
new Dictionary<string, (string, string)>
{
{
"sign_map_Texture_2",
("sign_map_Texture_2", "texture")
},
{
"poster",
("poster", "texture")
},
{
"Staff only sign_texture",
("Staff only sign_texture", "texture")
}
}
},
{
"ab5460c767500b748a7f5497682ffc63",
new Dictionary<string, (string, string)>
{
{
"VendingMachine",
("VendingMachine", "texture")
},
{
"wecamein",
("wecamein", "texture")
},
{
"wecamein2",
("wecamein2", "texture")
},
{
"T_LionPlaque",
("T_LionPlaque", "texture")
},
{
"ArchangelNamePlateGabriel",
("ArchangelNamePlateGabriel", "texture")
},
{
"ArchangelNamePlateMichael",
("ArchangelNamePlateMichael", "texture")
},
{
"ArchangelNamePlatePhanuel",
("ArchangelNamePlatePhanuel", "texture")
},
{
"ArchangelNamePlateRaphael",
("ArchangelNamePlateRaphael", "texture")
},
{
"ArchangelNamePlateVandalized",
("ArchangelNamePlateVandalized", "texture")
},
{
"",
("Batch 8-1", "texture")
}
}
},
{
"45addc6c3730dae418321e00af1116c5",
new Dictionary<string, (string, string)>
{
{
"StatsBoard",
("StatsBoard", "texture")
},
{
"inthemirror",
("inthemirror", "texture")
},
{
"VendingMachine",
("VendingMachine", "texture")
},
{
"big_hakita",
("big_hakita", "texture")
},
{
"presentation2",
("presentation2", "texture")
},
{
"",
("Batch 8-2", "texture")
},
{
"ad_clothes_1",
("ad_clothes_1", "texture")
},
{
"ad_fox_1",
("ad_fox_1", "texture")
},
{
"ad_wing_1",
("ad_wing_1", "texture")
},
{
"ad_clothes",
("ad_clothes", "texture")
},
{
"ad_fox",
("ad_fox", "texture")
},
{
"ad_wing",
("ad_wing", "texture")
},
{
"OfficeArchive",
("OfficeArchive", "texture")
},
{
"OfficeMaintenance",
("OfficeMaintenance", "texture")
}
}
},
{
"4d0787cb97dbde141b6957720788c4dd",
new Dictionary<string, (string, string)>
{
{
"T_LionPlaque",
("T_LionPlaque", "texture")
},
{
"VendingMachine",
("VendingMachine", "texture")
},
{
"SignWarning",
("SignWarning", "texture")
},
{
"",
("Batch 8-3", "texture")
}
}
},
{
"7f3f5eabda008e04cb2364d6f0327aa5",
new Dictionary<string, (string, string)>
{
{
"VendingMachine",
("VendingMachine", "texture")
},
{
"",
("Batch 8-4", "texture")
},
{
"SignWarning",
("SignWarning", "texture")
},
{
"CityoftheDeadSunPoster",
("CityoftheDeadSunPoster", "texture")
}
}
},
{
"e7825b3eefa03ff4c88fec66971e5523",
new Dictionary<string, (string, string)>
{
{
"LockdownText",
("LockdownText", "texture")
},
{
"DecalGreg",
("DecalGreg", "texture")
},
{
"MetaSign2",
("MetaSign2", "texture")
},
{
"T_PurgTerminal",
("T_PurgTerminal", "texture")
},
{
"T_PurgTerminal_Emission",
("T_PurgTerminal_Emission", "texture")
},
{
"click_to_be_pure",
("click_to_be_pure", "texture")
},
{
"CoolSign",
("CoolSign", "texture")
},
{
"watercontrol1",
("watercontrol1", "texture")
},
{
"watercontrol2",
("watercontrol2", "texture")
},
{
"watercontrol3",
("watercontrol3", "texture")
}
}
},
{
"cf4724b8ba08d2742bf12ea911d27043",
new Dictionary<string, (string, string)>
{
{
"Can Anyone Hear Me Now",
("Can Anyone Hear Me Now", "texture")
},
{
"LockdownText",
("LockdownText", "texture")
},
{
"DecalGreg",
("DecalGreg", "texture")
},
{
"signalisgrafitti",
("signalisgrafitti", "texture")
},
{
"electricitybox",
("electricitybox", "texture")
},
{
"T_PurgTerminal",
("T_PurgTerminal", "texture")
},
{
"T_PurgTerminal_Emission",
("T_PurgTerminal_Emission", "texture")
},
{
"click_to_be_pure",
("click_to_be_pure", "texture")
},
{
"TantLOS_Bluescreen_Old",
("TantLOS_Bluescreen_Old", "texture")
},
{
"MotelSign",
("MotelSign", "texture")
}
}
},
{
"12bc693bfa9919549902bc95d6143abe",
new Dictionary<string, (string, string)>
{
{
"T_PurgTerminal",
("T_PurgTerminal", "texture")
},
{
"T_PurgTerminal_Emission",
("T_PurgTerminal_Emission", "texture")
}
}
},
{
"cc498e471bbc2c444990dfcff25d8265",
new Dictionary<string, (string, string)>
{
{
"T_PurgTerminal",
("T_PurgTerminal", "texture")
},
{
"T_PurgTerminal_Emission",
("T_PurgTerminal_Emission", "texture")
}
}
},
{
"9a7b08749b3c7704f89d64cb3ea01ea2",
new Dictionary<string, (string, string)>
{
{
"T_PurgTerminal",
("T_PurgTerminal", "texture")
},
{
"T_PurgTerminal_Emission",
("T_PurgTerminal_Emission", "texture")
},
{
"room_of_shame",
("room_of_shame", "texture")
},
{
"MEPHIPANEL",
("MEPHIPANEL", "texture")
}
}
},
{
"b3bfe8ace27e5784c9c228ed28881d49",
new Dictionary<string, (string, string)>
{
{
"T_PurgTerminal",
("T_PurgTerminal", "texture")
},
{
"T_PurgTerminal_Emission",
("T_PurgTerminal_Emission", "texture")
}
}
},
{
"6384dbba1537c084e92d90ab032ee9bc",
new Dictionary<string, (string, string)>
{
{
"T_PurgTerminal",
("T_PurgTerminal", "texture")
},
{
"T_PurgTerminal_Emission",
("T_PurgTerminal_Emission", "texture")
},
{
"PurgMap",
("PurgMap", "texture")
}
}
}
};
initialized = true;
Plugin.LoggerInstance.LogInfo((object)$"[TexturePatcher] Loaded {globalTextureReplacements.Count} global and {levelTextureMappings.Count} level-specific mappings");
}
}
[HarmonyPatch(typeof(SceneHelper), "OnSceneLoaded")]
[HarmonyPostfix]
private static void OnSceneLoaded()
{
//IL_0042: Unknown result type (might be due to invalid IL or missing references)
//IL_0048: Expected O, but got Unknown
cancellationTokenSource?.Cancel();
cancellationTokenSource?.Dispose();
cancellationTokenSource = new CancellationTokenSource();
if ((Object)(object)coroutineStarter == (Object)null)
{
GameObject val = new GameObject("TexturePatcher_CoroutineStarter");
coroutineStarter = (MonoBehaviour)(object)val.AddComponent<DummyMonoBehaviour>();
}
coroutineStarter.StartCoroutine(ProcessSceneChange());
}
private static IEnumerator ProcessSceneChange()
{
if (isProcessing)
{
yield break;
}
isProcessing = true;
Scene activeScene = SceneManager.GetActiveScene();
string sceneName = ((Scene)(ref activeScene)).name;
if (string.IsNullOrEmpty(sceneName) || cancellationTokenSource.IsCancellationRequested)
{
Plugin.LoggerInstance.LogInfo((object)"[TexturePatcher] Scene loading aborted");
ResetInternalState();
yield break;
}
if (ShouldIgnoreScene(sceneName))
{
Plugin.LoggerInstance.LogInfo((object)("[TexturePatcher] Ignoring scene: " + sceneName));
ResetInternalState();
yield break;
}
if (!initialized)
{
Plugin.LoggerInstance.LogWarning((object)"[TexturePatcher] Not initialized");
ResetInternalState();
yield break;
}
Plugin.LoggerInstance.LogInfo((object)("[TexturePatcher] Processing scene: " + sceneName));
yield return null;
if (currentLevel != sceneName)
{
ResetInternalState();
currentLevel = sceneName;
}
currentReplacements = new Dictionary<string, Texture2D>();
yield return LoadTextures(globalTextureReplacements);
Dictionary<string, (string filename, string type)> levelSpecific = GetLevelSpecificTextures(sceneName);
if (levelSpecific != null && levelSpecific.Count > 0)
{
yield return LoadTextures(levelSpecific);
}
if (currentReplacements.Count == 0)
{
Plugin.LoggerInstance.LogWarning((object)"[TexturePatcher] No textures were loaded, skipping patching");
isProcessing = false;
yield break;
}
yield return ReplaceTexturesInScene(isInitialPass: true);
yield return ProcessBatchTextures(sceneName);
if (backgroundChecker != null)
{
coroutineStarter.StopCoroutine(backgroundChecker);
}
backgroundChecker = coroutineStarter.StartCoroutine(BackgroundTextureCheck());
isProcessing = false;
}
private static IEnumerator ProcessBatchTextures(string sceneName)
{
if (!manualBatchRegions.TryGetValue(sceneName, out var regions))
{
yield break;
}
Texture2D atlas = FindBatchTexture(sceneName);
if ((Object)(object)atlas == (Object)null)
{
yield break;
}
foreach (KeyValuePair<string, Rect> regionEntry in regions)
{
string textureName = regionEntry.Key;
Rect region = regionEntry.Value;
if (currentReplacements.TryGetValue(textureName, out var replacement))
{
ReplaceTextureRegion(atlas, region, replacement);
yield return null;
replacement = null;
}
}
}
private static void ResetInternalState()
{
ClearTextureCache();
processedObjectIds.Clear();
processedRawImages.Clear();
batchTextureCache.Clear();
batchRegionCache.Clear();
currentReplacements = null;
currentLevel = null;
isProcessing = false;
}
private static void ClearTextureCache()
{
foreach (Texture2D value in textureCache.Values)
{
Object.Destroy((Object)(object)value);
}
textureCache.Clear();
}
private static Dictionary<string, (string filename, string type)> GetLevelSpecificTextures(string sceneName)
{
foreach (KeyValuePair<string, Dictionary<string, (string, string)>> levelTextureMapping in levelTextureMappings)
{
if (sceneName.Contains(levelTextureMapping.Key))
{
return levelTextureMapping.Value;
}
}
return null;
}
private static Texture2D FindBatchTexture(string sceneName)
{
if (batchTextureCache.TryGetValue(sceneName, out var value))
{
return value;
}
Material[] array = Resources.FindObjectsOfTypeAll<Material>();
foreach (Material val in array)
{
if ((Object)(object)val == (Object)null || ((Object)val).name.IndexOf("Batch Material Environment", StringComparison.OrdinalIgnoreCase) < 0)
{
continue;
}
string[] textureProps = TextureProps;
foreach (string text in textureProps)
{
int num = Shader.PropertyToID(text);
if (val.HasProperty(num))
{
Texture texture = val.GetTexture(num);
Texture2D val2 = (Texture2D)(object)((texture is Texture2D) ? texture : null);
if (!((Object)(object)val2 == (Object)null))
{
batchTextureCache[sceneName] = val2;
Plugin.LoggerInstance.LogInfo((object)$"[TexturePatcher] Batch texture found: {((Object)val2).name} ({((Texture)val2).width}x{((Texture)val2).height})");
return val2;
}
}
}
}
Plugin.LoggerInstance.LogWarning((object)"[TexturePatcher] Batch texture not found");
return null;
}
private static IEnumerator LoadTextures(Dictionary<string, (string filename, string type)> textureMap)
{
foreach (KeyValuePair<string, (string, string)> entry in textureMap)
{
if (cancellationTokenSource.IsCancellationRequested)
{
yield break;
}
string key = entry.Key;
string filename = entry.Value.Item1;
if (!currentReplacements.ContainsKey(key))
{
Texture2D loaded = null;
yield return coroutineStarter.StartCoroutine(LoadTexture(filename, delegate(Texture2D tex)
{
loaded = tex;
}));
if ((Object)(object)loaded == (Object)null)
{
Plugin.LoggerInstance.LogWarning((object)("[TexturePatcher] Failed to load texture: " + filename));
continue;
}
((Texture)loaded).filterMode = (FilterMode)0;
currentReplacements[key] = loaded;
Plugin.LoggerInstance.LogInfo((object)("[TexturePatcher] Loaded texture '" + filename + "' as '" + key + "'"));
}
}
}
private static IEnumerator BackgroundTextureCheck()
{
while (!cancellationTokenSource.IsCancellationRequested && !string.IsNullOrEmpty(currentLevel))
{
float waitTime = GetSceneCheckDelay(currentLevel);
yield return (object)new WaitForSeconds(waitTime);
if (currentReplacements != null && currentReplacements.Count > 0)
{
yield return ReplaceTexturesInScene(isInitialPass: false);
}
}
Plugin.LoggerInstance.LogInfo((object)"[TexturePatcher] Background texture check ended.");
}
private static float GetSceneCheckDelay(string sceneName)
{
if (sceneName.IndexOf("4-S", StringComparison.OrdinalIgnoreCase) >= 0)
{
return 3f;
}
return 0.5f;
}
private static IEnumerator ReplaceTexturesInScene(bool isInitialPass)
{
if (currentReplacements == null || cancellationTokenSource.IsCancellationRequested)
{
yield break;
}
Camera mainCam = Camera.main;
int processedChanges = 0;
int scannedRenderers = 0;
int scannedRawImages = 0;
Renderer[] renderers = Object.FindObjectsOfType<Renderer>();
Renderer[] array = renderers;
foreach (Renderer rend in array)
{
if (!IsValidRenderer(rend, mainCam) || IsInIgnoredPath(((Component)rend).gameObject))
{
continue;
}
int id = ((Object)rend).GetInstanceID();
if (!processedObjectIds.Add(id))
{
continue;
}
Material[] sharedMaterials = rend.sharedMaterials;
MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
for (int m = 0; m < sharedMaterials.Length; m++)
{
Material mat = sharedMaterials[m];
if ((Object)(object)mat == (Object)null)
{
continue;
}
bool modified = false;
propertyBlock.Clear();
rend.GetPropertyBlock(propertyBlock, m);
for (int p = 0; p < TexturePropIDs.Length; p++)
{
int propId = TexturePropIDs[p];
if (!mat.HasProperty(propId))
{
continue;
}
Texture texture = mat.GetTexture(propId);
Texture2D curTex = (Texture2D)(object)((texture is Texture2D) ? texture : null);
if (!((Object)(object)curTex == (Object)null))
{
if (TryGetReplacement(((Object)curTex).name, out var replacement))
{
propertyBlock.SetTexture(propId, (Texture)(object)replacement);
modified = true;
processedChanges++;
}
if (processedChanges >= 8)
{
processedChanges = 0;
yield return null;
}
replacement = null;
}
}
if (modified)
{
rend.SetPropertyBlock(propertyBlock, m);
}
}
scannedRenderers++;
if (scannedRenderers % 60 == 0)
{
yield return null;
}
}
RawImage[] array2 = Object.FindObjectsOfType<RawImage>();
foreach (RawImage raw in array2)
{
if (!IsValidRawImage(raw) || IsInIgnoredPath(((Component)raw).gameObject))
{
continue;
}
int id2 = ((Object)raw).GetInstanceID();
if (!processedRawImages.Add(id2))
{
continue;
}
Texture texture2 = raw.texture;
Texture2D curTex2 = (Texture2D)(object)((texture2 is Texture2D) ? texture2 : null);
if (!((Object)(object)curTex2 == (Object)null))
{
if (TryGetReplacement(((Object)curTex2).name, out var replacement2))
{
raw.texture = (Texture)(object)replacement2;
processedChanges++;
}
scannedRawImages++;
if (processedChanges >= 8 || scannedRawImages % 60 == 0)
{
processedChanges = 0;
yield return null;
}
replacement2 = null;
}
}
}
private static bool TryGetReplacement(string textureName, out Texture2D replacement)
{
string key = textureName.Replace(" ", "_").ToLower();
return currentReplacements.TryGetValue(textureName, out replacement) || currentReplacements.TryGetValue(textureName.ToLower(), out replacement) || currentReplacements.TryGetValue(key, out replacement);
}
private static void ReplaceTextureRegion(Texture2D atlas, Rect region, Texture2D replacement)
{
if (!((Object)(object)atlas == (Object)null) && !((Object)(object)replacement == (Object)null))
{
int num = Mathf.Min((int)((Rect)(ref region)).width, ((Texture)replacement).width);
int num2 = Mathf.Min((int)((Rect)(ref region)).height, ((Texture)replacement).height);
Color32[] pixels = replacement.GetPixels32();
atlas.SetPixels32((int)((Rect)(ref region)).x, (int)((Rect)(ref region)).y, num, num2, pixels);
atlas.Apply(false, false);
Plugin.LoggerInstance.LogInfo((object)$"[TexturePatcher] Patched atlas region at {((Rect)(ref region)).x},{((Rect)(ref region)).y}");
}
}
private static bool IsValidRenderer(Renderer rend, Camera mainCam)
{
if ((Object)(object)rend == (Object)null || (Object)(object)((Component)rend).gameObject == (Object)null || !((Component)rend).gameObject.activeInHierarchy)
{
return false;
}
if (Object.op_Implicit((Object)(object)mainCam) && ((Object)(object)((Component)rend).gameObject == (Object)(object)((Component)mainCam).gameObject || (Object)(object)((Component)rend).GetComponentInParent<Camera>(true) != (Object)null))
{
return false;
}
return true;
}
private static bool IsValidRawImage(RawImage raw)
{
return (Object)(object)raw != (Object)null && ((Component)raw).gameObject.activeInHierarchy;
}
private static IEnumerator LoadTexture(string filename, Action<Texture2D> callback)
{
if (cancellationTokenSource.IsCancellationRequested)
{
callback(null);
yield break;
}
if (textureCache.TryGetValue(filename, out var cached))
{
callback(cached);
yield break;
}
string fullPath = FindTextureFile(filename);
if (string.IsNullOrEmpty(fullPath))
{
Plugin.LoggerInstance.LogWarning((object)("[TexturePatcher] File not found: " + filename));
callback(null);
yield break;
}
byte[] fileData = null;
Exception error = null;
bool isDone = false;
ThreadPool.QueueUserWorkItem(delegate
{
try
{
if (!cancellationTokenSource.IsCancellationRequested)
{
fileData = File.ReadAllBytes(fullPath);
}
}
catch (Exception ex)
{
error = ex;
}
finally
{
isDone = true;
}
});
while (!isDone && !cancellationTokenSource.IsCancellationRequested)
{
yield return null;
}
if (cancellationTokenSource.IsCancellationRequested)
{
callback(null);
yield break;
}
if (error != null)
{
Plugin.LoggerInstance.LogWarning((object)("[TexturePatcher] Error loading '" + filename + "': " + error.Message));
callback(null);
yield break;
}
if (fileData == null || fileData.Length == 0)
{
Plugin.LoggerInstance.LogWarning((object)("[TexturePatcher] Empty or unreadable file: " + filename));
callback(null);
yield break;
}
Texture2D tex = new Texture2D(2, 2, (TextureFormat)4, false)
{
name = Path.GetFileNameWithoutExtension(fullPath),
filterMode = (FilterMode)0,
anisoLevel = 0
};
if (!ImageConversion.LoadImage(tex, fileData, false))
{
Plugin.LoggerInstance.LogWarning((object)("[TexturePatcher] Failed to decode image: " + filename));
callback(null);
}
else
{
textureCache[filename] = tex;
callback(tex);
}
}
private static string FindTextureFile(string filename)
{
string[] array = new string[4] { ".png", ".jpg", ".jpeg", ".tga" };
string[] array2 = array;
foreach (string text in array2)
{
string text2 = Path.Combine(texturesFolder, filename + text);
if (File.Exists(text2))
{
return text2;
}
}
string text3 = Path.Combine(texturesFolder, filename);
return File.Exists(text3) ? text3 : null;
}
private static string GetHierarchyPath(Transform transform)
{
List<string> list = new List<string>();
while ((Object)(object)transform != (Object)null)
{
list.Insert(0, ((Object)transform).name);
transform = transform.parent;
}
return string.Join("/", list);
}
private static bool IsInIgnoredPath(GameObject obj)
{
string hierarchyPath = GetHierarchyPath(obj.transform);
foreach (string ignoredPathPattern in IgnoredPathPatterns)
{
if (hierarchyPath.Contains(ignoredPathPattern))
{
return true;
}
}
return false;
}
private static bool ShouldIgnoreScene(string sceneName)
{
return ignoredScenes.Any((string i) => sceneName.Equals(i, StringComparison.OrdinalIgnoreCase));
}
}
internal static class VideoPatcher
{
private sealed class VideoPatcherRunner : MonoBehaviour
{
}
private static bool _initialized;
private static bool _videoReplaced;
private static bool _prepareFailed;
private const string TargetSceneName = "1567f75bc4488644684d7a25471dbe95";
private const string VideoFileName = "5-S end video new.webm";
private static string _videoPath;
private static VideoPatcherRunner _runner;
private static VideoPlayer _currentPlayer;
private static Coroutine _retryCoroutine;
private static void Log(string message)
{
ManualLogSource loggerInstance = Plugin.LoggerInstance;
if (loggerInstance != null)
{
loggerInstance.LogInfo((object)("[TexturePatcher] " + message));
}
}
private static void LogWarn(string message)
{
ManualLogSource loggerInstance = Plugin.LoggerInstance;
if (loggerInstance != null)
{
loggerInstance.LogWarning((object)("[TexturePatcher] " + message));
}
}
private static void LogErr(string message)
{
ManualLogSource loggerInstance = Plugin.LoggerInstance;
if (loggerInstance != null)
{
loggerInstance.LogError((object)("[TexturePatcher] " + message));
}
}
public static void Initialize()
{
if (_initialized)
{
return;
}
string directoryName = Path.GetDirectoryName(typeof(VideoPatcher).Assembly.Location);
_videoPath = Path.Combine(directoryName ?? string.Empty, "5-S end video new.webm");
if (!File.Exists(_videoPath))
{
LogWarn("No se encontró el video traducido: " + _videoPath);
return;
}
CreateRunner();
if ((Object)(object)_runner == (Object)null)
{
LogErr("No se pudo crear el Coroutine Runner.");
return;
}
SceneManager.sceneLoaded += OnSceneLoaded;
_initialized = true;
}
private static void CreateRunner()
{
//IL_0017: Unknown result type (might be due to invalid IL or missing references)
//IL_001d: Expected O, but got Unknown
if (!((Object)(object)_runner != (Object)null))
{
GameObject val = new GameObject("TexturePatcher.VideoPatcherRunner");
Object.DontDestroyOnLoad((Object)(object)val);
_runner = val.AddComponent<VideoPatcherRunner>();
}
}
private static void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
//IL_0034: Unknown result type (might be due to invalid IL or missing references)
if (_initialized && !(((Scene)(ref scene)).name != "1567f75bc4488644684d7a25471dbe95"))
{
ClearVideoCallbacks();
_videoReplaced = false;
_prepareFailed = false;
StartRetryRoutine(scene);
}
}
private static void StartRetryRoutine(Scene scene)
{
//IL_005c: Unknown result type (might be due to invalid IL or missing references)
if ((Object)(object)_runner == (Object)null)
{
CreateRunner();
}
if ((Object)(object)_runner == (Object)null)
{
LogErr("No se pudo crear el Coroutine Runner.");
return;
}
if (_retryCoroutine != null)
{
((MonoBehaviour)_runner).StopCoroutine(_retryCoroutine);
_retryCoroutine = null;
}
_retryCoroutine = ((MonoBehaviour)_runner).StartCoroutine(TryReplaceWithRetries(scene));
}
private static IEnumerator TryReplaceWithRetries(Scene scene)
{
//IL_0007: Unknown result type (might be due to invalid IL or missing references)
//IL_0008: Unknown result type (might be due to invalid IL or missing references)
yield return null;
Scene activeScene;
for (int attempt = 0; attempt < 20; attempt++)
{
int num;
if (!_videoReplaced && ((Scene)(ref scene)).IsValid())
{
activeScene = SceneManager.GetActiveScene();
num = ((((Scene)(ref activeScene)).handle != ((Scene)(ref scene)).handle) ? 1 : 0);
}
else
{
num = 1;
}
if (num != 0)
{
break;
}
_prepareFailed = false;
if (TryReplaceFiveSVideo(scene))
{
float timer = 0f;
while (timer < 10f && !_videoReplaced && !_prepareFailed)
{
int num2;
if (((Scene)(ref scene)).IsValid())
{
activeScene = SceneManager.GetActiveScene();
num2 = ((((Scene)(ref activeScene)).handle != ((Scene)(ref scene)).handle) ? 1 : 0);
}
else
{
num2 = 1;
}
if (num2 != 0)
{
break;
}
timer += Time.unscaledDeltaTime;
yield return null;
}
if (_videoReplaced)
{
break;
}
ClearVideoCallbacks();
}
if (attempt < 19)
{
yield return (object)new WaitForSecondsRealtime(0.5f);
}
}
int num3;
if (!_videoReplaced && ((Scene)(ref scene)).IsValid())
{
activeScene = SceneManager.GetActiveScene();
num3 = ((((Scene)(ref activeScene)).handle == ((Scene)(ref scene)).handle) ? 1 : 0);
}
else
{
num3 = 0;
}
if (num3 != 0)
{
LogWarn("No se pudo localizar o reemplazar el VideoPlayer de 5-S.");
}
_retryCoroutine = null;
}
private static bool TryReplaceFiveSVideo(Scene scene)
{
//IL_0019: Unknown result type (might be due to invalid IL or missing references)
if (!((Scene)(ref scene)).IsValid())
{
return false;
}
GameObject val = FindRootObject(scene, "Exit Lobby Interior");
if ((Object)(object)val == (Object)null)
{
return false;
}
Transform val2 = val.transform.Find("Table top");
if ((Object)(object)val2 == (Object)null)
{
return false;
}
Transform val3 = val2.Find("TV");
if ((Object)(object)val3 == (Object)null)
{
return false;
}
Transform val4 = val3.Find("Screen");
if ((Object)(object)val4 == (Object)null)
{
return false;
}
VideoPlayer val5 = ((Component)val4).GetComponent<VideoPlayer>();
if ((Object)(object)val5 == (Object)null)
{
val5 = ((Component)val4).GetComponentInChildren<VideoPlayer>(true);
}
if ((Object)(object)val5 == (Object)null)
{
return false;
}
return ReplaceVideo(val5);
}
private static bool ReplaceVideo(VideoPlayer player)
{
//IL_0095: Unknown result type (might be due to invalid IL or missing references)
//IL_009f: Expected O, but got Unknown
//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
//IL_00b2: Expected O, but got Unknown
if (_videoReplaced || (Object)(object)player == (Object)null)
{
return _videoReplaced;
}
if (string.IsNullOrEmpty(_videoPath) || !File.Exists(_videoPath))
{
LogErr("No se encontró el video traducido: " + _videoPath);
return false;
}
try
{
ClearVideoCallbacks();
_currentPlayer = player;
_prepareFailed = false;
player.Stop();
player.source = (VideoSource)1;
player.url = _videoPath;
player.errorReceived += new ErrorEventHandler(OnVideoError);
player.prepareCompleted += new EventHandler(OnVideoPrepared);
player.Prepare();
return true;
}
catch (Exception ex)
{
LogErr("Error reemplazando el video de 5-S: " + ex);
ClearVideoCallbacks();
return false;
}
}
private static void OnVideoPrepared(VideoPlayer player)
{
//IL_0016: Unknown result type (might be due to invalid IL or missing references)
//IL_0020: Expected O, but got Unknown
if ((Object)(object)player == (Object)null)
{
return;
}
player.prepareCompleted -= new EventHandler(OnVideoPrepared);
try
{
player.Play();
_videoReplaced = true;
Log("Video de 5-S reemplazado correctamente.");
}
catch (Exception ex)
{
_prepareFailed = true;
LogErr("Error iniciando la reproducción: " + ex);
}
}
private static void OnVideoError(VideoPlayer player, string message)
{
if (!_videoReplaced)
{
_prepareFailed = true;
}
LogErr("Error del VideoPlayer: " + message);
}
private static void ClearVideoCallbacks()
{
//IL_001e: Unknown result type (might be due to invalid IL or missing references)
//IL_0028: Expected O, but got Unknown
//IL_0035: Unknown result type (might be due to invalid IL or missing references)
//IL_003f: Expected O, but got Unknown
if (!((Object)(object)_currentPlayer == (Object)null))
{
_currentPlayer.prepareCompleted -= new EventHandler(OnVideoPrepared);
_currentPlayer.errorReceived -= new ErrorEventHandler(OnVideoError);
_currentPlayer = null;
}
}
private static GameObject FindRootObject(Scene scene, string name)
{
GameObject[] rootGameObjects = ((Scene)(ref scene)).GetRootGameObjects();
foreach (GameObject val in rootGameObjects)
{
if (!((Object)(object)val == (Object)null))
{
if (((Object)val).name == name)
{
return val;
}
Transform val2 = FindChildRecursive(val.transform, name);
if ((Object)(object)val2 != (Object)null)
{
return ((Component)val2).gameObject;
}
}
}
return null;
}
private static Transform FindChildRecursive(Transform parent, string name)
{
//IL_0034: Unknown result type (might be due to invalid IL or missing references)
//IL_003b: Expected O, but got Unknown
if ((Object)(object)parent == (Object)null)
{
return null;
}
if (((Object)parent).name == name)
{
return parent;
}
foreach (Transform item in parent)
{
Transform parent2 = item;
Transform val = FindChildRecursive(parent2, name);
if ((Object)(object)val != (Object)null)
{
return val;
}
}
return null;
}
public static void Shutdown()
{
if (_initialized)
{
SceneManager.sceneLoaded -= OnSceneLoaded;
if ((Object)(object)_runner != (Object)null && _retryCoroutine != null)
{
((MonoBehaviour)_runner).StopCoroutine(_retryCoroutine);
_retryCoroutine = null;
}
ClearVideoCallbacks();
_videoReplaced = false;
_prepareFailed = false;
_initialized = false;
if ((Object)(object)_runner != (Object)null)
{
Object.Destroy((Object)(object)((Component)_runner).gameObject);
_runner = null;
}
}
}
}
}
namespace TexturePatcher.TexturePatcher.HarmonyPatches
{
[HarmonyPatch(typeof(FinalRank), "SetInfo")]
public static class FinalRank_SetInfo_Patch
{
[HarmonyPrefix]
private static void Prefix(FinalRank __instance)
{
if ((Object)(object)__instance.extraInfo != (Object)null)
{
__instance.extraInfo.text = StyleBonusStrings.TranslateBonus(__instance.extraInfo.text);
}
}
}
}