Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of CustomMobNames v1.0.0
CustomMobNames.dll
Decompiled 3 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("CustomMobNames")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("CustomMobNames")] [assembly: AssemblyTitle("CustomMobNames")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [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 CustomMobNames { [BepInPlugin("pabloss.valheim.custommobnames", "CustomMobNames", "1.0.0")] public class CustomMobNamesPlugin : BaseUnityPlugin { [HarmonyPatch(typeof(Character), "GetHoverName")] public static class CharacterHoverNamePatch { private static void Postfix(Character __instance, ref string __result) { if (!_enabledConfig.Value || (Object)(object)__instance == (Object)null || __instance.IsPlayer()) { return; } string prefabName = Utils.GetPrefabName(((Component)__instance).gameObject); if (string.IsNullOrEmpty(prefabName)) { return; } int characterLevel = GetCharacterLevel(__instance); string key = Math.Max(0, characterLevel - 1).ToString(); RegisterDiscoveredPrefab(prefabName, __result); lock (_syncLock) { if (!_mobTable.TryGetValue(prefabName, out var value) || value == null) { return; } string value3; string value4; if (_useSingleNameForAllStarsConfig.Value) { if (value.TryGetValue("default", out var value2) && !string.IsNullOrWhiteSpace(value2)) { __result = value2; } else if (value.TryGetValue("0", out value2) && !string.IsNullOrWhiteSpace(value2)) { __result = value2; } } else if (value.TryGetValue(key, out value3) && !string.IsNullOrWhiteSpace(value3)) { __result = value3; } else if (value.TryGetValue("default", out value4) && !string.IsNullOrWhiteSpace(value4)) { __result = value4; } } } } public const string PluginGUID = "pabloss.valheim.custommobnames"; public const string PluginName = "CustomMobNames"; public const string PluginVersion = "1.0.0"; private static ConfigEntry<bool> _enabledConfig; private static ConfigEntry<bool> _autoDiscoverMobsConfig; private static ConfigEntry<bool> _useSingleNameForAllStarsConfig; private static string _configDir; private static string _jsonPath; private static FileSystemWatcher _watcher; private static readonly object _syncLock = new object(); private static Dictionary<string, Dictionary<string, string>> _mobTable = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase); private void Awake() { _enabledConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enables or disables custom mob name overrides."); _autoDiscoverMobsConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AutoDiscoverMobs", true, "Automatically appends newly encountered mobs to mob_names.json."); _useSingleNameForAllStarsConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "UseSingleNameForAllStars", false, "Uses a single name (from 'default' or '0') across all star levels instead of per-star names."); _configDir = Path.Combine(Paths.ConfigPath, "CustomMobNames"); _jsonPath = Path.Combine(_configDir, "mob_names.json"); EnsureJsonExists(); LoadJson(); SetupFileWatcher(); Harmony.CreateAndPatchAll(typeof(CharacterHoverNamePatch), (string)null); ((BaseUnityPlugin)this).Logger.LogInfo((object)("CustomMobNames 1.0.0 loaded. Config file: " + _jsonPath)); } private void OnDestroy() { if (_watcher != null) { _watcher.EnableRaisingEvents = false; _watcher.Dispose(); } } private static void EnsureJsonExists() { Directory.CreateDirectory(_configDir); if (!File.Exists(_jsonPath)) { SaveJson(BuildDefaultMobCatalog()); } } private static Dictionary<string, string> CreateStarMap(string baseName) { return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "0", baseName }, { "1", baseName + " ★" }, { "2", baseName + " ★★" }, { "3", baseName + " ★★★" }, { "default", baseName } }; } private static Dictionary<string, Dictionary<string, string>> BuildDefaultMobCatalog() { string[] obj = new string[45] { "Boar", "Neck", "Deer", "Greyling", "Greydwarf", "Greydwarf_Elite", "Greydwarf_Shaman", "Troll", "Skeleton", "Skeleton_Poison", "Draugr", "Draugr_Elite", "Draugr_Ranged", "Blob", "BlobElite", "Leech", "Wraith", "Surtr", "Wolf", "Fenring", "Fenring_Cultist", "Drake", "StoneGolem", "Bat", "Ulv", "Lox", "Fuling", "Fuling_Berserker", "Fuling_Shaman", "Deathsquito", "GoblinBrute", "Seeker", "SeekerBrute", "SeekerBrood", "Tick", "Gjall", "Hare", "Charred_Melee", "Charred_Archer", "Charred_Twitcher", "Charred_Mage", "Asksvin", "Morgan", "BonemawSerpent", "Volture" }; Dictionary<string, Dictionary<string, string>> dictionary = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase); string[] array = obj; foreach (string text in array) { dictionary.Add(text, CreateStarMap(text)); } return dictionary; } private static void LoadJson() { lock (_syncLock) { if (!File.Exists(_jsonPath)) { return; } try { Dictionary<string, Dictionary<string, string>> dictionary = ParseMobTable(File.ReadAllText(_jsonPath, Encoding.UTF8)); if (dictionary != null && dictionary.Count > 0) { _mobTable = new Dictionary<string, Dictionary<string, string>>(dictionary, StringComparer.OrdinalIgnoreCase); } } catch (Exception ex) { Logger.CreateLogSource("CustomMobNames").LogError((object)("Failed to read mob_names.json: " + ex.Message)); } } } private static void SaveJson(Dictionary<string, Dictionary<string, string>> data) { string contents = SerializeMobTable(data); File.WriteAllText(_jsonPath, contents, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); } private static string EscapeJsonString(string value) { if (value == null) { return string.Empty; } StringBuilder stringBuilder = new StringBuilder(value.Length + 8); foreach (char c in value) { switch (c) { case '\\': stringBuilder.Append("\\\\"); break; case '"': stringBuilder.Append("\\\""); break; case '\n': stringBuilder.Append("\\n"); break; case '\r': stringBuilder.Append("\\r"); break; case '\t': stringBuilder.Append("\\t"); break; default: stringBuilder.Append(c); break; } } return stringBuilder.ToString(); } private static string SerializeMobTable(Dictionary<string, Dictionary<string, string>> data) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("{"); int num = 0; foreach (KeyValuePair<string, Dictionary<string, string>> datum in data) { num++; stringBuilder.Append(" \"").Append(EscapeJsonString(datum.Key)).AppendLine("\": {"); if (datum.Value != null) { int num2 = 0; foreach (KeyValuePair<string, string> item in datum.Value) { num2++; stringBuilder.Append(" \"").Append(EscapeJsonString(item.Key)).Append("\": \"") .Append(EscapeJsonString(item.Value)) .Append("\""); if (num2 < datum.Value.Count) { stringBuilder.Append(","); } stringBuilder.AppendLine(); } } stringBuilder.Append(" }"); if (num < data.Count) { stringBuilder.Append(","); } stringBuilder.AppendLine(); } stringBuilder.AppendLine("}"); return stringBuilder.ToString(); } private static Dictionary<string, Dictionary<string, string>> ParseMobTable(string json) { Dictionary<string, Dictionary<string, string>> dictionary = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase); if (string.IsNullOrWhiteSpace(json)) { return dictionary; } int pos = 0; SkipWhitespace(json, ref pos); if (pos >= json.Length || json[pos] != '{') { throw new FormatException("Expected '{' at start of JSON."); } for (pos++; pos < json.Length; pos++) { SkipWhitespace(json, ref pos); if (pos >= json.Length) { break; } if (json[pos] == '}') { pos++; break; } string text = ReadJsonString(json, ref pos); SkipWhitespace(json, ref pos); ExpectChar(json, ref pos, ':'); SkipWhitespace(json, ref pos); ExpectChar(json, ref pos, '{'); Dictionary<string, string> dictionary2 = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); for (; pos < json.Length; pos++) { SkipWhitespace(json, ref pos); if (pos < json.Length && json[pos] == '}') { pos++; break; } string key = ReadJsonString(json, ref pos); SkipWhitespace(json, ref pos); ExpectChar(json, ref pos, ':'); SkipWhitespace(json, ref pos); string value = ReadJsonString(json, ref pos); dictionary2[key] = value; SkipWhitespace(json, ref pos); if (pos >= json.Length || json[pos] != ',') { if (pos < json.Length && json[pos] == '}') { pos++; break; } throw new FormatException($"Unexpected token at position {pos} inside '{text}'."); } } dictionary[text] = dictionary2; SkipWhitespace(json, ref pos); if (pos >= json.Length || json[pos] != ',') { if (pos < json.Length && json[pos] == '}') { pos++; break; } throw new FormatException($"Unexpected token at position {pos} at root JSON level."); } } return dictionary; } private static void SkipWhitespace(string text, ref int pos) { while (pos < text.Length && char.IsWhiteSpace(text[pos])) { pos++; } } private static void ExpectChar(string text, ref int pos, char expected) { if (pos >= text.Length || text[pos] != expected) { throw new FormatException($"Expected '{expected}' at position {pos}."); } pos++; } private static string ReadJsonString(string text, ref int pos) { ExpectChar(text, ref pos, '"'); StringBuilder stringBuilder = new StringBuilder(); while (pos < text.Length) { char c = text[pos++]; switch (c) { case '"': return stringBuilder.ToString(); case '\\': { if (pos >= text.Length) { throw new FormatException("Unexpected end of string after '\\'."); } char c2 = text[pos++]; switch (c2) { case '"': stringBuilder.Append('"'); break; case '\\': stringBuilder.Append('\\'); break; case '/': stringBuilder.Append('/'); break; case 'b': stringBuilder.Append('\b'); break; case 'f': stringBuilder.Append('\f'); break; case 'n': stringBuilder.Append('\n'); break; case 'r': stringBuilder.Append('\r'); break; case 't': stringBuilder.Append('\t'); break; case 'u': { if (pos + 4 > text.Length) { throw new FormatException("Incomplete \\uXXXX escape sequence."); } string value = text.Substring(pos, 4); stringBuilder.Append((char)Convert.ToInt32(value, 16)); pos += 4; break; } default: stringBuilder.Append(c2); break; } break; } default: stringBuilder.Append(c); break; } } throw new FormatException("Unterminated string literal in JSON."); } private static void SetupFileWatcher() { _watcher = new FileSystemWatcher(_configDir, "mob_names.json") { NotifyFilter = (NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite), EnableRaisingEvents = true }; _watcher.Changed += delegate { Thread.Sleep(150); LoadJson(); }; } private static void RegisterDiscoveredPrefab(string prefabName, string fallbackDisplayName) { if (!_autoDiscoverMobsConfig.Value || string.IsNullOrEmpty(prefabName)) { return; } lock (_syncLock) { if (!_mobTable.ContainsKey(prefabName)) { string baseName = (string.IsNullOrEmpty(fallbackDisplayName) ? prefabName : fallbackDisplayName); _mobTable.Add(prefabName, CreateStarMap(baseName)); SaveJson(_mobTable); } } } private static int GetCharacterLevel(Character character) { if ((Object)(object)character == (Object)null) { return 1; } try { MethodInfo methodInfo = AccessTools.Method(typeof(Character), "GetLevel", (Type[])null, (Type[])null); if (methodInfo != null && methodInfo.Invoke(character, null) is int num && num > 0) { return num; } object? obj = AccessTools.Field(typeof(Character), "m_nview")?.GetValue(character); ZNetView val = (ZNetView)(((obj is ZNetView) ? obj : null) ?? ((Component)character).GetComponent<ZNetView>()); if ((Object)(object)val != (Object)null && val.IsValid()) { ZDO zDO = val.GetZDO(); if (zDO != null) { return Math.Max(1, zDO.GetInt("level", 1)); } } } catch { } return 1; } } }