// Consolidated decompiled source — Wubarrk-Fatty v1.0.2 // Generated by Hexium's decompiled-source browser. Best-effort concatenation of every type in this // version's manifest — decompiler output isn't guaranteed to compile as-is. using System; using System.Runtime.CompilerServices; using BepInEx.Configuration; using JetBrains.Annotations; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using HarmonyLib; using UnityEngine; using BepInEx; using TMPro; using BepInEx.Logging; using Fatty.Compat; using Fatty.Configuration; using System.Text.RegularExpressions; using BepInEx.Bootstrap; using Fatty.Synergies; using UnityEngine.UI; using Newtonsoft.Json; using ServerSync; // ---- plugins/Fatty.dll :: Microsoft.CodeAnalysis.EmbeddedAttribute ---- namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } // ---- plugins/Fatty.dll :: ServerSync.OwnConfigEntryBase ---- namespace ServerSync { [PublicAPI] public abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } } // ---- plugins/Fatty.dll :: ServerSync.SyncedConfigEntry`1 ---- namespace ServerSync { [PublicAPI] public class SyncedConfigEntry(ConfigEntry sourceConfig) : OwnConfigEntryBase { public readonly ConfigEntry SourceConfig = sourceConfig; public override ConfigEntryBase BaseConfig => SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } } // ---- plugins/Fatty.dll :: ServerSync.CustomSyncedValueBase ---- namespace ServerSync { public abstract class CustomSyncedValueBase { public object? LocalBaseValue; public readonly string Identifier; public readonly Type Type; private object? boxedValue; protected bool localIsOwner; public readonly int Priority; public object? BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action? ValueChanged; protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } } // ---- plugins/Fatty.dll :: ServerSync.CustomSyncedValue`1 ---- namespace ServerSync { [PublicAPI] public sealed class CustomSyncedValue : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } } // ---- plugins/Fatty.dll :: ServerSync.ConfigurationManagerAttributes ---- namespace ServerSync { internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } } // ---- plugins/Fatty.dll :: ServerSync.ConfigSync ---- namespace ServerSync { [PublicAPI] public class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { public static ZRpc? currentRpc; [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register(configSync2.Name + " ConfigSync", configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"); } } if (isServer) { __instance.StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ZNet.instance.StartCoroutine(configSync.sendZPackage(peers, package)); } } static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId"); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List CurrentList = new List(adminList.GetList()); while (true) { yield return new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List(adminList.GetList()); List list = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId != null) ? ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })) : adminList.Contains(hostName); }).ToList(); SendAdmin(ZNet.instance.GetPeers().Except(list).ToList(), isAdmin: false); SendAdmin(list, isAdmin: true); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register(configSync.Name + " ConfigSync", configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary configValues = new Dictionary(); public readonly Dictionary customValues = new Dictionary(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { private class BufferingSocket(ISocket original) : ZPlayFabSocket, ISocket { public volatile bool finished; public volatile int versionMatchQueued = -1; public readonly List Package = new List(); public readonly ISocket Original = original; public new bool IsConnected() { return Original.IsConnected(); } public new ZPackage Recv() { return Original.Recv(); } public new int GetSendQueueSize() { return Original.GetSendQueueSize(); } public new int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public new bool IsHost() { return Original.IsHost(); } public new void Dispose() { Original.Dispose(); } public new bool GotNewData() { return Original.GotNewData(); } public new void Close() { Original.Close(); } public new string GetEndPointString() { return Original.GetEndPointString(); } public new void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(out totalSent, out totalRecv); } public new void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(out localQuality, out remoteQuality, out ping, out outByteSec, out inByteSec); } public new ISocket Accept() { return Original.Accept(); } public new int GetHostPort() { return Original.GetHostPort(); } public new bool Flush() { return Original.Flush(); } public new string GetHostName() { return Original.GetHostName(); } public new void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public new void Send(ZPackage pkg) { int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == "PeerInfo".GetStableHashCode() || num == "RoutedRPC".GetStableHashCode() || num == "ZDOData".GetStableHashCode()) && !finished) { ZPackage zPackage = new ZPackage(pkg.GetArray()); zPackage.SetPos(pos); Package.Add(zPackage); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix(ref Dictionary? __state, ZNet __instance, ZRpc rpc) { if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); if (AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }).Invoke(__instance, new object[1] { rpc }) is ZNetPeer obj && ZNet.m_onlineBackend != OnlineBackendType.Steamworks) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); if (fieldInfo.GetValue(obj) is ZPlayFabSocket zPlayFabSocket) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, zPlayFabSocket.m_remotePlayerId); } fieldInfo.SetValue(obj, bufferingSocket); } if (__state == null) { __state = new Dictionary(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }).Invoke(__instance, new object[1] { rpc }); peer = obj as ZNetPeer; if (peer == null) { SendBufferedData(); } else { __instance.StartCoroutine(sendAsync()); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List list = new List(); if (configSync.CurrentVersion != null) { list.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId"); SyncedList syncedList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); list.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)methodInfo == null) ? ((object)syncedList.Contains(rpc.GetSocket().GetHostName())) : methodInfo.Invoke(ZNet.instance, new object[2] { syncedList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, list, partial: false); yield return __instance.StartCoroutine(configSync.sendZPackage(new List { peer }, package)); } SendBufferedData(); } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); if (AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }).Invoke(__instance, new object[1] { rpc }) is ZNetPeer obj2) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(obj2, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } } } private class PackageEntry { public string section; public string key; public Type type; public object? value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning($"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } private class InvalidDeserializationTypeException : Exception { public string expected; public string received; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet configSyncs; private readonly HashSet allConfigs = new HashSet(); private HashSet allCustomValues = new HashSet(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary> configValueCache = new Dictionary>(); private readonly List> cacheExpirations = new List>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0051; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (num) { return !lockExempt; } goto IL_0051; IL_0051: return false; } set { forceConfigLocking = value; } } public bool IsAdmin { get { if (!lockExempt) { return isSourceOfTruth; } return true; } } public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } public event Action? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry AddConfigEntry(ConfigEntry configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData(configEntry); SyncedConfigEntry syncedEntry = ownConfigEntryBase as SyncedConfigEntry; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "k__BackingField").SetValue(configEntry.Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(configEntry.Description.Tags ?? Array.Empty()).Concat(new SyncedConfigEntry[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry AddLockingConfigEntry(ConfigEntry lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { try { if (isServer && IsLocked) { string text = SnatchCurrentlyHandlingRPC.currentRpc?.GetSocket()?.GetHostName(); if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId"); SyncedList syncedList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? syncedList.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { syncedList, text })))) { return false; } } } cacheExpirations.RemoveAll(delegate(KeyValuePair kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out var value)) { value = new SortedDictionary(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4) != 0) { MemoryStream stream = new MemoryStream(package.ReadByteArray()); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile configFile = null; bool saveOnConfigSet = false; foreach (KeyValuePair configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (configFile == null) { configFile = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = configFile.SaveOnConfigSet; configFile.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (configFile != null) { configFile.SaveOnConfigSet = saveOnConfigSet; configFile.Save(); } foreach (KeyValuePair customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log(string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int num2 = 0; num2 < num; num2++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName); } else { Debug.LogWarning("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."); } continue; } Debug.LogWarning("Got invalid type " + text3 + ", abort reading of received configs"); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } if (!configSync.IsSourceOfTruth && config.SynchronizedConfig && config.LocalBaseValue != null) { if (!configSync.IsLocked) { if (config == configSync.lockedConfig) { return lockExempt; } return true; } return false; } return true; } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile configFile = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (configFile == null) { configFile = item.BaseConfig.ConfigFile; saveOnConfigSet = configFile.SaveOnConfigSet; configFile.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (configFile != null) { configFile.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer.m_socket.IsConnected()) { ZPackage zPackage = new ZPackage(); zPackage.Write((byte)2); zPackage.Write(packageIdentifier); zPackage.Write(fragment); zPackage.Write(fragments); zPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(zPackage); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer.m_rpc.Invoke(text, pkg); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, pkg); } } IEnumerable waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log($"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", ZNet.ConnectionStatus.ErrorConnectFailed); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!ZNet.instance) { return Enumerable.Empty().GetEnumerator(); } List list = (List)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List peers, ZPackage package) { if (!ZNet.instance) { yield break; } byte[] array = package.GetArray(); if (array != null && array.LongLength > 10000) { ZPackage zPackage = new ZPackage(); zPackage.Write((byte)4); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(memoryStream, System.IO.Compression.CompressionLevel.Optimal)) { deflateStream.Write(array, 0, array.Length); } zPackage.Write(memoryStream.ToArray()); package = zPackage; } List> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet.instance?.StartCoroutine(sendZPackage(target, package)); } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet.instance?.StartCoroutine(sendZPackage(target, package)); } } private static OwnConfigEntryBase? configData(ConfigEntryBase config) { return config.Description.Tags?.OfType().SingleOrDefault(); } public static SyncedConfigEntry? ConfigData(ConfigEntry config) { return config.Description.Tags?.OfType>().SingleOrDefault(); } private static T configAttribute(ConfigEntryBase config) { return config.Description.Tags.OfType().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { if (!type.IsEnum) { return type; } return Enum.GetUnderlyingType(type); } private static ZPackage ConfigsToPackage(IEnumerable? configs = null, IEnumerable? customValues = null, IEnumerable? packageEntries = null, bool partial = true) { List list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List(); List list2 = customValues?.ToList() ?? new List(); ZPackage zPackage = new ZPackage(); zPackage.Write(partial ? ((byte)1) : ((byte)0)); zPackage.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty()) { AddEntryToPackage(zPackage, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(zPackage, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(zPackage, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return zPackage; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, object? value) { Type type = value?.GetType(); if (value is Enum) { value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture); } else { if (value is ICollection collection) { package.Write(collection.Count); { foreach (object item in collection) { AddValueToZPackage(package, item); } return; } } if ((object)type != null && type.IsValueType && !type.IsPrimitive) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); package.Write(fields.Length); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { package.Write(GetZPackageTypeString(fieldInfo.FieldType)); AddValueToZPackage(package, fieldInfo.GetValue(value)); } return; } } ZRpc.Serialize(new object[1] { value }, ref package); } private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type) { if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); int num = package.ReadInt(); if (num != fields.Length) { throw new InvalidDeserializationTypeException { received = $"(field count: {num})", expected = $"(field count: {fields.Length})" }; } object uninitializedObject = FormatterServices.GetUninitializedObject(type); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { string text = package.ReadString(); if (text != GetZPackageTypeString(fieldInfo.FieldType)) { throw new InvalidDeserializationTypeException { received = text, expected = GetZPackageTypeString(fieldInfo.FieldType), field = fieldInfo.Name }; } fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType)); } return uninitializedObject; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { int num2 = package.ReadInt(); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type); Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments); FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic); for (int j = 0; j < num2; j++) { object obj = ReadValueWithTypeFromZPackage(package, type2); dictionary.Add(field.GetValue(obj), field2.GetValue(obj)); } return dictionary; } if (type != typeof(List) && type.IsGenericType) { Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]); if ((object)type3 != null && type3.IsAssignableFrom(type)) { int num3 = package.ReadInt(); object obj2 = Activator.CreateInstance(type); MethodInfo method = type3.GetMethod("Add"); for (int k = 0; k < num3; k++) { method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) }); } return obj2; } } ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo)); AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type); List parameters = new List(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref parameters); return parameters.First(); } } } // ---- plugins/Fatty.dll :: ServerSync.VersionCheck ---- namespace ServerSync { [PublicAPI] [HarmonyPatch] public class VersionCheck { private static readonly HashSet versionChecks; private static readonly Dictionary notProcessedNames; public string Name; private string? displayName; private string? currentVersion; private string? minimumRequiredVersion; public bool ModRequired = true; private string? ReceivedCurrentVersion; private string? ReceivedMinimumRequiredVersion; private readonly List ValidatedClients = new List(); private ConfigSync? ConfigSync; public string DisplayName { get { return displayName ?? Name; } set { displayName = value; } } public string CurrentVersion { get { return currentVersion ?? "0.0.0"; } set { currentVersion = value; } } public string MinimumRequiredVersion { get { string text = minimumRequiredVersion; if (text == null) { if (!ModRequired) { return "0.0.0"; } text = CurrentVersion; } return text; } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { Patches patchInfo = PatchProcessor.GetPatchInfo(AccessTools.DeclaredMethod(typeof(ZNet), "Awake")); if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony harmony = new Harmony("org.bepinex.helpers.ServerSync"); foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) }) where t.IsClass select t) { harmony.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet(); notProcessedNames = new Dictionary(); typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1] { new Action(PatchServerSync) }); } public VersionCheck(string name) { Name = name; ModRequired = true; versionChecks.Add(this); } public VersionCheck(ConfigSync configSync) { ConfigSync = configSync; Name = ConfigSync.Name; versionChecks.Add(this); } public void Initialize() { ReceivedCurrentVersion = null; ReceivedMinimumRequiredVersion = null; if (ConfigSync != null) { Name = ConfigSync.Name; DisplayName = ConfigSync.DisplayName; CurrentVersion = ConfigSync.CurrentVersion; MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion; ModRequired = ConfigSync.ModRequired; } } private bool IsVersionOk() { if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null) { return !ModRequired; } bool num = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion); bool flag = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion); return num && flag; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } if (!(new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion))) { return DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + "."; } return DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + "."; } private string ErrorServer(ZRpc rpc) { return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion; } private string Error(ZRpc? rpc = null) { if (rpc != null) { return ErrorServer(rpc); } return ErrorClient(); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray(); } private static void Logout() { Game.instance.Logout(); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, ZNet.ConnectionStatus.ErrorVersion); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", 3); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action? original) { string text = pkg.ReadString(); string text2 = pkg.ReadString(); string text3 = pkg.ReadString(); bool flag = false; foreach (VersionCheck versionCheck in versionChecks) { if (!(text != versionCheck.Name)) { Debug.Log("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."); versionCheck.ReceivedMinimumRequiredVersion = text2; versionCheck.ReceivedCurrentVersion = text3; if (ZNet.instance.IsServer() && versionCheck.IsVersionOk()) { versionCheck.ValidatedClients.Add(rpc); } flag = true; } } if (flag) { return; } pkg.SetPos(0); if (original != null) { original(rpc, pkg); if (pkg.GetPos() == 0) { notProcessedNames.Add(text, text3); } } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; for (int i = 0; i < array2.Length; i++) { Debug.LogWarning(array2[i].Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains("ServerSync VersionCheck".GetStableHashCode())) { object obj = dictionary["ServerSync VersionCheck".GetStableHashCode()]; Action action = (Action)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register("ServerSync VersionCheck", delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register("ServerSync VersionCheck", CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."); ZPackage zPackage = new ZPackage(); zPackage.Write(versionCheck.Name); zPackage.Write(versionCheck.MinimumRequiredVersion); zPackage.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", zPackage); } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] [HarmonyPrefix] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] [HarmonyPostfix] private static void ShowConnectionError(FejdStartup __instance) { if (!__instance.m_connectionFailedPanel.activeSelf || ZNet.GetConnectionStatus() != ZNet.ConnectionStatus.ErrorVersion) { return; } bool flag = false; VersionCheck[] failedClient = GetFailedClient(); if (failedClient.Length != 0) { string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error())); TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + text; flag = true; } foreach (KeyValuePair item in notProcessedNames.OrderBy((KeyValuePair kv) => kv.Key)) { if (!__instance.m_connectionFailedError.text.Contains(item.Key)) { TMP_Text connectionFailedError2 = __instance.m_connectionFailedError; connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed."; flag = true; } } if (flag) { RectTransform component = __instance.m_connectionFailedPanel.transform.Find("Image").GetComponent(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; __instance.m_connectionFailedError.ForceMeshUpdate(); float num = __instance.m_connectionFailedError.renderedHeight + 105f; RectTransform component2 = component.transform.Find("ButtonOk").GetComponent(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } } // ---- plugins/Fatty.dll :: Fatty.FattyPlugin ---- namespace Fatty { [BepInPlugin("wubarrk.fatty", "Fatty", "1.0.2")] public class FattyPlugin : BaseUnityPlugin { public const string PluginGUID = "wubarrk.fatty"; public const string PluginName = "Fatty"; public const string PluginVersion = "1.0.2"; private readonly Harmony _harmony = new Harmony("wubarrk.fatty"); public static FattyPlugin Instance { get; private set; } public ManualLogSource Log { get; private set; } private void Awake() { Instance = this; Log = base.Logger; FoodDurationMultiplierCompat.Initialize(); ConfigManager.Init(base.Config); CategoryManager.Init(); _harmony.PatchAll(); Log.LogInfo("Fatty v1.0.2 loaded successfully! Time to get fat."); } } } // ---- plugins/Fatty.dll :: Fatty.Synergies.SynergyEffects ---- namespace Fatty.Synergies { public static class SynergyEffects { private static bool _built; private static SE_Stats _balanced; private static SE_Stats _sugar; private static SE_Stats _fisher; private static SE_Stats _lumber; public static int BalancedDietHash { get; private set; } public static int SugarRushHash { get; private set; } public static int FishermanHash { get; private set; } public static int LumberjackHash { get; private set; } public static void Register(ObjectDB odb) { if (!(odb == null) && odb.m_StatusEffects != null) { if (!_built) { BuildEffects(); } AddIfMissing(odb, _balanced); AddIfMissing(odb, _sugar); AddIfMissing(odb, _fisher); AddIfMissing(odb, _lumber); } } private static void AddIfMissing(ObjectDB odb, StatusEffect se) { if (!(se == null) && odb.GetStatusEffect(se.NameHash()) == null) { odb.m_StatusEffects.Add(se); } } private static SE_Stats CreateBase(string internalName, string displayName, string tooltip) { SE_Stats sE_Stats = ScriptableObject.CreateInstance(); sE_Stats.name = internalName; sE_Stats.m_name = displayName; sE_Stats.m_tooltip = tooltip; sE_Stats.m_startMessage = displayName; sE_Stats.m_startMessageType = MessageHud.MessageType.TopLeft; sE_Stats.m_ttl = 0f; sE_Stats.m_healthRegenMultiplier = 1f; sE_Stats.m_staminaRegenMultiplier = 1f; sE_Stats.m_eitrRegenMultiplier = 1f; return sE_Stats; } private static void BuildEffects() { _balanced = CreateBase("SE_Fatty_BalancedDiet", "Balanced Diet", "A well-rounded meal.\nHealth & Stamina regeneration greatly increased."); float num = Mathf.Max(1f, ConfigManager.balancedDietRegen.Value); _balanced.m_healthRegenMultiplier = num; _balanced.m_staminaRegenMultiplier = num; _balanced.m_icon = SynergyIcons.Resolve("BalancedDiet", SynergyIcons.BalancedDiet); BalancedDietHash = _balanced.NameHash(); _sugar = CreateBase("SE_Fatty_SugarRush", "Sugar Rush", "Buzzing with energy!\nMovement speed greatly increased."); _sugar.m_speedModifier = Mathf.Max(0f, ConfigManager.sugarRushSpeedBonus.Value - 1f); _sugar.m_icon = SynergyIcons.Resolve("SugarRush", SynergyIcons.SugarRush); SugarRushHash = _sugar.NameHash(); _fisher = CreateBase("SE_Fatty_Fisherman", "Fisherman's Friend", "One with the water.\nImproved swim speed and reduced swim stamina use."); _fisher.m_swimSpeedModifier = 0.1f; _fisher.m_swimStaminaUseModifier = 0f - Mathf.Clamp01(ConfigManager.fishermanSwimStaminaReduction.Value); _fisher.m_icon = SynergyIcons.Resolve("Fisherman", SynergyIcons.Fisherman); FishermanHash = _fisher.NameHash(); _lumber = CreateBase("SE_Fatty_Lumberjack", "Lumberjack's Feast", "Fed and ready to fell forests.\nBonus carry weight and woodcutting damage."); _lumber.m_addMaxCarryWeight = ConfigManager.lumberjackCarryWeight.Value; _lumber.m_modifyAttackSkill = Skills.SkillType.WoodCutting; _lumber.m_damageModifier = ConfigManager.lumberjackWoodcuttingDamage.Value; _lumber.m_icon = SynergyIcons.Resolve("Lumberjack", SynergyIcons.Lumberjack); LumberjackHash = _lumber.NameHash(); _built = true; } } } // ---- plugins/Fatty.dll :: Fatty.Synergies.ObjectDB_Awake_Patch ---- namespace Fatty.Synergies { [HarmonyPatch(typeof(ObjectDB), "Awake")] public static class ObjectDB_Awake_Patch { [HarmonyPostfix] public static void Postfix(ObjectDB __instance) { try { SynergyEffects.Register(__instance); } catch (Exception arg) { FattyPlugin.Instance.Log.LogError($"Fatty Mod: Feature Lost - Synergy Registration (ObjectDB.Awake). Reason: {arg}"); } } } } // ---- plugins/Fatty.dll :: Fatty.Synergies.ObjectDB_CopyOtherDB_Patch ---- namespace Fatty.Synergies { [HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")] public static class ObjectDB_CopyOtherDB_Patch { [HarmonyPostfix] public static void Postfix(ObjectDB __instance) { try { SynergyEffects.Register(__instance); } catch (Exception arg) { FattyPlugin.Instance.Log.LogError($"Fatty Mod: Feature Lost - Synergy Registration (ObjectDB.CopyOtherDB). Reason: {arg}"); } } } } // ---- plugins/Fatty.dll :: Fatty.Synergies.SynergyIcons ---- namespace Fatty.Synergies { public static class SynergyIcons { private enum Emblem { Equals, Star, Wave, Tree } private const int Size = 64; private static readonly Color BackgroundColor = new Color(0.05f, 0.05f, 0.06f, 1f); private static MethodInfo _loadImage; private static readonly Color Gold = new Color(0.82f, 0.66f, 0.22f, 1f); private static readonly Color GoldLight = new Color(1f, 0.9f, 0.45f, 1f); public static Sprite Resolve(string baseName, Func proceduralFallback) { try { Sprite sprite = LoadEmbedded(baseName); if (sprite != null) { return sprite; } } catch (Exception ex) { FattyPlugin.Instance.Log.LogWarning("Fatty: could not load embedded icon '" + baseName + "': " + ex.Message); } try { return proceduralFallback?.Invoke(); } catch (Exception ex2) { FattyPlugin.Instance.Log.LogWarning("Fatty: could not draw fallback icon '" + baseName + "': " + ex2.Message); return null; } } private static Sprite LoadEmbedded(string baseName) { Assembly assembly = typeof(SynergyIcons).Assembly; string value = "." + baseName + ".png"; string[] manifestResourceNames = assembly.GetManifestResourceNames(); foreach (string text in manifestResourceNames) { if (!text.EndsWith(value, StringComparison.OrdinalIgnoreCase)) { continue; } using Stream stream = assembly.GetManifestResourceStream(text); if (stream == null) { continue; } using MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); byte[] data = memoryStream.ToArray(); Texture2D texture2D = new Texture2D(2, 2, TextureFormat.RGBA32, mipChain: false) { wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Bilinear, name = "Fatty_" + baseName }; if (!LoadPng(texture2D, data)) { UnityEngine.Object.Destroy(texture2D); return null; } FlattenAlpha(texture2D, BackgroundColor); return Sprite.Create(texture2D, new Rect(0f, 0f, texture2D.width, texture2D.height), new Vector2(0.5f, 0.5f), 100f); } return null; } private static bool LoadPng(Texture2D tex, byte[] data) { if (_loadImage == null) { Type type = AccessTools.TypeByName("UnityEngine.ImageConversion"); _loadImage = ((type != null) ? AccessTools.Method(type, "LoadImage", new Type[2] { typeof(Texture2D), typeof(byte[]) }) : null); } if (_loadImage == null) { return false; } object obj = _loadImage.Invoke(null, new object[2] { tex, data }); bool flag = default(bool); int num; if (obj is bool) { flag = (bool)obj; num = 1; } else { num = 0; } return (byte)((uint)num & (flag ? 1u : 0u)) != 0; } private static void FlattenAlpha(Texture2D tex, Color bg) { Color[] pixels = tex.GetPixels(); for (int i = 0; i < pixels.Length; i++) { Color color = pixels[i]; float a = color.a; pixels[i] = new Color(color.r * a + bg.r * (1f - a), color.g * a + bg.g * (1f - a), color.b * a + bg.b * (1f - a), 1f); } tex.SetPixels(pixels); tex.Apply(updateMipmaps: false, makeNoLongerReadable: false); } public static Sprite BalancedDiet() { return Build(new Color(0.34f, 0.68f, 0.32f), Emblem.Equals); } public static Sprite SugarRush() { return Build(new Color(0.88f, 0.36f, 0.66f), Emblem.Star); } public static Sprite Fisherman() { return Build(new Color(0.24f, 0.55f, 0.85f), Emblem.Wave); } public static Sprite Lumberjack() { return Build(new Color(0.7f, 0.45f, 0.22f), Emblem.Tree); } private static Sprite Build(Color baseColor, Emblem emblem) { Texture2D texture2D = new Texture2D(64, 64, TextureFormat.RGBA32, mipChain: false) { wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Bilinear, name = "Fatty_SynergyIcon" }; Color[] array = new Color[4096]; float num = 31.5f; float num2 = 30.08f; float num3 = 25.6f; Color a = Color.Lerp(baseColor, Color.white, 0.3f); for (int i = 0; i < 64; i++) { for (int j = 0; j < 64; j++) { float num4 = (float)j - num; float num5 = (float)i - num; float num6 = Mathf.Sqrt(num4 * num4 + num5 * num5); Color color; if (num6 > num2) { color = BackgroundColor; } else if (num6 > num3) { color = Gold; } else { float t = Mathf.Clamp01(num6 / num3); color = Color.Lerp(a, baseColor, t); float nx = num4 / num3; float ny = num5 / num3; if (InEmblem(emblem, nx, ny)) { color = GoldLight; } } if (num6 > num2 - 1f && num6 <= num2) { color = Color.Lerp(BackgroundColor, color, Mathf.Clamp01(num2 - num6)); } color.a = 1f; array[i * 64 + j] = color; } } texture2D.SetPixels(array); texture2D.Apply(updateMipmaps: false, makeNoLongerReadable: false); return Sprite.Create(texture2D, new Rect(0f, 0f, 64f, 64f), new Vector2(0.5f, 0.5f), 100f); } private static bool InEmblem(Emblem emblem, float nx, float ny) { switch (emblem) { case Emblem.Equals: if (Mathf.Abs(nx) < 0.52f) { if (!Between(ny, 0.14f, 0.32f)) { return Between(ny, -0.32f, -0.14f); } return true; } return false; case Emblem.Star: if (!(Mathf.Abs(nx) < 0.14f) || !(Mathf.Abs(ny) < 0.58f)) { if (Mathf.Abs(ny) < 0.14f) { return Mathf.Abs(nx) < 0.58f; } return false; } return true; case Emblem.Wave: { if (Mathf.Abs(nx) > 0.62f) { return false; } float num4 = 0.26f * Mathf.Sin(nx * MathF.PI * 2f); return Mathf.Abs(ny - num4) < 0.11f; } case Emblem.Tree: { float num = -0.5f; float num2 = 0.3f; if (Between(ny, num, num2)) { float num3 = 0.55f * ((ny - num) / (num2 - num)); if (Mathf.Abs(nx) <= num3) { return true; } } if (Mathf.Abs(nx) < 0.1f) { return Between(ny, 0.3f, 0.52f); } return false; } default: return false; } } private static bool Between(float v, float lo, float hi) { if (v >= lo) { return v <= hi; } return false; } } } // ---- plugins/Fatty.dll :: Fatty.Synergies.SynergyManager ---- namespace Fatty.Synergies { [HarmonyPatch] public static class SynergyManager { [HarmonyPatch(typeof(Player), "UpdateFood")] [HarmonyPostfix] public static void Player_UpdateFood_Postfix(Player __instance, ref List ___m_foods) { try { if (!(__instance == null)) { SEMan sEMan = __instance.GetSEMan(); if (sEMan != null) { bool value = ConfigManager.enableSynergies.Value; Dictionary dictionary = CountCategories(___m_foods); bool qualified = value && dictionary["Meat"] >= 1 && dictionary["Vegetable"] >= 1; bool qualified2 = value && dictionary["Sweet"] >= 3 && dictionary["Drink"] >= 1; bool qualified3 = value && dictionary["Fish"] >= 2 && dictionary["Vegetable"] >= 1; bool qualified4 = value && dictionary["Meat"] >= 3 && dictionary["Drink"] >= 1; ApplySynergy(sEMan, SynergyEffects.BalancedDietHash, qualified); ApplySynergy(sEMan, SynergyEffects.SugarRushHash, qualified2); ApplySynergy(sEMan, SynergyEffects.FishermanHash, qualified3); ApplySynergy(sEMan, SynergyEffects.LumberjackHash, qualified4); } } } catch (Exception arg) { FattyPlugin.Instance.Log.LogError($"Fatty Mod: Feature Lost - Dietary Synergies. Reason: {arg}"); } } private static Dictionary CountCategories(List foods) { Dictionary dictionary = new Dictionary { { "Meat", 0 }, { "Vegetable", 0 }, { "Sweet", 0 }, { "Drink", 0 }, { "Fish", 0 } }; if (foods == null) { return dictionary; } foreach (Player.Food food in foods) { if (food != null && food.m_item != null) { string categoryForPrefab = CategoryManager.GetCategoryForPrefab((food.m_item.m_dropPrefab != null) ? food.m_item.m_dropPrefab.name : food.m_name); if (dictionary.ContainsKey(categoryForPrefab)) { dictionary[categoryForPrefab]++; } } } return dictionary; } private static void ApplySynergy(SEMan seman, int nameHash, bool qualified) { if (nameHash != 0) { bool flag = seman.HaveStatusEffect(nameHash); if (qualified && !flag) { seman.AddStatusEffect(nameHash, resetTime: true); } else if (!qualified && flag) { seman.RemoveStatusEffect(nameHash); } } } } } // ---- plugins/Fatty.dll :: Fatty.Scanners.FoodScanner ---- namespace Fatty.Scanners { [HarmonyPatch] public static class FoodScanner { private static bool _hasScanned = false; private static readonly Regex WordSplitter = new Regex("[A-Z]?[a-z0-9]+|[A-Z0-9]+(?![a-z])", RegexOptions.Compiled); private static readonly HashSet DrinkWords = new HashSet { "tea", "coffee", "mead", "ale", "drink", "meadnog", "alenog", "shake", "smoothie", "shroomshake" }; private static readonly HashSet MeatWords = new HashSet { "meat", "steak", "pork", "sausage", "sausages", "meatbug" }; private static readonly HashSet SweetWords = new HashSet { "berry", "berries", "cake", "sweet", "honey", "vineberry" }; private static readonly HashSet FishWords = new HashSet { "fish", "salmon", "magmafish" }; private const int ItemsPerFrame = 100; private static void AddWords(string s, HashSet into) { if (string.IsNullOrEmpty(s)) { return; } foreach (Match item in WordSplitter.Matches(s)) { into.Add(item.Value.ToLowerInvariant()); } } [HarmonyPatch(typeof(ZNetScene), "Awake")] [HarmonyPostfix] public static void ZNetScene_Awake_Postfix(ZNetScene __instance) { try { if (!_hasScanned && !(__instance == null)) { __instance.StartCoroutine(ScanRoutine()); } } catch (Exception arg) { FattyPlugin.Instance.Log.LogError($"Fatty Mod: Feature Lost - Dynamic Food Scanner (start). Reason: {arg}"); } } [HarmonyPatch(typeof(Player), "OnSpawned")] [HarmonyPostfix] public static void Player_OnSpawned_Postfix(Player __instance) { try { if (!_hasScanned && !(__instance == null)) { __instance.StartCoroutine(ScanRoutine()); } } catch (Exception arg) { FattyPlugin.Instance.Log.LogError($"Fatty Mod: Feature Lost - Dynamic Food Scanner (spawn). Reason: {arg}"); } } private static IEnumerator ScanRoutine() { if (_hasScanned) { yield break; } _hasScanned = true; List list = null; bool flag = false; try { FattyPlugin.Instance.Log.LogInfo("Scanning ObjectDB for custom food items..."); ObjectDB instance = ObjectDB.instance; if (instance == null || instance.m_items == null) { FattyPlugin.Instance.Log.LogInfo("Fatty: ObjectDB not populated yet; deferring food scan until player spawn."); _hasScanned = false; } else { CategoryManager.EnsureBaseCategories(); Integrations.MapHardcodedIntegrations(CategoryManager.Categories); list = new List(instance.m_items); flag = true; } } catch (Exception arg) { FattyPlugin.Instance.Log.LogError($"Fatty Mod: Feature Lost - Dynamic Food Scanner (setup). Reason: {arg}"); _hasScanned = false; } if (!flag || list == null) { yield break; } bool categoryUpdated = false; int processed = 0; int foodFound = 0; foreach (GameObject item in list) { try { if (ProcessItem(item, ref foodFound)) { categoryUpdated = true; } } catch (Exception arg2) { FattyPlugin.Instance.Log.LogError($"Fatty Mod: Skipped a food item during scan. Reason: {arg2}"); } int num = processed + 1; processed = num; if (num % 100 == 0) { yield return null; } } if (categoryUpdated) { try { CategoryManager.Save(); } catch (Exception arg3) { FattyPlugin.Instance.Log.LogError($"Fatty Mod: Feature Lost - Food Data Save. Reason: {arg3}"); } } FattyPlugin.Instance.Log.LogInfo(string.Format("Fatty food scan complete: {0} food item(s) catalogued ({1}).", foodFound, categoryUpdated ? "data saved" : "no change")); } private static bool ProcessItem(GameObject item, ref int foodFound) { if (item == null) { return false; } ItemDrop component = item.GetComponent(); if (component == null || component.m_itemData == null || component.m_itemData.m_shared == null) { return false; } ItemDrop.ItemData.SharedData shared = component.m_itemData.m_shared; bool num = shared.m_food > 0f || shared.m_foodStamina > 0f || shared.m_foodEitr > 0f; bool flag = shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable; if (!num && !flag) { return false; } string prefabName = item.name; if (string.IsNullOrEmpty(prefabName)) { return false; } foodFound++; bool result = false; string text = CategoryManager.GetCategoryForPrefab(prefabName); if (text == "Unknown") { HashSet hashSet = new HashSet(); AddWords(shared.m_name, hashSet); AddWords(prefabName, hashSet); string text2 = (hashSet.Overlaps(DrinkWords) ? "Drink" : (hashSet.Overlaps(MeatWords) ? "Meat" : (hashSet.Overlaps(SweetWords) ? "Sweet" : ((!hashSet.Overlaps(FishWords)) ? "Vegetable" : "Fish")))); CategoryManager.AddToCategory(text2, prefabName); text = text2; result = true; FattyPlugin.Instance.Log.LogInfo("Auto-categorized new food '" + prefabName + "' as " + text2); } if (CategoryManager.AllFoodData.Find((CategoryManager.FoodData f) => f != null && f.PrefabName == prefabName) == null) { CategoryManager.AllFoodData.Add(new CategoryManager.FoodData { PrefabName = prefabName, InGameName = shared.m_name, Health = shared.m_food, Stamina = shared.m_foodStamina, Eitr = shared.m_foodEitr, Regen = shared.m_foodRegen, BurnTime = shared.m_foodBurnTime, Category = text }); result = true; } return result; } } } // ---- plugins/Fatty.dll :: Fatty.Scanners.Integrations ---- namespace Fatty.Scanners { public static class Integrations { public static bool IsValheimCuisineInstalled => Chainloader.PluginInfos.ContainsKey("XutzBR.ValheimCuisine"); public static void MapHardcodedIntegrations(Dictionary> categories) { if (IsValheimCuisineInstalled) { FattyPlugin.Instance.Log.LogInfo("Valheim Cuisine detected! Injecting hardcoded categories..."); CategoryManager.AddToCategory("Meat", "VC_NeckSoup"); CategoryManager.AddToCategory("Meat", "VC_ForestSkewer"); CategoryManager.AddToCategory("Meat", "VC_TrollStew"); CategoryManager.AddToCategory("Meat", "VC_BoarStew"); CategoryManager.AddToCategory("Meat", "VC_NeckStew"); CategoryManager.AddToCategory("Meat", "VC_SmokedBearStew"); CategoryManager.AddToCategory("Meat", "VC_FensalirSkause"); CategoryManager.AddToCategory("Meat", "VC_BloodyBroth"); CategoryManager.AddToCategory("Meat", "VC_TrollJerky"); CategoryManager.AddToCategory("Meat", "VC_ColdCuredNeck"); CategoryManager.AddToCategory("Meat", "VC_YdalirSkause"); CategoryManager.AddToCategory("Meat", "VC_UlvTailStew"); CategoryManager.AddToCategory("Meat", "VC_HatchlingSoup"); CategoryManager.AddToCategory("Meat", "VC_LoxJerky"); CategoryManager.AddToCategory("Meat", "VC_NeckBarleyStew"); CategoryManager.AddToCategory("Meat", "VC_AlfablotStew"); CategoryManager.AddToCategory("Meat", "VC_JarnbjornStew"); CategoryManager.AddToCategory("Meat", "VC_HareJerky"); CategoryManager.AddToCategory("Meat", "VC_TrollAspic"); CategoryManager.AddToCategory("Meat", "VC_ChickenStew"); CategoryManager.AddToCategory("Meat", "VC_HareStew"); CategoryManager.AddToCategory("Meat", "VC_DvergrMageBroth"); CategoryManager.AddToCategory("Meat", "VC_MorgenJerky"); CategoryManager.AddToCategory("Meat", "VC_Biksemad"); CategoryManager.AddToCategory("Meat", "VC_BonemawStew"); CategoryManager.AddToCategory("Meat", "VC_VarangianStew"); CategoryManager.AddToCategory("Meat", "VC_BonemawChowder"); CategoryManager.AddToCategory("Meat", "VC_SerpentChowder"); CategoryManager.AddToCategory("Meat", "VC_LyngbakrChowder"); CategoryManager.AddToCategory("Meat", "VC_RegalPorridge"); CategoryManager.AddToCategory("Meat", "VC_FolkvangrNattmal"); CategoryManager.AddToCategory("Meat", "VC_WolfWraps"); CategoryManager.AddToCategory("Meat", "VC_DvergrDagmal"); CategoryManager.AddToCategory("Meat", "VC_Bacon"); CategoryManager.AddToCategory("Meat", "VC_SmokedBoarHam"); CategoryManager.AddToCategory("Meat", "VC_SmokedDrakeHeart"); CategoryManager.AddToCategory("Meat", "VC_BoarHam"); CategoryManager.AddToCategory("Meat", "VC_BonemawHakarl"); CategoryManager.AddToCategory("Meat", "VC_Hakarl"); CategoryManager.AddToCategory("Meat", "VC_UncuredWolfSalami"); CategoryManager.AddToCategory("Meat", "VC_PickledEntrails"); CategoryManager.AddToCategory("Meat", "VC_UnfermentedPickledEntrails"); CategoryManager.AddToCategory("Fish", "VC_PikeFillets"); CategoryManager.AddToCategory("Fish", "VC_PerchSteak"); CategoryManager.AddToCategory("Fish", "VC_BloodmoonStew"); CategoryManager.AddToCategory("Fish", "VC_GrouperPottage"); CategoryManager.AddToCategory("Fish", "VC_CrispyPuffers"); CategoryManager.AddToCategory("Fish", "VC_DeepNorthRagout"); CategoryManager.AddToCategory("Fish", "VC_MunarvagrSkause"); CategoryManager.AddToCategory("Fish", "VC_JomsvikingStew"); CategoryManager.AddToCategory("Fish", "VC_Gravlaks"); CategoryManager.AddToCategory("Fish", "VC_HighlanderDagmal"); CategoryManager.AddToCategory("Fish", "VC_Stockfish"); CategoryManager.AddToCategory("Fish", "VC_PickledHerring"); CategoryManager.AddToCategory("Fish", "VC_UnfermentedPickledHerring"); CategoryManager.AddToCategory("Fish", "VC_UnfermentedRakfisk"); CategoryManager.AddToCategory("Fish", "VC_UnfermentedLutefisk"); CategoryManager.AddToCategory("Sweet", "VC_EctoplasmSoup"); CategoryManager.AddToCategory("Sweet", "VC_Lefse"); CategoryManager.AddToCategory("Sweet", "VC_Multekrem"); CategoryManager.AddToCategory("Sweet", "VC_CreamBastarde"); CategoryManager.AddToCategory("Sweet", "VC_Blodplattar"); CategoryManager.AddToCategory("Sweet", "VC_FruitBowl"); CategoryManager.AddToCategory("Sweet", "VC_HerbalRemedy"); CategoryManager.AddToCategory("Drink", "VC_PerryBroth"); CategoryManager.AddToCategory("Drink", "VC_GlowingStew"); CategoryManager.AddToCategory("Drink", "VC_PerryPorridge"); CategoryManager.AddToCategory("Drink", "VC_MistyFondue"); CategoryManager.AddToCategory("Drink", "VC_Bragafull"); CategoryManager.AddToCategory("Drink", "VC_PeasantDagmal"); CategoryManager.AddToCategory("Drink", "VC_VarangianDagmal"); CategoryManager.AddToCategory("Drink", "VC_SpicedPerry"); CategoryManager.AddToCategory("Drink", "VC_ShroomBeer"); CategoryManager.AddToCategory("Drink", "VC_UnfermentedSpicedPerry"); CategoryManager.AddToCategory("Drink", "VC_Blaand"); CategoryManager.AddToCategory("Drink", "VC_FulingBeer"); CategoryManager.AddToCategory("Drink", "VC_FulingBlaand"); CategoryManager.AddToCategory("Drink", "VC_Booze"); CategoryManager.AddToCategory("Drink", "VC_Tunnelrumbler"); CategoryManager.AddToCategory("Drink", "VC_Nogginfog"); } } } } // ---- plugins/Fatty.dll :: Fatty.Patches.HudPatches ---- namespace Fatty.Patches { [HarmonyPatch] public static class HudPatches { private class FoodGroup { public Player.Food Rep; public int Count; public float MaxTime; } private const int TargetSlots = 5; private static readonly Color GoldTrim = new Color(0.82f, 0.66f, 0.22f, 1f); private static readonly Color GoldText = new Color(1f, 0.86f, 0.35f, 1f); private static bool _customDrawReady; private static TMP_Text[] _countLabels; private static readonly List _groups = new List(); private static readonly Dictionary _groupIndex = new Dictionary(); [HarmonyPatch(typeof(Hud), "Awake")] [HarmonyPostfix] public static void Hud_Awake_Postfix(Hud __instance, ref Image[] ___m_foodIcons, ref Image[] ___m_foodBars, ref TMP_Text[] ___m_foodTime, RectTransform ___m_foodBarRoot) { _customDrawReady = false; _countLabels = null; try { if (___m_foodIcons == null || ___m_foodBars == null || ___m_foodTime == null) { Bail("food icon/bar/time arrays are null"); return; } int num = ___m_foodIcons.Length; if (num < 1 || ___m_foodBars.Length != num || ___m_foodTime.Length != num) { Bail($"food arrays empty or mismatched (icons={___m_foodIcons.Length}, bars={___m_foodBars.Length}, time={___m_foodTime.Length})"); return; } if (num < 5) { TryExpand(ref ___m_foodIcons, ref ___m_foodBars, ref ___m_foodTime, num); } int num2 = ___m_foodIcons.Length; TMP_Text[] array = new TMP_Text[num2]; TMP_Text template = FirstNonNull(___m_foodTime); for (int i = 0; i < num2; i++) { if (!(___m_foodIcons[i] == null)) { StyleIcon(___m_foodIcons[i]); array[i] = CreateCountLabel(___m_foodIcons[i].transform, template); } } _countLabels = array; _customDrawReady = true; FattyPlugin.Instance.Log.LogInfo($"Fatty: food HUD ready with {num2} slot(s); custom steady draw active."); } catch (Exception arg) { _customDrawReady = false; _countLabels = null; FattyPlugin.Instance.Log.LogError($"Fatty Mod: Feature Lost - Food HUD Setup. Reason: {arg}"); } } [HarmonyPatch(typeof(Hud), "UpdateFood")] [HarmonyPrefix] public static bool Hud_UpdateFood_Prefix(Hud __instance, Player player, Image[] ___m_foodIcons, Image[] ___m_foodBars, TMP_Text[] ___m_foodTime, RectTransform ___m_foodBarRoot, RectTransform ___m_foodBaseBar) { if (!_customDrawReady || player == null) { return true; } if (___m_foodIcons == null || ___m_foodBars == null || ___m_foodTime == null) { return true; } try { List foods = player.GetFoods(); _groups.Clear(); _groupIndex.Clear(); if (foods != null) { foreach (Player.Food item in foods) { if (item == null || item.m_item == null) { continue; } string text = ((item.m_item.m_dropPrefab != null) ? item.m_item.m_dropPrefab.name : item.m_name); if (string.IsNullOrEmpty(text)) { text = "?"; } if (_groupIndex.TryGetValue(text, out var value)) { FoodGroup foodGroup = _groups[value]; foodGroup.Count++; if (item.m_time > foodGroup.MaxTime) { foodGroup.MaxTime = item.m_time; } } else { _groupIndex[text] = _groups.Count; _groups.Add(new FoodGroup { Rep = item, Count = 1, MaxTime = item.m_time }); } } } if (___m_foodBaseBar != null) { ___m_foodBaseBar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, player.GetBaseFoodHP() / 25f * 32f); } int num = ___m_foodIcons.Length; for (int i = 0; i < num; i++) { Image image = ((i < ___m_foodIcons.Length) ? ___m_foodIcons[i] : null); Image image2 = ((i < ___m_foodBars.Length) ? ___m_foodBars[i] : null); TMP_Text tMP_Text = ((i < ___m_foodTime.Length) ? ___m_foodTime[i] : null); TMP_Text tMP_Text2 = ((_countLabels != null && i < _countLabels.Length) ? _countLabels[i] : null); bool flag = i < _groups.Count; if (image != null) { SetActiveSafe(image.transform, flag); } if (image2 != null) { SetActiveSafe(image2.transform, flag); } if (tMP_Text != null) { SetActiveSafe(tMP_Text.transform, flag); } if (flag) { FoodGroup foodGroup2 = _groups[i]; if (image != null && foodGroup2.Rep != null && foodGroup2.Rep.m_item != null) { image.sprite = foodGroup2.Rep.m_item.GetIcon(); image.color = Color.white; } if (tMP_Text != null) { float maxTime = foodGroup2.MaxTime; tMP_Text.text = ((maxTime >= 60f) ? (Mathf.CeilToInt(maxTime / 60f) + "m") : (Mathf.FloorToInt(maxTime) + "s")); tMP_Text.color = Color.white; } if (tMP_Text2 != null) { if (foodGroup2.Count > 1) { tMP_Text2.text = "x" + foodGroup2.Count; SetActiveSafe(tMP_Text2.transform, active: true); } else { SetActiveSafe(tMP_Text2.transform, active: false); } } } else if (tMP_Text2 != null) { SetActiveSafe(tMP_Text2.transform, active: false); } } if (___m_foodBarRoot != null) { ___m_foodBarRoot.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, Mathf.Ceil(player.GetMaxHealth() / 25f * 32f)); } return false; } catch (Exception arg) { FattyPlugin.Instance.Log.LogError($"Fatty Mod: Feature Lost - Food HUD Draw. Reason: {arg}"); return true; } } [HarmonyPatch(typeof(Hud), "UpdateStatusEffects")] [HarmonyPostfix] public static void Hud_UpdateStatusEffects_Postfix(List statusEffects, List ___m_statusEffects) { try { if (statusEffects == null || ___m_statusEffects == null) { return; } int num = Mathf.Min(statusEffects.Count, ___m_statusEffects.Count); for (int i = 0; i < num; i++) { StatusEffect statusEffect = statusEffects[i]; if (statusEffect == null) { continue; } int num2 = statusEffect.NameHash(); if (num2 != SynergyEffects.BalancedDietHash && num2 != SynergyEffects.SugarRushHash && num2 != SynergyEffects.FishermanHash && num2 != SynergyEffects.LumberjackHash) { continue; } RectTransform rectTransform = ___m_statusEffects[i]; if (!(rectTransform == null)) { Transform transform = rectTransform.Find("TimeBar"); if (transform != null) { transform.gameObject.SetActive(value: false); } Transform transform2 = rectTransform.Find("Cooldown"); if (transform2 != null) { transform2.gameObject.SetActive(value: false); } } } } catch (Exception arg) { FattyPlugin.Instance.Log.LogError($"Fatty Mod: Feature Lost - Synergy Status Icon Cleanup. Reason: {arg}"); } } private static void TryExpand(ref Image[] icons, ref Image[] bars, ref TMP_Text[] times, int existing) { if (existing < 2) { Bail("need >=2 existing slots to derive the layout spacing; keeping current count"); return; } if (icons[0] == null || icons[1] == null || bars[0] == null || bars[1] == null || times[0] == null || times[1] == null) { Bail("slot 0/1 has a null component; keeping current count"); return; } Image[] array = Grow(icons, 5); Image[] array2 = Grow(bars, 5); TMP_Text[] array3 = Grow(times, 5); List list = new List(); bool flag = ExpandArray(bars, array2, existing, list); bool flag2 = icons[0].transform.parent != icons[1].transform.parent; bool flag3 = (flag2 ? ExpandIconGroups(icons, times, array, array3, existing, list) : (ExpandArray(icons, array, existing, list) && ExpandArray(times, array3, existing, list))); if (!flag || !flag3) { DestroyClones(list); Bail($"could not build extra slots (bars ok: {flag}, icons ok: {flag3}); keeping {existing} slot(s)"); return; } icons = array; bars = array2; times = array3; FattyPlugin.Instance.Log.LogInfo(string.Format("Fatty: expanded food HUD {0} -> {1} slots (icons {2}).", existing, 5, flag2 ? "grouped" : "parallel")); } private static bool ExpandArray(T[] src, T[] dst, int existing, List created) where T : Component { for (int i = existing; i < 5; i++) { T val = CloneComponent(src[0], src[1], i, created); if (val == null) { return false; } dst[i] = val; } return true; } private static T CloneComponent(T template, T next, int slot, List created) where T : Component { if (template == null) { return null; } GameObject gameObject = UnityEngine.Object.Instantiate(template.gameObject, template.transform.parent); gameObject.name = template.gameObject.name + "_Fatty" + slot; created.Add(gameObject); T component = gameObject.GetComponent(); if (component == null) { return null; } if (template.transform is RectTransform rectTransform && next.transform is RectTransform rectTransform2 && gameObject.transform is RectTransform rectTransform3) { Vector2 vector = rectTransform2.anchoredPosition - rectTransform.anchoredPosition; rectTransform3.anchoredPosition = rectTransform.anchoredPosition + vector * slot; } return component; } private static bool ExpandIconGroups(Image[] icons, TMP_Text[] times, Image[] newIcons, TMP_Text[] newTimes, int existing, List created) { Transform parent = icons[0].transform.parent; Transform parent2 = icons[1].transform.parent; if (parent == null || parent2 == null) { return false; } string name = icons[0].name; string name2 = times[0].name; bool flag = times[0].transform.IsChildOf(parent); Vector2 vector = ((parent is RectTransform rectTransform) ? rectTransform.anchoredPosition : Vector2.zero); Vector2 vector2 = ((parent2 is RectTransform rectTransform2) ? (rectTransform2.anchoredPosition - vector) : Vector2.zero); if (vector2 == Vector2.zero) { return false; } for (int i = existing; i < 5; i++) { GameObject gameObject = UnityEngine.Object.Instantiate(parent.gameObject, parent.parent); gameObject.name = "Fatty_FoodSlot" + i; created.Add(gameObject); if (gameObject.transform is RectTransform rectTransform3) { rectTransform3.anchoredPosition = vector + vector2 * i; } Image image = FindComp(gameObject.transform, name); if (image == null) { return false; } newIcons[i] = image; if (flag) { TMP_Text tMP_Text = FindComp(gameObject.transform, name2); if (tMP_Text == null) { return false; } newTimes[i] = tMP_Text; } } if (!flag && !ExpandArray(times, newTimes, existing, created)) { return false; } return true; } private static void StyleIcon(Image icon) { if (!(icon == null) && !(icon.gameObject.GetComponent() != null)) { Outline outline = icon.gameObject.AddComponent(); outline.effectColor = GoldTrim; outline.effectDistance = new Vector2(2f, 2f); } } private static TMP_Text CreateCountLabel(Transform iconRoot, TMP_Text template) { if (iconRoot == null || template == null) { return null; } GameObject gameObject = UnityEngine.Object.Instantiate(template.gameObject, iconRoot); gameObject.name = "Fatty_StackCount"; TMP_Text component = gameObject.GetComponent(); if (component == null) { UnityEngine.Object.Destroy(gameObject); return null; } component.text = string.Empty; component.color = GoldText; component.fontStyle = FontStyles.Bold; component.alignment = TextAlignmentOptions.TopRight; component.raycastTarget = false; if (gameObject.transform is RectTransform rectTransform) { rectTransform.anchorMin = new Vector2(1f, 1f); rectTransform.anchorMax = new Vector2(1f, 1f); rectTransform.pivot = new Vector2(1f, 1f); rectTransform.anchoredPosition = new Vector2(-1f, -1f); } gameObject.transform.SetAsLastSibling(); gameObject.SetActive(value: false); return component; } private static void SetActiveSafe(Transform t, bool active) { if (t != null && t.gameObject.activeSelf != active) { t.gameObject.SetActive(active); } } private static void Bail(string reason) { FattyPlugin.Instance.Log.LogWarning("Fatty Mod: Food HUD expansion skipped - " + reason + "."); } private static T[] Grow(T[] src, int length) { T[] array = new T[length]; for (int i = 0; i < src.Length && i < length; i++) { array[i] = src[i]; } return array; } private static T FirstNonNull(T[] arr) where T : class { if (arr == null) { return null; } foreach (T val in arr) { if (val != null) { return val; } } return null; } private static void DestroyClones(List objs) { foreach (GameObject obj in objs) { if (obj != null) { UnityEngine.Object.Destroy(obj); } } } private static T FindComp(Transform root, string name) where T : Component { if (root.name == name) { T component = root.GetComponent(); if (component != null) { return component; } } for (int i = 0; i < root.childCount; i++) { T val = FindComp(root.GetChild(i), name); if (val != null) { return val; } } return null; } } } // ---- plugins/Fatty.dll :: Fatty.Patches.PlayerPatches ---- namespace Fatty.Patches { [HarmonyPatch] public static class PlayerPatches { private const int MaxFoodSlots = 4; private const int MaxDrinkSlots = 1; public static bool CanAddFood(List foods, ItemDrop.ItemData item, out string blockMessage) { blockMessage = null; if (item == null || item.m_shared == null) { return false; } string prefabName = GetPrefabName(item); bool flag = CategoryManager.GetCategoryForPrefab(prefabName) == "Drink"; int num = 0; HashSet hashSet = new HashSet(); HashSet hashSet2 = new HashSet(); if (foods != null) { foreach (Player.Food food in foods) { if (food != null && food.m_item != null && food.m_item.m_shared != null) { string prefabName2 = GetPrefabName(food.m_item); if (prefabName2 == prefabName) { num++; } if (CategoryManager.GetCategoryForPrefab(prefabName2) == "Drink") { hashSet2.Add(prefabName2); } else { hashSet.Add(prefabName2); } } } } int num2 = Mathf.Max(1, ConfigManager.maxFoodStacks.Value); if (num >= num2) { blockMessage = "You cannot eat any more of this right now!"; LogBlock(prefabName, flag, num, num2, hashSet.Count, hashSet2.Count, blockMessage); return false; } if (num == 0) { if (flag && hashSet2.Count >= 1) { blockMessage = "Drink slot is full!"; LogBlock(prefabName, flag, num, num2, hashSet.Count, hashSet2.Count, blockMessage); return false; } if (!flag && hashSet.Count >= 4) { blockMessage = "Food slots are full!"; LogBlock(prefabName, flag, num, num2, hashSet.Count, hashSet2.Count, blockMessage); return false; } } return true; } private static void LogBlock(string prefabName, bool isDrink, int sameFood, int maxStacks, int foodTypeCount, int drinkTypeCount, string reason) { FattyPlugin.Instance.Log.LogInfo(string.Format("[Fatty] Blocked eating '{0}' (category={1}, sameFood={2}/{3}, foodTypes={4}/{5}, drinkTypes={6}/{7}): {8}", prefabName, isDrink ? "Drink" : "Food", sameFood, maxStacks, foodTypeCount, 4, drinkTypeCount, 1, reason)); } private static string GetPrefabName(ItemDrop.ItemData item) { if (item == null || item.m_shared == null) { return string.Empty; } if (item.m_dropPrefab != null) { return item.m_dropPrefab.name; } return item.m_shared.m_name ?? string.Empty; } private static string GetPrefabName(Player.Food food) { if (food == null || food.m_item == null) { return string.Empty; } if (food.m_item.m_dropPrefab != null) { return food.m_item.m_dropPrefab.name; } return food.m_name ?? string.Empty; } private static float GetStackMultiplier(int stackIndex) { if (stackIndex <= 0) { return 1f; } return stackIndex switch { 1 => ConfigManager.stackDiminishingReturnStep1.Value, 2 => ConfigManager.stackDiminishingReturnStep2.Value, _ => ConfigManager.stackDiminishingReturnStep3.Value, }; } [HarmonyPatch(typeof(Player), "CanEat")] [HarmonyPrefix] public static bool CanEat_Prefix(Player __instance, ItemDrop.ItemData item, bool showMessages, ref bool __result) { try { if (item == null || item.m_shared == null) { return true; } string blockMessage; bool flag = CanAddFood(__instance.GetFoods(), item, out blockMessage); if (!flag && showMessages && !string.IsNullOrEmpty(blockMessage)) { __instance.Message(MessageHud.MessageType.Center, blockMessage); } __result = flag; return false; } catch (Exception arg) { FattyPlugin.Instance.Log.LogError($"Fatty Mod: Feature Lost - Eat Rules (CanEat). Reason: {arg}"); return true; } } [HarmonyPatch(typeof(Player), "EatFood")] [HarmonyPrefix] public static bool EatFood_Prefix(Player __instance, ItemDrop.ItemData item, ref List ___m_foods, ref bool __result) { try { if (item == null || item.m_shared == null) { return true; } if (!CanAddFood(___m_foods, item, out var blockMessage)) { if (!string.IsNullOrEmpty(blockMessage)) { __instance.Message(MessageHud.MessageType.Center, blockMessage); } __result = false; return false; } float durationMultiplier = FoodDurationMultiplierCompat.GetDurationMultiplier(); Player.Food food = new Player.Food { m_name = GetPrefabName(item), m_item = item, m_time = item.m_shared.m_foodBurnTime * durationMultiplier, m_health = item.m_shared.m_food, m_stamina = item.m_shared.m_foodStamina, m_eitr = item.m_shared.m_foodEitr }; ___m_foods.Add(food); string text = string.Empty; if (item.m_shared.m_food > 0f) { text = text + " +" + item.m_shared.m_food + " $item_food_health "; } if (item.m_shared.m_foodStamina > 0f) { text = text + " +" + item.m_shared.m_foodStamina + " $item_food_stamina "; } if (item.m_shared.m_foodEitr > 0f) { text = text + " +" + item.m_shared.m_foodEitr + " $item_food_eitr "; } if (!string.IsNullOrWhiteSpace(text)) { __instance.Message(MessageHud.MessageType.Center, text); } __instance.UpdateFood(0f, true); if (ConfigManager.debugMode.Value) { FattyPlugin.Instance.Log.LogInfo($"[Fatty Debug] Ate '{food.m_name}'. Total slots used: {___m_foods.Count}"); } __result = true; return false; } catch (Exception arg) { FattyPlugin.Instance.Log.LogError($"Fatty Mod: Feature Lost - Eat Handling (EatFood). Reason: {arg}"); return true; } } [HarmonyPatch(typeof(Player), "GetTotalFoodValue")] [HarmonyPostfix] public static void GetTotalFoodValue_Postfix(ref float hp, ref float stamina, ref float eitr, List ___m_foods, float ___m_baseHP, float ___m_baseStamina) { try { if (___m_foods == null || ___m_foods.Count == 0) { return; } bool value = ConfigManager.noFoodDecay.Value; float num = ___m_baseHP; float num2 = ___m_baseStamina; float num3 = 0f; Dictionary dictionary = new Dictionary(); foreach (Player.Food ___m_food in ___m_foods) { if (___m_food != null && ___m_food.m_item != null && ___m_food.m_item.m_shared != null) { ItemDrop.ItemData.SharedData shared = ___m_food.m_item.m_shared; string prefabName = GetPrefabName(___m_food); int value2; int num4 = (dictionary.TryGetValue(prefabName, out value2) ? value2 : 0); dictionary[prefabName] = num4 + 1; float stackMultiplier = GetStackMultiplier(num4); float num5 = 1f; if (!value) { float durationMultiplier = FoodDurationMultiplierCompat.GetDurationMultiplier(); float num6 = shared.m_foodBurnTime * durationMultiplier; num5 = ((num6 > 0f) ? Mathf.Pow(Mathf.Clamp01(___m_food.m_time / num6), 0.3f) : 0f); } num += shared.m_food * num5 * stackMultiplier; num2 += shared.m_foodStamina * num5 * stackMultiplier; num3 += shared.m_foodEitr * num5 * stackMultiplier; } } hp = num; stamina = num2; eitr = num3; } catch (Exception arg) { FattyPlugin.Instance.Log.LogError($"Fatty Mod: Feature Lost - Food Totals (GetTotalFoodValue). Reason: {arg}"); } } [HarmonyPatch(typeof(Player), "RemoveOneFood")] [HarmonyPrefix] public static bool RemoveOneFood_Prefix(Player __instance, ref List ___m_foods, ref bool __result) { try { if (___m_foods == null || ___m_foods.Count == 0) { __result = false; return false; } ___m_foods.Clear(); __instance.UpdateFood(0f, true); __result = true; return false; } catch (Exception arg) { FattyPlugin.Instance.Log.LogError($"Fatty Mod: Feature Lost - Puke Clears Stomach. Reason: {arg}"); return true; } } } } // ---- plugins/Fatty.dll :: Fatty.Configuration.CategoryManager ---- namespace Fatty.Configuration { public static class CategoryManager { public class FoodData { public string PrefabName { get; set; } public string InGameName { get; set; } public float Health { get; set; } public float Stamina { get; set; } public float Eitr { get; set; } public float Regen { get; set; } public float BurnTime { get; set; } public string Category { get; set; } } public static readonly string[] BaseCategories = new string[5] { "Meat", "Vegetable", "Sweet", "Fish", "Drink" }; private static string ConfigPath => Path.Combine(Paths.ConfigPath, "Fatty_FoodData.json"); public static Dictionary> Categories { get; private set; } = new Dictionary>(); public static List AllFoodData { get; private set; } = new List(); public static void Init() { if (File.Exists(ConfigPath)) { Load(); } else { GenerateDefaultCategories(); } EnsureBaseCategories(); } public static void EnsureBaseCategories() { string[] baseCategories = BaseCategories; foreach (string key in baseCategories) { if (!Categories.ContainsKey(key)) { Categories[key] = new List(); } } } public static void AddToCategory(string category, string prefabName) { if (!string.IsNullOrEmpty(category) && !string.IsNullOrEmpty(prefabName)) { if (!Categories.TryGetValue(category, out var value)) { value = new List(); Categories[category] = value; } if (!value.Contains(prefabName)) { value.Add(prefabName); } } } private static void GenerateDefaultCategories() { Categories["Meat"] = new List { "CookedMeat", "NeckTailGrilled", "DeerMeatCooked", "SerpentMeatCooked", "LoxMeatCooked", "WolfMeatCooked", "BugMeatCooked" }; Categories["Vegetable"] = new List { "Turnip", "Carrot", "Onion", "Mushroom", "MushroomYellow", "MushroomBlue" }; Categories["Sweet"] = new List { "Raspberry", "Blueberry", "Cloudberry", "Honey" }; Categories["Fish"] = new List { "FishRaw", "FishCooked" }; Categories["Drink"] = new List { "MeadTasty", "MeadHealthMinor", "MeadStaminaMinor" }; } public static void Load() { try { Categories.Clear(); AllFoodData.Clear(); AllFoodData = JsonConvert.DeserializeObject>(File.ReadAllText(ConfigPath)) ?? new List(); foreach (FoodData allFoodDatum in AllFoodData) { if (allFoodDatum != null && !string.IsNullOrWhiteSpace(allFoodDatum.Category) && !string.IsNullOrWhiteSpace(allFoodDatum.PrefabName)) { AddToCategory(allFoodDatum.Category, allFoodDatum.PrefabName); } } FattyPlugin.Instance.Log.LogInfo($"Successfully loaded Fatty_FoodData.json with {AllFoodData.Count} items."); } catch (Exception ex) { FattyPlugin.Instance.Log.LogError("Error loading FoodData JSON: " + ex.Message + ". Falling back to defaults."); Categories.Clear(); AllFoodData.Clear(); GenerateDefaultCategories(); } } public static void Save() { try { string contents = JsonConvert.SerializeObject((object)AllFoodData, (Formatting)1); File.WriteAllText(ConfigPath, contents); FattyPlugin.Instance.Log.LogInfo("Successfully updated Fatty_FoodData.json"); } catch (Exception ex) { FattyPlugin.Instance.Log.LogError("Error saving FoodData JSON: " + ex.Message); } } public static string GetCategoryForPrefab(string prefabName) { if (string.IsNullOrEmpty(prefabName)) { return "Unknown"; } foreach (KeyValuePair> category in Categories) { if (category.Value != null && category.Value.Contains(prefabName)) { return category.Key; } } return "Unknown"; } } } // ---- plugins/Fatty.dll :: Fatty.Configuration.ConfigManager ---- namespace Fatty.Configuration { public static class ConfigManager { private static readonly ConfigSync configSync = new ConfigSync("com.wubarrk.fatty") { DisplayName = "Fatty", CurrentVersion = "1.0.1", MinimumRequiredVersion = "1.0.1" }; public static ConfigEntry serverConfigLocked; public static ConfigEntry noFoodDecay; public static ConfigEntry maxFoodStacks; public static ConfigEntry debugMode; public static ConfigEntry stackDiminishingReturnStep1; public static ConfigEntry stackDiminishingReturnStep2; public static ConfigEntry stackDiminishingReturnStep3; public static ConfigEntry enableSynergies; public static ConfigEntry balancedDietRegen; public static ConfigEntry sugarRushSpeedBonus; public static ConfigEntry fishermanSwimStaminaReduction; public static ConfigEntry lumberjackCarryWeight; public static ConfigEntry lumberjackWoodcuttingDamage; public static void Init(ConfigFile config) { serverConfigLocked = config.Bind("1 - General", "Lock Configuration", defaultValue: true, "If on, the configuration is locked and can be changed by server admins only."); configSync.AddLockingConfigEntry(serverConfigLocked); noFoodDecay = BindSynced(config, "2 - Core", "No Food Decay", defaultValue: true, "Prevents food stats from decaying over time. Stats stay at full value until the food's timer expires."); maxFoodStacks = BindSynced(config, "2 - Core", "Max Food Stacks", 5, "Maximum number of times you can eat the same food at once (stacking)."); stackDiminishingReturnStep1 = BindSynced(config, "3 - Stacking", "Stack 2 Multiplier", 0.5f, "Stats multiplier for the 2nd stack of the same food (0.25 = 25%)."); stackDiminishingReturnStep2 = BindSynced(config, "3 - Stacking", "Stack 3 Multiplier", 0.25f, "Stats multiplier for the 3rd stack of the same food (0.05 = 5%)."); stackDiminishingReturnStep3 = BindSynced(config, "3 - Stacking", "Stack 4+ Multiplier", 0.05f, "Stats multiplier for the 4th and all further stacks of the same food (0.02 = 2%)."); enableSynergies = BindSynced(config, "4 - Synergies", "Enable Synergies", defaultValue: true, "Enables the dietary synergy status effects."); balancedDietRegen = BindSynced(config, "4 - Synergies", "Balanced Diet Regen Multiplier", 3f, "Balanced Diet (1 Meat + 1 Veggie): health & stamina regen multiplier. 2.0 = +100% regen."); sugarRushSpeedBonus = BindSynced(config, "4 - Synergies", "Sugar Rush Speed Multiplier", 2.5f, "Sugar Rush (3 Sweets + 1 Drink): movement speed multiplier. 1.30 = +30% speed."); fishermanSwimStaminaReduction = BindSynced(config, "4 - Synergies", "Fisherman Swim Stamina Reduction", 0.5f, "Fisherman's Friend (2 Fish + 1 Veggie): fraction of swim stamina drain removed. 0.25 = -25% drain."); lumberjackCarryWeight = BindSynced(config, "4 - Synergies", "Lumberjack Carry Weight Bonus", 100f, "Lumberjack's Feast (3 Meat + 1 Drink): bonus max carry weight."); lumberjackWoodcuttingDamage = BindSynced(config, "4 - Synergies", "Lumberjack Woodcutting Damage", 0.45f, "Lumberjack's Feast (3 Meat + 1 Drink): bonus woodcutting damage. 0.25 = +25%."); debugMode = config.Bind("5 - Debug", "Enable Debug Mode", defaultValue: false, "Enable verbose logging and dump data-driven food logs for developers."); } private static ConfigEntry BindSynced(ConfigFile config, string section, string key, T defaultValue, string description) { ConfigEntry configEntry = config.Bind(section, key, defaultValue, description); configSync.AddConfigEntry(configEntry); return configEntry; } } } // ---- plugins/Fatty.dll :: Fatty.Compat.FoodDurationMultiplierCompat ---- namespace Fatty.Compat { public static class FoodDurationMultiplierCompat { private static bool _initialized; private static bool _isInstalled; private static Type _pluginType; public static void Initialize() { if (!_initialized) { _initialized = true; if (Chainloader.PluginInfos.TryGetValue("blacks7ar.FoodDurationMultiplier", out var value)) { _isInstalled = true; _pluginType = value.Instance.GetType(); FattyPlugin.Instance.Log.LogInfo("Found blacks7ar.FoodDurationMultiplier, enabling compatibility."); } } } public static float GetDurationMultiplier() { if (!_isInstalled) { return 1f; } try { FieldInfo field = _pluginType.GetField("_durationMultiplier", BindingFlags.Static | BindingFlags.Public); if (field != null) { object value = field.GetValue(null); if (value != null) { PropertyInfo property = value.GetType().GetProperty("Value"); if (property != null) { return (float)property.GetValue(value); } } } } catch (Exception ex) { FattyPlugin.Instance.Log.LogWarning("Failed to read FoodDurationMultiplier._durationMultiplier: " + ex.Message); } return 1f; } } }