Decompiled source of Sweet Russian Translate v0.3.0

SweetRussianTranslate.dll

Decompiled an hour ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;
using UnityEngine.Localization;
using UnityEngine.Localization.Settings;
using UnityEngine.Localization.Tables;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace SweetRussianTranslate
{
	internal static class HardcodedLabels
	{
		private static Dictionary<string, string> labels;

		internal static Dictionary<string, string> All
		{
			get
			{
				if (labels == null)
				{
					labels = new Dictionary<string, string>();
					foreach (KeyValuePair<string, string> item in Tsv.Read("Hardcoded.tsv"))
					{
						labels[item.Key] = item.Value;
					}
					Plugin.Log.LogInfo((object)("Loaded " + labels.Count + " hardcoded label replacements."));
				}
				return labels;
			}
		}

		internal static bool Translate(ref string text)
		{
			if (text != null && All.TryGetValue(text, out var value))
			{
				text = value;
				return true;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(SemiUI), "Start")]
	internal static class HardcodedLabelPatch
	{
		[HarmonyPostfix]
		private static void Postfix(SemiUI __instance)
		{
			if (HardcodedLabels.All.Count == 0)
			{
				return;
			}
			TMP_Text[] componentsInChildren = ((Component)__instance).GetComponentsInChildren<TMP_Text>(true);
			foreach (TMP_Text val in componentsInChildren)
			{
				string text = val.text;
				if (HardcodedLabels.Translate(ref text))
				{
					val.text = text;
				}
			}
		}
	}
	[HarmonyPatch(typeof(BigMessageUI), "BigMessage")]
	internal static class BigMessagePatch
	{
		[HarmonyPrefix]
		private static void Prefix(ref string message)
		{
			HardcodedLabels.Translate(ref message);
		}
	}
	[HarmonyPatch(typeof(ItemTracker), "DisplayColorOverride")]
	internal static class ItemTrackerDisplayPatch
	{
		[HarmonyPrefix]
		private static void Prefix(ref string _text)
		{
			HardcodedLabels.Translate(ref _text);
		}
	}
	[HarmonyPatch(typeof(ExtractionPoint), "TowerEvaluationTextUpdate")]
	internal static class TowerEvaluationTextPatch
	{
		[HarmonyPostfix]
		private static void Postfix(ExtractionPoint __instance)
		{
			TMP_Text haulGoalScreen = (TMP_Text)(object)__instance.haulGoalScreen;
			if (!((Object)(object)haulGoalScreen == (Object)null))
			{
				string text = haulGoalScreen.text;
				if (HardcodedLabels.Translate(ref text))
				{
					haulGoalScreen.text = text;
				}
			}
		}
	}
	[HarmonyPatch(typeof(ValuableScale), "UpdateText")]
	internal static class ValuableScaleTextPatch
	{
		[HarmonyPrefix]
		private static void Prefix(ref string _displayText)
		{
			HardcodedLabels.Translate(ref _displayText);
		}
	}
	[HarmonyPatch(typeof(LocalizationManager), "LoadLocalizationOverrides")]
	internal static class LocalizationOverridePatch
	{
		internal const string Russian = "ru-RU";

		private static readonly string[] TableNames = new string[3] { "HUD", "Menu", "Game" };

		private static bool fontReady;

		[HarmonyPostfix]
		private static void Postfix(Locale _locale)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			UseGameCyrillicFont();
			if ((Object)(object)_locale == (Object)null)
			{
				return;
			}
			LocaleIdentifier identifier = _locale.Identifier;
			if (((LocaleIdentifier)(ref identifier)).Code != "ru-RU")
			{
				return;
			}
			string[] tableNames = TableNames;
			foreach (string text in tableNames)
			{
				try
				{
					ApplyTable(text, _locale);
				}
				catch (Exception ex)
				{
					Plugin.Log.LogError((object)("Failed to apply " + text + ".tsv: " + ex.Message));
				}
			}
		}

		private static void ApplyTable(string tableName, Locale locale)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			List<KeyValuePair<string, string>> list = Tsv.Read(tableName + ".tsv");
			if (list.Count == 0)
			{
				return;
			}
			StringTable table = ((LocalizedDatabase<StringTable, StringTableEntry>)(object)LocalizationSettings.StringDatabase).GetTable(TableReference.op_Implicit(tableName), locale);
			if ((Object)(object)table == (Object)null)
			{
				Plugin.Log.LogError((object)("String table not found: " + tableName));
				return;
			}
			foreach (KeyValuePair<string, string> item in list)
			{
				StringTableEntry entry = ((DetailedLocalizationTable<StringTableEntry>)(object)table).GetEntry(item.Key);
				if (entry != null)
				{
					entry.Value = item.Value;
				}
				else
				{
					((DetailedLocalizationTable<StringTableEntry>)(object)table).AddEntry(item.Key, item.Value);
				}
			}
			Plugin.Log.LogInfo((object)("Applied " + list.Count + " strings to table " + tableName + "."));
		}

		private static void UseGameCyrillicFont()
		{
			if (fontReady)
			{
				return;
			}
			TMP_FontAsset val = null;
			TMP_FontAsset[] array = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
			foreach (TMP_FontAsset val2 in array)
			{
				if (((Object)val2).name.StartsWith("Oswald") && ((Object)val2).name.Contains("Cyrillic"))
				{
					val = val2;
					break;
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogWarning((object)"Game Cyrillic font not found yet, Russian text may show as squares on some screens.");
				return;
			}
			fontReady = true;
			List<TMP_FontAsset> fallbackFontAssets = TMP_Settings.fallbackFontAssets;
			if (fallbackFontAssets != null && !fallbackFontAssets.Contains(val))
			{
				fallbackFontAssets.Insert(0, val);
			}
			Plugin.Log.LogInfo((object)("Using the game's Cyrillic font: " + ((Object)val).name + "."));
		}
	}
	[HarmonyPatch(typeof(LocalizationManager), "Start")]
	internal static class SwitchToRussianOncePatch
	{
		[HarmonyPostfix]
		private static void Postfix(LocalizationManager __instance)
		{
			if (!Plugin.SwitchToRussian.Value)
			{
				return;
			}
			if (!__instance.Locales.TryGetValue("ru-RU", out var value))
			{
				Plugin.Log.LogWarning((object)"The game has no ru-RU language, leaving the language alone.");
				return;
			}
			if ((Object)(object)LocalizationSettings.SelectedLocale != (Object)(object)value.LocaleReference)
			{
				__instance.SwitchLocale(value, true);
				Plugin.Log.LogInfo((object)"Game language switched to Russian.");
			}
			Plugin.SwitchToRussian.Value = false;
		}
	}
	[BepInPlugin("sweet.russiantranslate", "Sweet Russian Translate", "0.3.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "sweet.russiantranslate";

		internal static ManualLogSource Log;

		internal static string ModFolder;

		internal static Plugin Instance;

		internal static ConfigEntry<bool> SwitchToRussian;

		private void Awake()
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			ModFolder = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			SwitchToRussian = ((BaseUnityPlugin)this).Config.Bind<bool>("Language", "Switch game to Russian on next start", true, "Перевод показывается, когда в игре выбран русский язык. Включено — при следующем запуске мод сам переключит игру на русский и выключит эту галку. Дальше язык выбираешь сам в настройках игры.");
			Harmony val = new Harmony("sweet.russiantranslate");
			val.PatchAll(Assembly.GetExecutingAssembly());
			int num = 0;
			foreach (MethodBase patchedMethod in val.GetPatchedMethods())
			{
				_ = patchedMethod;
				num++;
			}
			Log.LogInfo((object)("Sweet Russian Translate loaded from " + ModFolder + ", patched methods: " + num));
			TuneTextures();
		}

		private void TuneTextures()
		{
			if (!((BaseUnityPlugin)this).Config.Bind<bool>("Textures", "Translate textures", true, "Переводить надписи, нарисованные на текстурах: вывески комнат, плакаты, экраны. Выключи, если хочешь видеть их по-английски или подозреваешь их в тормозах. Меняется только при перезапуске игры.").Value)
			{
				Log.LogInfo((object)"Textures translation is off by config, signs stay English.");
			}
			else
			{
				TexturePatch.Init(ModFolder);
			}
		}
	}
	internal static class TexturePatch
	{
		private static readonly float[] ScanAt = new float[3] { 0f, 3f, 10f };

		private static readonly Dictionary<string, string> Files = new Dictionary<string, string>();

		private static readonly Dictionary<string, Texture2D> Loaded = new Dictionary<string, Texture2D>();

		private static readonly Dictionary<Shader, string[]> Properties = new Dictionary<Shader, string[]>();

		private static readonly HashSet<string> Done = new HashSet<string>();

		private static int replaced;

		internal static void Init(string modFolder)
		{
			string[] files = Directory.GetFiles(modFolder, "resources_*.png", SearchOption.AllDirectories);
			if (files.Length == 0)
			{
				Plugin.Log.LogWarning((object)("Картинок resources_*.png нет, надписи на текстурах останутся английскими: " + modFolder));
				return;
			}
			string[] array = files;
			foreach (string text in array)
			{
				string text2 = Key(Path.GetFileNameWithoutExtension(text));
				if (text2.Length != 0)
				{
					if (Files.ContainsKey(text2))
					{
						Plugin.Log.LogWarning((object)("Два файла на одно имя текстуры, беру первый: " + text));
					}
					else
					{
						Files[text2] = text;
					}
				}
			}
			Plugin.Log.LogInfo((object)("Текстур на подмену: " + Files.Count));
		}

		internal static IEnumerator AfterLevel()
		{
			if (Files.Count != 0)
			{
				float num = 0f;
				float[] scanAt = ScanAt;
				foreach (float at in scanAt)
				{
					yield return (object)new WaitForSeconds(at - num);
					num = at;
					Scan();
				}
			}
		}

		private static void Scan()
		{
			Material[] array = Resources.FindObjectsOfTypeAll<Material>();
			int num = replaced;
			Material[] array2 = array;
			foreach (Material val in array2)
			{
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Shader shader = val.shader;
				if ((Object)(object)shader == (Object)null)
				{
					continue;
				}
				string[] array3 = TextureProperties(shader);
				foreach (string text in array3)
				{
					Texture texture = val.GetTexture(text);
					if (!((Object)(object)texture == (Object)null))
					{
						Texture2D val2 = Ours(texture);
						if (!((Object)(object)val2 == (Object)null))
						{
							val.SetTexture(text, (Texture)(object)val2);
							replaced++;
							Done.Add(((Object)texture).name);
							Plugin.Log.LogInfo((object)("Текстура заменена: " + ((Object)texture).name + " (материал " + ((Object)val).name + ", " + text + ")"));
						}
					}
				}
			}
			if (replaced != num)
			{
				Plugin.Log.LogInfo((object)("Всего замен: " + replaced + ", разных картинок: " + Done.Count + " из " + Files.Count));
			}
		}

		private static string[] TextureProperties(Shader shader)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Invalid comparison between Unknown and I4
			if (Properties.TryGetValue(shader, out var value))
			{
				return value;
			}
			List<string> list = new List<string>();
			int propertyCount = shader.GetPropertyCount();
			for (int i = 0; i < propertyCount; i++)
			{
				if ((int)shader.GetPropertyType(i) == 4)
				{
					list.Add(shader.GetPropertyName(i));
				}
			}
			string[] array = list.ToArray();
			Properties[shader] = array;
			return array;
		}

		private static Texture2D Ours(Texture original)
		{
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			string text = Key(((Object)original).name);
			if (text.Length == 0)
			{
				return null;
			}
			string text2 = text + original.width + "x" + original.height;
			if (Files.ContainsKey(text2))
			{
				text = text2;
			}
			if (!Files.TryGetValue(text, out var value))
			{
				return null;
			}
			if (Loaded.TryGetValue(text, out var value2))
			{
				return value2;
			}
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, true, !original.isDataSRGB);
			if (!ImageConversion.LoadImage(val, File.ReadAllBytes(value), true))
			{
				Plugin.Log.LogWarning((object)("PNG не читается, пропускаю: " + value));
				Object.Destroy((Object)(object)val);
				Loaded[text] = null;
				return null;
			}
			((Object)val).name = ((Object)original).name + " RU";
			((Texture)val).wrapMode = original.wrapMode;
			((Texture)val).filterMode = original.filterMode;
			((Texture)val).anisoLevel = original.anisoLevel;
			((Object)val).hideFlags = (HideFlags)32;
			Loaded[text] = val;
			return val;
		}

		private static string Key(string name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return string.Empty;
			}
			StringBuilder stringBuilder = new StringBuilder(name.Length);
			foreach (char c in name)
			{
				if (char.IsLetterOrDigit(c))
				{
					stringBuilder.Append(char.ToLowerInvariant(c));
				}
			}
			string text = stringBuilder.ToString();
			if (!text.StartsWith("resources", StringComparison.Ordinal))
			{
				return text;
			}
			int j;
			for (j = "resources".Length; j < text.Length && char.IsDigit(text[j]); j++)
			{
			}
			if (j <= "resources".Length)
			{
				return text;
			}
			return text.Substring(j);
		}
	}
	[HarmonyPatch(typeof(LevelGenerator), "GenerateDone")]
	internal static class LevelDonePatch
	{
		[HarmonyPostfix]
		private static void Postfix(LevelGenerator __instance)
		{
			if (__instance.Generated)
			{
				((MonoBehaviour)Plugin.Instance).StartCoroutine(TexturePatch.AfterLevel());
			}
		}
	}
	internal static class Tsv
	{
		internal static List<KeyValuePair<string, string>> Read(string fileName)
		{
			List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
			string text = Path.Combine(Plugin.ModFolder, fileName);
			if (!File.Exists(text))
			{
				Plugin.Log.LogWarning((object)("Missing file: " + text));
				return list;
			}
			try
			{
				string[] array = File.ReadAllLines(text, Encoding.UTF8);
				foreach (string text2 in array)
				{
					if (!string.IsNullOrWhiteSpace(text2) && !text2.StartsWith("#"))
					{
						string[] array2 = text2.Split('\t');
						if (array2.Length == 2 && !string.IsNullOrWhiteSpace(array2[1]))
						{
							list.Add(new KeyValuePair<string, string>(array2[0], array2[1].Replace("\\n", "\n")));
						}
					}
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Failed to read " + fileName + ": " + ex.Message));
			}
			return list;
		}
	}
}