using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("Valheim10Compatibility.Adapter")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("BepInEx runtime adapter plugin for Valheim 1.0.")] [assembly: AssemblyFileVersion("1.4.1.0")] [assembly: AssemblyInformationalVersion("1.4.1+392146eab253da24bd329d86438263eeac9a4c7d")] [assembly: AssemblyProduct("Valheim10Compatibility.Adapter")] [assembly: AssemblyTitle("Valheim10Compatibility.Adapter")] [assembly: AssemblyVersion("1.4.1.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 Valheim10Compatibility.Adapter { [BepInPlugin("com.wubarrk.valheim10adapter", "Valheim10CompatibilityAdapter", "1.4.1")] public class AdapterPlugin : BaseUnityPlugin { public static class ObjectDBShield { [HarmonyPatch(typeof(ObjectDB), "UpdateRegisters")] [HarmonyPrefix] [HarmonyPriority(0)] public static void PrefixUpdateRegisters(ObjectDB __instance) { List list = __instance?.m_items; if (list == null) { return; } Dictionary dictionary = new Dictionary(list.Count); for (int i = 0; i < list.Count; i++) { GameObject val = list[i]; if (!((Object)(object)val == (Object)null)) { int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)val).name); if (dictionary.TryGetValue(stableHashCode, out var value)) { Log.LogWarning((object)$"[ObjectDBShield] Duplicate item prefab '{((Object)val).name}' (hash {stableHashCode}) in ObjectDB.m_items: kept the first registration ({Describe(value)}), dropped the later one ({Describe(val)}). Vanilla's Dictionary.Add would have thrown here and aborted FejdStartup.Start. A mod registered an item under a name Valheim 1.0 now uses itself; the game stays up, but that mod needs a 1.0 build."); list.RemoveAt(i--); } else { dictionary.Add(stableHashCode, val); } } } } private static string Describe(GameObject prefab) { string text = prefab.GetComponent()?.m_itemData?.m_shared?.m_name; if (!string.IsNullOrEmpty(text)) { return $"'{text}', instance {((Object)prefab).GetInstanceID()}"; } return $"no ItemDrop, instance {((Object)prefab).GetInstanceID()}"; } } public const string PluginGUID = "com.wubarrk.valheim10adapter"; public const string PluginName = "Valheim10CompatibilityAdapter"; public const string PluginVersion = "1.4.1"; private static ManualLogSource Log; private Harmony harmony; private static readonly FieldInfo AvailablePiecesByCategory = AccessTools.Field(typeof(PieceTable), "m_availablePiecesByCategory"); private void Awake() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; Log.LogInfo((object)"Valheim10CompatibilityAdapter v1.4.1 loading..."); harmony = new Harmony("com.wubarrk.valheim10adapter"); harmony.PatchAll(typeof(AdapterPlugin)); if (ReadObjectDBShieldSwitch()) { harmony.PatchAll(typeof(ObjectDBShield)); Log.LogInfo((object)"[ObjectDBShield] armed on ObjectDB.UpdateRegisters: a later item prefab whose name hash duplicates an earlier one is dropped (first registration wins) instead of aborting FejdStartup.Start."); } else { Log.LogWarning((object)"[ObjectDBShield] disabled in Valheim10Compatibility.cfg ([Shields] ObjectDBDuplicateItems = false); a duplicate item name hash aborts startup as on plain 1.0."); } Log.LogInfo((object)"Valheim10CompatibilityAdapter successfully patched runtime hooks."); } private static bool ReadObjectDBShieldSwitch() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) try { string configPath = Paths.ConfigPath; if (string.IsNullOrEmpty(configPath)) { return true; } return new ConfigFile(Path.Combine(configPath, "Valheim10Compatibility.cfg"), false) { SaveOnConfigSet = false }.Bind("Shields", "ObjectDBDuplicateItems", true, "Read by the adapter; the patcher writes this key's description.").Value; } catch (Exception ex) { Log.LogWarning((object)("[ObjectDBShield] Could not read Valheim10Compatibility.cfg (" + ex.GetType().Name + ": " + ex.Message + "); the shield stays on.")); return true; } } private void OnDestroy() { Harmony obj = harmony; if (obj != null) { obj.UnpatchSelf(); } } [HarmonyPatch(typeof(World), "SaveWorldFWLData", new Type[] { typeof(DateTime) })] [HarmonyPrefix] public static void PrefixSaveWorldFWLData(World __instance) { try { if (__instance == null || __instance.IsChunkedSave()) { return; } string dBPath = __instance.GetDBPath(); string saveFWLPath = __instance.GetSaveFWLPath(); if (File.Exists(dBPath)) { string text = Path.Combine(Path.GetDirectoryName(dBPath) ?? "", "pre_1.0_chunked_backups", __instance.m_name); Directory.CreateDirectory(text); string text2 = DateTime.Now.ToString("yyyyMMdd_HHmmss"); string text3 = Path.Combine(text, __instance.m_name + "_" + text2 + ".db"); File.Copy(dBPath, text3, overwrite: true); if (File.Exists(saveFWLPath)) { string destFileName = Path.Combine(text, __instance.m_name + "_" + text2 + ".fwl"); File.Copy(saveFWLPath, destFileName, overwrite: true); } Log.LogWarning((object)("[SaveWatchdog] World '" + __instance.m_name + "' is migrating from monolithic DB to Chunked Saves!")); Log.LogInfo((object)("[SaveWatchdog] Successfully generated pre-migration safety backup at: " + text3)); } } catch (Exception arg) { Log.LogError((object)$"[SaveWatchdog] Error executing pre-migration backup for world '{__instance?.m_name}': {arg}"); } } public static void EnsurePieceTableCapacity(PieceTable table, int requiredCategory = -1) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected I4, but got Unknown //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Invalid comparison between Unknown and I4 //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected I4, but got Unknown if ((Object)(object)table == (Object)null) { return; } int num = requiredCategory; if (num < 0) { num = (int)table.GetSelectedCategory(); } int num2 = Math.Max(num, 8); if (table.m_pieces != null) { foreach (GameObject piece in table.m_pieces) { if ((Object)(object)piece == (Object)null) { continue; } Piece component = piece.GetComponent(); if ((Object)(object)component != (Object)null && (int)component.m_category != 100) { int num3 = (int)component.m_category; if (num3 > num2 && num3 < 100) { num2 = num3; } } } } int num4 = num2 + 1; if (table.m_selectedPiece == null || table.m_selectedPiece.Length < num4) { Array.Resize(ref table.m_selectedPiece, num4); } if (table.m_lastSelectedPiece == null || table.m_lastSelectedPiece.Length < num4) { Array.Resize(ref table.m_lastSelectedPiece, num4); } if (AvailablePiecesByCategory?.GetValue(table) is List> { Count: >0 } list && list.Count < num4) { while (list.Count < num4) { list.Add(new List()); } } } [HarmonyPatch(typeof(PieceTable), "SetSelected")] [HarmonyPrefix] public static void PrefixSetSelected(PieceTable __instance) { EnsurePieceTableCapacity(__instance); } [HarmonyPatch(typeof(PieceTable), "SetCategory", new Type[] { typeof(int) })] [HarmonyPrefix] public static void PrefixSetCategory(PieceTable __instance, int index) { EnsurePieceTableCapacity(__instance, index); } [HarmonyPatch(typeof(PieceTable), "UpdateAvailable")] [HarmonyPrefix] public static void PrefixUpdateAvailable(PieceTable __instance) { EnsurePieceTableCapacity(__instance); } [HarmonyPatch(typeof(PieceTable), "LeftPiece")] [HarmonyPatch(typeof(PieceTable), "RightPiece")] [HarmonyPatch(typeof(PieceTable), "DownPiece")] [HarmonyPatch(typeof(PieceTable), "UpPiece")] [HarmonyPrefix] public static void PrefixPieceNavigation(PieceTable __instance) { EnsurePieceTableCapacity(__instance); } [HarmonyPatch(typeof(Hud), "UpdatePieceList")] [HarmonyFinalizer] public static Exception FinalizerUpdatePieceList(Exception __exception) { if (__exception != null) { Log.LogWarning((object)("[BuildMenuShield] Handled UI exception in Hud.UpdatePieceList: " + __exception.Message)); } return null; } [HarmonyPatch(typeof(ZNet), "SendPeerInfo")] [HarmonyPrefix] public static void PrefixSendPeerInfo(ZRpc rpc, string password) { Log.LogInfo((object)("[NetHandshake] Outgoing peer handshake to " + rpc.GetSocket().GetHostName() + " (adapter 1.4.1 for Valheim 1.0.x+; running game " + GameVersionText() + ", network version " + NetworkVersionText() + ").")); } private static string GameVersionText() { try { return Version.GetVersionString(false); } catch { return "unknown"; } } private static string NetworkVersionText() { try { FieldInfo field = typeof(Version).GetField("c_networkVersion", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field == null) { return "unknown"; } return (field.IsLiteral ? field.GetRawConstantValue() : field.GetValue(null))?.ToString() ?? "unknown"; } catch { return "unknown"; } } } }