Decompiled source of Season 01 v1.21.1
plugins/Neobotics-HUDCompass/HUDCompass.dll
Decompiled 2 years agousing System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using HarmonyLib; using TMPro; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("HUDCompass")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HUDCompass")] [assembly: AssemblyCopyright("Copyright © 2024")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("9f8a1b6e-6d0e-4dab-bbd8-9ed433836544")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] internal sealed class ConfigurationManagerAttributes { public delegate void CustomHotkeyDrawerFunc(ConfigEntryBase setting, ref bool isCurrentlyAcceptingInput); public bool? ShowRangeAsPercent; public Action<ConfigEntryBase> CustomDrawer; public CustomHotkeyDrawerFunc CustomHotkeyDrawer; public bool? Browsable; public string Category; public object DefaultValue; public bool? HideDefaultButton; public bool? HideSettingName; public string Description; public string DispName; public int? Order; public bool? ReadOnly; public bool? IsAdvanced; public Func<object, string> ObjToStr; public Func<string, object> StrToObj; } namespace neobotics.ValheimMods; internal class DebugUtils { public static void ObjectInspector(object o) { if (o == null) { Debug.Log((object)"Object is null"); return; } BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; Type type = o.GetType(); Debug.Log((object)(o.ToString() + " Type " + type.Name)); PropertyInfo[] properties = type.GetProperties(bindingAttr); foreach (PropertyInfo propertyInfo in properties) { Debug.Log((object)$"{type.Name}.{propertyInfo.Name} = {propertyInfo.GetValue(o)}"); } FieldInfo[] fields = type.GetFields(bindingAttr); foreach (FieldInfo field in fields) { FieldPrinter(o, type, field); } } public static void MethodInspector(object o) { if (o == null) { Debug.Log((object)"Object is null"); return; } BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; Type type = o.GetType(); Debug.Log((object)(o.ToString() + " Type " + type.Name)); MethodInfo[] methods = type.GetMethods(bindingAttr); foreach (MethodInfo methodInfo in methods) { methodInfo.GetParameters(); string arg = string.Join(", ", (from x in methodInfo.GetParameters() select x.ParameterType?.ToString() + " " + x.Name).ToArray()); Debug.Log((object)$"{methodInfo.ReturnType} {methodInfo.Name} ({arg})"); } } private static void ItemDataInspector(ItemData item) { ObjectInspector(item); ObjectInspector(item.m_shared); } private static void FieldPrinter(object o, Type t, FieldInfo field) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Expected O, but got Unknown try { if (field.FieldType == typeof(ItemData)) { ItemData val = (ItemData)field.GetValue(o); if (val != null) { ItemDataInspector(val); } else { Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)} [null]"); } } else if (field.FieldType == typeof(Transform)) { Transform val2 = (Transform)field.GetValue(o); if ((Object)(object)val2 != (Object)null) { Debug.Log((object)("\tTransform.parent = " + ((Object)val2.parent).name)); } else { Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)} [null]"); } } else if (field.FieldType == typeof(EffectList)) { EffectList val3 = (EffectList)field.GetValue(o); if (val3 != null) { Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)}:"); EffectData[] effectPrefabs = val3.m_effectPrefabs; foreach (EffectData val4 in effectPrefabs) { Debug.Log((object)("\tEffectData.m_prefab = " + ((Object)val4.m_prefab).name)); } } else { Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)} [null]"); } } else { Debug.Log((object)$"{t.Name}.{field.Name} = {field.GetValue(o)}"); } } catch (Exception) { Debug.Log((object)("Exception accessing " + t?.Name + "." + field?.Name)); } } public static void GameObjectInspector(GameObject go) { Debug.Log((object)("\n\nInspecting GameObject " + ((Object)go).name)); ObjectInspector(go); Component[] componentsInChildren = go.GetComponentsInChildren<Component>(); foreach (Component val in componentsInChildren) { try { string obj = ((val != null) ? ((Object)val).name : null); object obj2; if (val == null) { obj2 = null; } else { Transform transform = val.transform; if (transform == null) { obj2 = null; } else { Transform parent = transform.parent; obj2 = ((parent != null) ? ((Object)parent).name : null); } } Debug.Log((object)("\n\nInspecting Component " + obj + " with parent " + (string?)obj2)); ObjectInspector(val); } catch (Exception) { } } } public static void ComponentInspector(Component c) { Debug.Log((object)("\n\nInspecting Component " + ((Object)c).name)); ObjectInspector(c); } public static void EffectsInspector(EffectList e) { EffectData[] effectPrefabs = e.m_effectPrefabs; Debug.Log((object)$"Effect list has effects {e.HasEffects()} count {effectPrefabs.Length}"); EffectData[] array = effectPrefabs; foreach (EffectData val in array) { Debug.Log((object)$"Effect Data {val} prefab name {((Object)val.m_prefab).name} prefab GameObject name {((Object)val.m_prefab.gameObject).name}"); } } public static void PrintInventory() { foreach (ItemData allItem in ((Humanoid)Player.m_localPlayer).GetInventory().GetAllItems()) { Debug.Log((object)allItem.m_shared.m_name); } } public static void PrintAllObjects() { ZNetScene.instance.m_prefabs.ForEach(delegate(GameObject x) { Debug.Log((object)("GameObject " + ((Object)x).name)); }); } public static void PrintAllCharacters() { Character.GetAllCharacters().ForEach(delegate(Character x) { Debug.Log((object)("Character " + ((Object)x).name)); }); } } public class DelegatedConfigEntry<T> : DelegatedConfigEntryBase { private ConfigEntry<T> _entry; private EventHandler rootHandler; private Action<object, EventArgs> clientDelegate; private Logging Log; public ConfigEntry<T> ConfigEntry { get { return _entry; } set { _entry = value; if (_entry != null && rootHandler != null) { _entry.SettingChanged += rootHandler; } Name = ((ConfigEntryBase)_entry).Definition.Key; Section = ((ConfigEntryBase)_entry).Definition.Section; ServerValue = ((ConfigEntryBase)_entry).GetSerializedValue(); Log.Trace("Set " + Section + " " + Name + " to serialized value " + ServerValue); } } public T Value { get { return _entry.Value; } set { _entry.Value = value; } } public DelegatedConfigEntry(bool useServerDelegate = false) : this((Action<object, EventArgs>)null, useServerDelegate) { } public DelegatedConfigEntry(Action<object, EventArgs> delegateHandler, bool useServerDelegate = false) { Log = Logging.GetLogger(); Log.Trace("DelegatedConfigEntry"); if (delegateHandler != null) { clientDelegate = delegateHandler; } if (useServerDelegate) { Log.Trace("Configuring server delegate"); rootHandler = delegate(object s, EventArgs e) { ServerDelegate(s, e); }; ServerConfiguration.ServerDelegatedEntries.Add(this); } else if (clientDelegate != null) { rootHandler = delegate(object s, EventArgs e) { clientDelegate(s, e); }; } } private void ServerDelegate(object sender, EventArgs args) { //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Expected O, but got Unknown Logging.GetLogger().Trace("ServerDelegate"); _entry.SettingChanged -= rootHandler; ZNet instance = ZNet.instance; bool? flag = ((instance != null) ? new bool?(instance.IsServer()) : null); if (flag.HasValue) { if (flag == false) { if (ServerValue != null) { ((ConfigEntryBase)_entry).SetSerializedValue(ServerValue); } } else { ServerValue = ((ConfigEntryBase)_entry).GetSerializedValue(); ServerConfiguration.Instance.SendConfigToAllClients(sender, (SettingChangedEventArgs)args); } } if (clientDelegate != null) { clientDelegate(sender, args); } _entry.SettingChanged += rootHandler; } public void EnableHandler(bool setActive) { if (setActive) { _entry.SettingChanged += rootHandler; } else { _entry.SettingChanged -= rootHandler; } } public bool IsKeyPressed() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) if (ConfigEntry is ConfigEntry<KeyboardShortcut> val) { KeyboardShortcut value = val.Value; foreach (KeyCode modifier in ((KeyboardShortcut)(ref value)).Modifiers) { if (!Input.GetKey(modifier)) { return false; } } if (!Input.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey)) { return false; } return true; } Log.Error("Keyboard read attempted on non-KeyboardShortcut config."); return false; } public bool IsKeyDown() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) if (ConfigEntry is ConfigEntry<KeyboardShortcut> val) { KeyboardShortcut value = val.Value; foreach (KeyCode modifier in ((KeyboardShortcut)(ref value)).Modifiers) { if (!Input.GetKey(modifier)) { return false; } } if (!Input.GetKey(((KeyboardShortcut)(ref value)).MainKey)) { return false; } return true; } Log.Error("Keyboard read attempted on non-KeyboardShortcut config."); return false; } public bool IsKeyReleased() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) if (ConfigEntry is ConfigEntry<KeyboardShortcut> val) { KeyboardShortcut value = val.Value; foreach (KeyCode modifier in ((KeyboardShortcut)(ref value)).Modifiers) { if (!Input.GetKeyUp(modifier)) { return false; } } if (!Input.GetKeyUp(((KeyboardShortcut)(ref value)).MainKey)) { return false; } return true; } Log.Error("Keyboard read attempted on non-KeyboardShortcut config."); return false; } } public class DelegatedConfigEntryBase { public string Name; public string Section; public string ServerValue; } internal class HarmonyHelper { public enum PatchType { Prefix, Postfix, Transpiler, Finalizer } private static Dictionary<string, string> detectionSet = new Dictionary<string, string>(); private static Dictionary<string, string> unpatchMods = new Dictionary<string, string>(); public static void GetDetectionSet(Dictionary<string, string> harmonyIds) { Logging logger = Logging.GetLogger(); foreach (KeyValuePair<string, string> harmonyId in harmonyIds) { if (Harmony.HasAnyPatches(harmonyId.Key)) { logger.Debug("Detected " + harmonyId.Value + " from Harmony"); if (!detectionSet.ContainsKey(harmonyId.Key)) { detectionSet.Add(harmonyId.Key, harmonyId.Value); } } else if (Chainloader.PluginInfos.ContainsKey(harmonyId.Key)) { logger.Debug("Detected " + harmonyId.Value + " from BepInEx"); if (!detectionSet.ContainsKey(harmonyId.Key)) { detectionSet.Add(harmonyId.Key, harmonyId.Value); } } } } public static void AddExclusion(string key) { if (detectionSet.ContainsKey(key)) { unpatchMods.Add(key, detectionSet[key]); } } public static void UnpatchMods(Harmony harmony) { Logging logger = Logging.GetLogger(); foreach (KeyValuePair<string, string> unpatchMod in unpatchMods) { logger.Warning("Not compatible with " + unpatchMod.Value); harmony.UnpatchAll(unpatchMod.Key); detectionSet.Remove(unpatchMod.Key); logger.Warning("Disabled " + unpatchMod.Value); } } public static bool IsModDetected(string key) { return detectionSet.ContainsKey(key); } public static bool IsModNameDetected(string value) { return detectionSet.ContainsValue(value); } public static bool TryGetDetectedModName(string key, out string mod) { return detectionSet.TryGetValue(key, out mod); } public static bool TryGetDetectedModKey(string value, out string key) { key = null; foreach (string key2 in detectionSet.Keys) { if (detectionSet[key2] == value) { key = key2; return true; } } return false; } public static string AddAnonymousPatch(string baseMethodName, PatchType patchType, string modName, string patchMethodName = null) { string text = null; int num = 0; Logging logger = Logging.GetLogger(); foreach (MethodBase item in Harmony.GetAllPatchedMethods().ToList()) { MethodBaseExtensions.HasMethodBody(item); Patches patchInfo = Harmony.GetPatchInfo(item); ReadOnlyCollection<Patch> readOnlyCollection = patchInfo.Prefixes; switch (patchType) { case PatchType.Postfix: readOnlyCollection = patchInfo.Postfixes; break; case PatchType.Prefix: readOnlyCollection = patchInfo.Prefixes; break; case PatchType.Transpiler: readOnlyCollection = patchInfo.Transpilers; break; case PatchType.Finalizer: readOnlyCollection = patchInfo.Finalizers; break; } foreach (Patch item2 in readOnlyCollection) { if (!item2.owner.StartsWith("harmony-auto") || !(item.Name == baseMethodName)) { continue; } if (patchMethodName != null) { if (item2.PatchMethod.Name == patchMethodName) { num++; text = item2.owner; } } else { num++; text = item2.owner; } } if (num == 1) { detectionSet.Add(text, modName); logger.Info($"Added unique anonymous {baseMethodName} {patchType}: {text} as {modName}"); } else if (num > 1) { text = null; logger.Warning($"Found multiple anonymous {baseMethodName} {patchType} entries. Can't identify correct patch to remove or modify."); } } if (num == 0) { logger.Info("No patch found for " + modName); } return text; } } public class IterativeStopwatch : Stopwatch { private double startMillis; private Logging Log = Logging.GetLogger(); public long Iterations { get; private set; } public double IterationMicroseconds { get; private set; } public double TotalElapsedMicroseconds { get; private set; } public double AverageMicroseconds { get; private set; } public IterativeStopwatch() { Iterations = 0L; } public new void Start() { startMillis = base.Elapsed.TotalMilliseconds; base.Start(); } public new void Stop() { base.Stop(); Iterations++; IterationMicroseconds = (base.Elapsed.TotalMilliseconds - startMillis) * 1000.0; TotalElapsedMicroseconds = base.Elapsed.TotalMilliseconds * 1000.0; AverageMicroseconds = TotalElapsedMicroseconds / (double)Iterations; } public new void Reset() { startMillis = 0.0; Iterations = 0L; base.Reset(); } public new void Restart() { startMillis = 0.0; Iterations = 0L; base.Restart(); } } public class Logging { public enum LogLevels { Critical, Error, Warning, Info, Debug, Trace } private static Logging _logger; public LogLevels LogLevel { get; set; } public string ModName { get; set; } private Logging(LogLevels level, string name) { LogLevel = level; ModName = name; } public static Logging GetLogger(LogLevels level, string name) { if (_logger == null) { _logger = new Logging(level, name); } return _logger; } public static Logging GetLogger() { if (_logger == null) { throw new NullReferenceException("Logger not initialized"); } return _logger; } public void Trace(string msg) { if (LogLevel >= LogLevels.Trace) { Debug.Log((object)Message(msg)); } } public void Debug(string msg) { if (LogLevel >= LogLevels.Debug) { Debug.Log((object)Message(msg)); } } public void Info(string msg) { if (LogLevel >= LogLevels.Info) { Debug.Log((object)Message(msg)); } } public void Warning(string msg) { if (LogLevel >= LogLevels.Warning) { Debug.LogWarning((object)Message(msg)); } } public void Error(string msg) { if (LogLevel >= LogLevels.Error) { Debug.LogWarning((object)Message(msg)); } } public void Error(Exception e) { Error(e, stackTrace: false); } public void Error(Exception e, bool stackTrace) { if (LogLevel >= LogLevels.Error) { Warning(Message(e.Message)); if (stackTrace) { Warning(e.StackTrace); } } } public void Critical(Exception e) { if (LogLevel >= LogLevels.Critical) { Debug(Message(e.Message)); Error(e.StackTrace); } } private string Message(string msg) { return ModName + ": " + msg; } public static void ChangeLogging(object s, EventArgs e) { SettingChangedEventArgs val = (SettingChangedEventArgs)(object)((e is SettingChangedEventArgs) ? e : null); GetLogger().Debug($"ChangeLog {val.ChangedSetting.Definition.Key} to {val.ChangedSetting.BoxedValue}"); GetLogger().LogLevel = Cfg.debugLevel.Value; } } public class ServerConfiguration { [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class ZNet_OnNewConnection_Patch { private static void Postfix(ZNet __instance, ZNetPeer peer) { Log.Debug("ZNet OnNewConnection postfix"); if (!__instance.IsServer()) { try { Log.Debug("Client registered RPC_ClientConfigReceiver"); peer.m_rpc.Register<ZPackage>("ClientConfigReceiver." + GetPluginGuid(), (Action<ZRpc, ZPackage>)RPC_ClientConfigReceiver); return; } catch (Exception) { Log.Warning("Failed to register RPC"); return; } } try { SendConfigToClient(peer); } catch (Exception) { Log.Warning("Error sending server configuration to client"); } } } public static List<DelegatedConfigEntryBase> ServerDelegatedEntries = new List<DelegatedConfigEntryBase>(); private static ConfigFile LocalConfig; private static BaseUnityPlugin Mod; private static string ConfigFileName; private static ServerConfiguration _instance; private static Logging Log; public static bool IsSetup = false; private const string NOT_CONFIGURED = "ServerConfiguration not initialized. Setup first."; public static ServerConfiguration Instance { get { if (_instance == null) { _instance = new ServerConfiguration(); } return _instance; } } private ServerConfiguration() { } public void Setup(ConfigFile config, BaseUnityPlugin modInstance) { LocalConfig = config; Log = Logging.GetLogger(); Log.Trace("ServerConfiguration Setup"); Mod = modInstance; ConfigFileName = Path.GetFileName(LocalConfig.ConfigFilePath); IsSetup = true; } public void CreateConfigWatcher() { string configFilePath = LocalConfig.ConfigFilePath; string fileName = Path.GetFileName(LocalConfig.ConfigFilePath); Log.Trace("Configuration File Watcher Setup"); FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(configFilePath.Substring(0, configFilePath.Length - fileName.Length), fileName); fileSystemWatcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.CreationTime; fileSystemWatcher.Changed += LoadConfig; fileSystemWatcher.Created += LoadConfig; fileSystemWatcher.IncludeSubdirectories = false; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private void LoadConfig(object sender, FileSystemEventArgs e) { if (!File.Exists(LocalConfig.ConfigFilePath)) { return; } try { Log.Debug($"Loading configuration {e.ChangeType}"); LocalConfig.Reload(); } catch { Log.Error("Error loading configuration file " + ConfigFileName); } } public static string GetPluginGuid() { return Mod.Info.Metadata.GUID; } public static void RPC_ClientConfigReceiver(ZRpc zrpc, ZPackage package) { if (!IsSetup) { Log.Error("ServerConfiguration not initialized. Setup first."); return; } Log.Debug("ClientConfigReceiver"); string section; string name; while (package.GetPos() < package.Size()) { section = package.ReadString(); name = package.ReadString(); string text = package.ReadString(); Log.Trace("Reading " + section + " " + name + " value " + text + " from ZPackage"); DelegatedConfigEntryBase delegatedConfigEntryBase = ServerDelegatedEntries.Find((DelegatedConfigEntryBase e) => e.Name == name && e.Section == section); if (delegatedConfigEntryBase != null) { Log.Trace("Found DCEB on client and setting to server value " + text); delegatedConfigEntryBase.ServerValue = text; } ConfigEntryBase val = LocalConfig[section, name]; if (val != null) { Log.Trace("Found local CEB and setting underlying config value " + text); val.SetSerializedValue(text); } } } internal static void WriteConfigEntries(ZPackage zpkg) { foreach (DelegatedConfigEntryBase serverDelegatedEntry in ServerDelegatedEntries) { Log.Trace("Writing " + serverDelegatedEntry.Section + " " + serverDelegatedEntry.Name + " value " + serverDelegatedEntry.ServerValue + " to ZPackage"); zpkg.Write(serverDelegatedEntry.Section); zpkg.Write(serverDelegatedEntry.Name); zpkg.Write(serverDelegatedEntry.ServerValue); } } internal static void SendConfigToClient(ZNetPeer peer) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown if (!IsSetup) { Log.Error("ServerConfiguration not initialized. Setup first."); return; } Log.Debug("ServerSendConfigToClient"); ZPackage val = new ZPackage(); WriteConfigEntries(val); peer.m_rpc.Invoke("ClientConfigReceiver." + GetPluginGuid(), new object[1] { val }); } public void SendConfigToAllClients(object o, SettingChangedEventArgs e) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown if (!IsSetup) { Log.Error("ServerConfiguration not initialized. Setup first."); } else if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer() && ZNet.instance.GetPeerConnections() > 0) { Log.Debug("SendConfigToAllClients"); ZPackage zpkg = new ZPackage(); WriteConfigEntries(zpkg); ((MonoBehaviour)Mod).StartCoroutine(_instance.Co_BroadcastConfig(zpkg)); } } private IEnumerator Co_BroadcastConfig(ZPackage zpkg) { Log.Debug("Co_BroadcastConfig"); List<ZNetPeer> connectedPeers = ZNet.instance.GetConnectedPeers(); foreach (ZNetPeer item in connectedPeers) { if (item != ZNet.instance.GetServerPeer()) { item.m_rpc.Invoke("ClientConfigReceiver." + GetPluginGuid(), new object[1] { zpkg }); } yield return null; } } } internal class Utils { public static TEnum Guardrails<TEnum>(string value, TEnum enumDefault) where TEnum : struct { if (Enum.TryParse<TEnum>(value, ignoreCase: true, out var result)) { return result; } return enumDefault; } public static int Guardrails(int value, int lbound, int ubound) { if (value < lbound) { return lbound; } if (value > ubound) { return ubound; } return value; } public static float Guardrails(float value, float lbound, float ubound) { if (value < lbound) { return lbound; } if (value > ubound) { return ubound; } return value; } public static string UnClonifiedName(string name) { if (name == null) { return null; } int num = name.IndexOf("(Clone)"); if (num < 1) { return name; } return name.Substring(0, num); } public static void SetTranslator(int id, string idText) { typeof(Localization).GetMethod("AddWord", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(Localization.instance, new object[2] { "skill_" + id, idText }); } public static string GetTranslated(int id) { Logging.GetLogger().Debug(string.Format("Got translation for id {0} to {1}", id, Localization.instance.Localize("skill_" + id))); return Localization.instance.Localize("$skill_" + id); } public static Sprite GetPrefabIcon(string prefabName) { Sprite result = null; GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(prefabName); ItemDrop val = default(ItemDrop); if ((Object)(object)itemPrefab != (Object)null && itemPrefab.TryGetComponent<ItemDrop>(ref val)) { result = val.m_itemData.GetIcon(); } return result; } public static Player GetPlayerByZDOID(ZDOID zid) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) foreach (Player allPlayer in Player.GetAllPlayers()) { ZDOID zDOID = ((Character)allPlayer).GetZDOID(); if (((ZDOID)(ref zDOID)).Equals(zid)) { return allPlayer; } } return null; } public static Character GetCharacterByZDOID(string cid) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) foreach (Character allCharacter in Character.GetAllCharacters()) { ZDOID zDOID = allCharacter.GetZDOID(); if (((object)(ZDOID)(ref zDOID)).ToString().Equals(cid)) { return allCharacter; } } return null; } public static Character GetCharacterByZDOID(ZDOID cid) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) foreach (Character allCharacter in Character.GetAllCharacters()) { ZDOID zDOID = allCharacter.GetZDOID(); if (((ZDOID)(ref zDOID)).Equals(cid)) { return allCharacter; } } return null; } public static ZNetPeer GetPeerByRPC(ZRpc rpc) { foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { if (peer.m_rpc == rpc) { return peer; } } return null; } public static List<GameObject> GetGameObjectsOfType(Type t) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) List<GameObject> list = new List<GameObject>(); Object[] array = Object.FindObjectsOfType(t); foreach (Object val in array) { list.Add(((Component)val).gameObject); } return list; } public static GameObject GetClosestGameObjectOfType(Type t, Vector3 point, float radius) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return GetGameObjectsOfTypeInRangeByDistance(t, point, radius)?[0]; } public static List<GameObject> GetGameObjectsOfTypeInRangeByDistance(Type t, Vector3 point, float radius) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) List<KeyValuePair<GameObject, float>> list = new List<KeyValuePair<GameObject, float>>(); List<GameObject> gameObjectsOfTypeInRange = GetGameObjectsOfTypeInRange(t, point, radius); if (gameObjectsOfTypeInRange.Count > 0) { foreach (GameObject item in gameObjectsOfTypeInRange) { list.Add(new KeyValuePair<GameObject, float>(item, Vector3.Distance(item.transform.position, point))); } list.Sort((KeyValuePair<GameObject, float> pair1, KeyValuePair<GameObject, float> pair2) => pair1.Value.CompareTo(pair2.Value)); return list.ConvertAll((KeyValuePair<GameObject, float> x) => x.Key); } return null; } public static List<GameObject> GetGameObjectsOfTypeInRange(Type t, Vector3 point, float radius) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) return (from x in GetGameObjectsOfType(t) where Vector3.Distance(x.transform.position, point) < radius select x).ToList(); } public static float GetPointDepth(Vector3 p) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) return ZoneSystem.instance.m_waterLevel - GetSolidHeight(p); } public static List<string> GetDelimitedStringAsList(string delimitedString, char delimiter) { List<string> list = new List<string>(); string[] array = delimitedString.Split(new char[1] { delimiter }, StringSplitOptions.RemoveEmptyEntries); foreach (string text in array) { list.Add(text.Trim()); } return list; } public static float GetSolidHeight(Vector3 p) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) int solidRayMask = ZoneSystem.instance.m_solidRayMask; float result = 0f; p.y += 1000f; RaycastHit val = default(RaycastHit); if (Physics.Raycast(p, Vector3.down, ref val, 2000f, solidRayMask) && !Object.op_Implicit((Object)(object)((RaycastHit)(ref val)).collider.attachedRigidbody)) { result = ((RaycastHit)(ref val)).point.y; } return result; } public static Transform FindChild(Transform aParent, string aName) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown foreach (Transform item in aParent) { Transform val = item; if (((Object)val).name == aName) { return val; } Transform val2 = FindChild(val, aName); if ((Object)(object)val2 != (Object)null) { return val2; } } return null; } public static Transform FindParent(Transform go) { while ((Object)(object)go.parent != (Object)null) { go = go.parent; } return go; } public static GameObject GetPrefabByHash(int prefabHash) { GameObject val = ObjectDB.instance.GetItemPrefab(prefabHash); Logging logger = Logging.GetLogger(); if ((Object)(object)val != (Object)null) { logger.Debug("Found prefab in ObjectDB"); } else { ZNetScene instance = ZNetScene.instance; val = ((instance != null) ? instance.GetPrefab(prefabHash) : null); if ((Object)(object)val != (Object)null) { logger.Debug("Found prefab in Scene"); } } return val; } public static GameObject GetPrefab(string prefabName) { GameObject val = ObjectDB.instance.GetItemPrefab(prefabName); Logging logger = Logging.GetLogger(); if ((Object)(object)val != (Object)null) { logger.Debug("Found " + prefabName + " in ObjectDB"); } else { ZNetScene instance = ZNetScene.instance; val = ((instance != null) ? instance.GetPrefab(prefabName) : null); if ((Object)(object)val != (Object)null) { logger.Debug("Found " + prefabName + " in Scene"); } } return val; } public static string SerializeFromDictionary<K, V>(string delimp, string delimc, IDictionary<K, V> dict) { if (dict == null) { return null; } IEnumerable<string> values = dict.Select(delegate(KeyValuePair<K, V> kvp) { KeyValuePair<K, V> keyValuePair = kvp; string? obj = keyValuePair.Key?.ToString(); string text = delimc; keyValuePair = kvp; return obj + text + keyValuePair.Value; }); return string.Join(delimp, values); } public static void DeserializeToDictionary<K, V>(string serializedString, string delimp, string delimc, ref IDictionary<K, V> dict) { if (dict == null) { return; } dict.Clear(); string[] separator = new string[1] { delimp }; string[] separator2 = new string[1] { delimc }; string[] array = serializedString.Split(separator, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < array.Length; i++) { string[] array2 = array[i].Split(separator2, StringSplitOptions.RemoveEmptyEntries); if (array2.Length == 2) { dict.Add(TypedValue<K>(array2[0]), TypedValue<V>(array2[1])); } } } public static T TypedValue<T>(object a) { return (T)Convert.ChangeType(a, typeof(T)); } public static bool CopyComponentToGameObject(Component original, ref GameObject destination) { //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Expected O, but got Unknown Logging logger = Logging.GetLogger(); Type type = ((object)original).GetType(); logger.Debug($"Original Type is {type}"); GameObject obj = destination; logger.Debug("Destination GameObject " + ((obj != null) ? ((Object)obj).name : null)); Component val = destination.GetComponent(type); if ((Object)(object)val == (Object)null) { val = destination.AddComponent(type); } if ((Object)(object)val == (Object)null) { logger.Debug("Destination component is null"); return false; } Component val2 = (Component)Activator.CreateInstance(type); if ((Object)(object)val2 == (Object)null) { logger.Debug("Destination component is null"); return false; } if ((Object)(object)val2 == (Object)null) { logger.Debug("Boxed component is null"); return false; } FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { fieldInfo.SetValue(val2, fieldInfo.GetValue(original)); } val = val2; return true; } public static bool CopyObject(object original, object target) { Logging logger = Logging.GetLogger(); Type type = original.GetType(); Type type2 = target.GetType(); if (type == null) { logger.Warning("Copy Object: Source object is null"); Activator.CreateInstance(type); return false; } if (type2 == null) { logger.Warning("Copy Object: Destination object is null"); return false; } if (type2 != type) { logger.Warning("Copy Object: Source and destination components are different types"); return false; } FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { fieldInfo.SetValue(target, fieldInfo.GetValue(original)); } return true; } } public class ImageHelper { private string resources; private Logging logger; public ImageHelper(string manifestResourceLocation) { resources = manifestResourceLocation; logger = Logging.GetLogger(); } public Sprite LoadSprite(string name, int width, int height, bool linear = false, float pixelsPerUnit = 100f) { logger.Debug("Reading image and creating sprite " + name); if (TryLoadImage(name, width, height, linear, out var image)) { return LoadSprite(image, pixelsPerUnit); } return null; } public Sprite LoadSprite(Texture2D texture, float pixelsPerUnit = 100f) { return LoadSprite(texture, ((Object)texture).name, ((Texture)texture).width, ((Texture)texture).height, pixelsPerUnit); } public Sprite LoadSprite(Texture2D texture, string name, float width, float height, float pixelsPerUnit = 100f) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)texture == (Object)null) { return null; } if (Utility.IsNullOrWhiteSpace(name)) { name = ((Object)texture).name; } logger.Debug("Creating sprite " + name + " from existing texture"); Sprite obj = Sprite.Create(texture, new Rect(0f, 0f, width, height), Vector2.zero, pixelsPerUnit); if ((Object)(object)obj == (Object)null) { throw new ApplicationException("Can't create sprite " + name); } ((Object)obj).name = name; return obj; } public bool TryLoadImage(string name, int width, int height, bool linear, out Texture2D image) { //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected O, but got Unknown image = null; logger.Debug("Loading image from " + resources + "." + name); Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resources + "." + name); if (manifestResourceStream == null) { throw new FileNotFoundException("Can't find " + name + " in " + resources); } byte[] array = new byte[manifestResourceStream.Length]; manifestResourceStream.Read(array, 0, (int)manifestResourceStream.Length); Texture2D val = new Texture2D(width, height, (TextureFormat)4, true, linear); logger.Debug("Loading image " + name); if (ImageConversion.LoadImage(val, array, false)) { image = val; return true; } throw new FileLoadException("Can't load " + name); } } internal class Cfg { public static DelegatedConfigEntry<bool> configEnabled; public static ConfigEntry<Color> colorCompass = null; public static ConfigEntry<Color> colorPins = null; public static ConfigEntry<Color> colorCenterMark = null; public static ConfigEntry<bool> compassUsePlayerDirection = null; public static ConfigEntry<int> compassYOffset = null; public static ConfigEntry<float> compassScale = null; public static ConfigEntry<float> scalePinsMin = null; public static ConfigEntry<float> scalePins = null; public static ConfigEntry<bool> compassShowCenterMark = null; public static ConfigEntry<bool> useDynamicColorsOnCompass = null; public static DelegatedConfigEntry<string> ignoredPinNames; public static DelegatedConfigEntry<string> ignoredPinTypes; public static DelegatedConfigEntry<string> alwaysVisible; public static DelegatedConfigEntry<int> distancePinsMin; public static DelegatedConfigEntry<int> distancePinsMax; public static DelegatedConfigEntry<bool> compassShowPlayerPins; public static DelegatedConfigEntry<bool> showShips; public static DelegatedConfigEntry<bool> showCarts; public static DelegatedConfigEntry<bool> showPortals; public static DelegatedConfigEntry<bool> showDynamicPinsOnMap; public static DelegatedConfigEntry<bool> showDynamicPinsOnCompass; public static DelegatedConfigEntry<float> playerPinUpdateInterval; public static ConfigEntry<bool> showTypeOnMinimap = null; public static ConfigEntry<bool> showPortalNamesOnMinimap = null; public static ConfigEntry<Color> activePortalColor = null; public static ConfigEntry<Color> portalColor = null; public static ConfigEntry<Color> shipColor = null; public static ConfigEntry<Color> cartColor = null; public static DelegatedConfigEntry<Logging.LogLevels> debugLevel; private static KeyCode[] keyModifiers = (KeyCode[])(object)new KeyCode[1] { (KeyCode)308 }; public static KeyboardShortcut keyConfigItemDefault = new KeyboardShortcut((KeyCode)116, keyModifiers); public static void BepInExConfig(BaseUnityPlugin _instance) { //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Expected O, but got Unknown //IL_0246: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Expected O, but got Unknown //IL_02fb: Unknown result type (might be due to invalid IL or missing references) //IL_031f: Unknown result type (might be due to invalid IL or missing references) //IL_0343: Unknown result type (might be due to invalid IL or missing references) //IL_03d4: Unknown result type (might be due to invalid IL or missing references) //IL_03de: Expected O, but got Unknown //IL_04b1: Unknown result type (might be due to invalid IL or missing references) //IL_04d5: Unknown result type (might be due to invalid IL or missing references) //IL_04f9: Unknown result type (might be due to invalid IL or missing references) //IL_051d: Unknown result type (might be due to invalid IL or missing references) configEnabled = new DelegatedConfigEntry<bool>(useServerDelegate: true); ignoredPinNames = new DelegatedConfigEntry<string>(HUDCompass.SettingChanged_IgnoredNames, useServerDelegate: true); ignoredPinTypes = new DelegatedConfigEntry<string>(HUDCompass.SettingChanged_IgnoredTypes, useServerDelegate: true); alwaysVisible = new DelegatedConfigEntry<string>(HUDCompass.SettingChanged_VisibleBehavior, useServerDelegate: true); distancePinsMin = new DelegatedConfigEntry<int>(useServerDelegate: true); distancePinsMax = new DelegatedConfigEntry<int>(useServerDelegate: true); compassShowPlayerPins = new DelegatedConfigEntry<bool>(useServerDelegate: true); showShips = new DelegatedConfigEntry<bool>(useServerDelegate: true); showCarts = new DelegatedConfigEntry<bool>(useServerDelegate: true); showPortals = new DelegatedConfigEntry<bool>(useServerDelegate: true); showDynamicPinsOnMap = new DelegatedConfigEntry<bool>(useServerDelegate: true); showDynamicPinsOnCompass = new DelegatedConfigEntry<bool>(useServerDelegate: true); playerPinUpdateInterval = new DelegatedConfigEntry<float>(useServerDelegate: true); debugLevel = new DelegatedConfigEntry<Logging.LogLevels>(Logging.ChangeLogging); debugLevel.ConfigEntry = _instance.Config.Bind<Logging.LogLevels>("Z - Utility", "LogLevel", Logging.LogLevels.Info, "Controls the level of information contained in the log"); Logging.GetLogger().LogLevel = debugLevel.Value; configEnabled.ConfigEntry = _instance.Config.Bind<bool>("A - Immersive Compass", "Enabled", true, "Enable or disable the Immersive Compass.*"); compassUsePlayerDirection = _instance.Config.Bind<bool>("B - Compass Display", "Use Player Direction", false, "Orient the compass based on the direction the player is facing, rather than the middle of the screen."); compassScale = _instance.Config.Bind<float>("B - Compass Display", "Compass Scale", 0.75f, new ConfigDescription("Sets the overall scale of the compass on the screen", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 3f), Array.Empty<object>())); compassYOffset = _instance.Config.Bind<int>("B - Compass Display", "Offset (Y)", 0, "Offset from the top of the screen in pixels."); distancePinsMin.ConfigEntry = _instance.Config.Bind<int>("B - Compass Display", "Distance (Minimum)", 1, "Minimum distance from pin to show on compass.*"); distancePinsMax.ConfigEntry = _instance.Config.Bind<int>("B - Compass Display", "Distance (Maximum)", 300, "Maximum distance from pin to show on compass.*"); compassShowPlayerPins.ConfigEntry = _instance.Config.Bind<bool>("B - Compass Display", "Show Player Pins", true, "Show player pins on the compass.*"); scalePins = _instance.Config.Bind<float>("B - Compass Display", "Pins Scale", 1f, new ConfigDescription("Sets the overall scale of the pins on the on the screen", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 4f), Array.Empty<object>())); scalePinsMin = _instance.Config.Bind<float>("B - Compass Display", "Minimum Pin Size", 0.25f, "Enlarge or shrink the scale of the pins at their furthest visible distance."); compassShowCenterMark = _instance.Config.Bind<bool>("B - Compass Display", "Show Center Mark", false, "(Optional) Show center mark graphic."); ignoredPinNames.ConfigEntry = _instance.Config.Bind<string>("C - Ignore", "Pin Names", "Silver,Obsidian,Copper,Tin", "Ignore location pins with these names (comma separated, no spaces). End a string with asterix * to denote a prefix.*"); ignoredPinTypes.ConfigEntry = _instance.Config.Bind<string>("C - Ignore", "Pin Types", "Shout,Ping,Death", "Ignore location pins of these types (comma separated, no spaces). Types include: Icon0,Icon1,Icon2,Icon3,Icon4,Death,Bed,Shout,None,Boss,Player,RandomEvent,Ping,EventArea.*"); colorCompass = _instance.Config.Bind<Color>("E - Compass Colors", "Compass Color", Color.white, "(Optional) Adjust the main color of the compass."); colorPins = _instance.Config.Bind<Color>("E - Compass Colors", "Pin Color", Color.white, "(Optional) Adjust the color of the location pins on the compass."); colorCenterMark = _instance.Config.Bind<Color>("E - Compass Colors", "Center Mark Color", Color.yellow, "(Optional) Adjust the color of the center mark graphic."); showDynamicPinsOnMap.ConfigEntry = _instance.Config.Bind<bool>("F - Dynamic Pins", "Show dynamic pins on map", true, "Display pins for ships, carts and portals on the main and minimap. Controlled individually below.*"); showDynamicPinsOnCompass.ConfigEntry = _instance.Config.Bind<bool>("F - Dynamic Pins", "Show dynamic pins on compass", true, "Display pins for ships, carts and portals on the compass. Controlled individually below.*"); playerPinUpdateInterval.ConfigEntry = _instance.Config.Bind<float>("F - Dynamic Pins", "Player pin refresh pin interval", 2f, new ConfigDescription("Interval in seconds between refresh of player pins on map and compass. Decrease for 'smoother' updates of player pins. Zero refreshes every frame. NOTE: Valheim default for Player pin refresh is 2 seconds. Decreasing can reduce multiplayer performance.*", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>())); showShips.ConfigEntry = _instance.Config.Bind<bool>("G - Dynamic Types", "Show Ships", true, "Show ships on the map and compass.*"); showCarts.ConfigEntry = _instance.Config.Bind<bool>("G - Dynamic Types", "Show Carts", true, "Show carts on the map and compass.*"); showPortals.ConfigEntry = _instance.Config.Bind<bool>("G - Dynamic Types", "Show Portals", true, "Show portals on the map and compass.*"); showTypeOnMinimap = _instance.Config.Bind<bool>("H - Dynamic Names", "Show dynamic types on minimap", false, "Show boat and cart types (i.e., Raft, Karve, Longship) on the Minimap."); showPortalNamesOnMinimap = _instance.Config.Bind<bool>("H - Dynamic Names", "Show portal names on minimap", false, "Show portal names on the Minimap."); activePortalColor = _instance.Config.Bind<Color>("I - Dynamic Map Colors", "Active portal color on map", new Color(255f, 153f, 51f), "Color of portal icons with active connections."); portalColor = _instance.Config.Bind<Color>("I - Dynamic Map Colors", "Portal color", Color.white, "Color of portal icons on map."); shipColor = _instance.Config.Bind<Color>("I - Dynamic Map Colors", "Ship color", Color.yellow, "Color of ship icons on map."); cartColor = _instance.Config.Bind<Color>("I - Dynamic Map Colors", "Cart color", Color.cyan, "Color of cart icons on map."); useDynamicColorsOnCompass = _instance.Config.Bind<bool>("I - Dynamic Map Colors", "Use colors on compass", false, "Use colors for dynamic pins on the compass"); alwaysVisible.ConfigEntry = _instance.Config.Bind<string>("J - Visibility", "Always Visible", "", "Always display pins of these types or names (comma separated, no spaces) at full size regardless of distance.*"); } } public enum MarkerGroup { Ship, Cart, Portal, ActivePortal } public class DynamicMapMarkers { [HarmonyPatch(typeof(ZNetScene), "OnZDODestroyed")] private static class ZNetScene_OnZDODestroyed_Patch { [HarmonyPrefix] private static void ZNetScene_OnZDODestroyed_Prefix(ZDO zdo) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) HUDCompass.Log.Trace("ZNetScene_OnZDODestroyed_Patch_Prefix"); if (s_dmm.Markers.ContainsKey(zdo.m_uid)) { MarkerData markerData = s_dmm.Markers[zdo.m_uid]; markerData.ZDO = null; markerData.Type = null; if ((Object)(object)markerData.Marker != (Object)null) { Object.Destroy((Object)(object)markerData.Marker); } if ((Object)(object)markerData.Nametag != (Object)null) { Object.Destroy((Object)(object)markerData.Nametag); } s_dmm.Markers.Remove(zdo.m_uid); } } } [HarmonyPatch(typeof(Player), "OnSpawned")] private static class Player_OnSpawned_Patch { [HarmonyPostfix] private static void Player_OnSpawned_Postfix(Player __instance) { //IL_009c: Unknown result type (might be due to invalid IL or missing references) HUDCompass.Log.Debug("Player_OnSpawned_Patch_Postfix"); s_dmm.DestroyMarkers(); List<ZDO> list = new List<ZDO>(); foreach (MarkerType markerType in s_dmm.MarkerTypes) { GetAllZDOsWithPrefab(markerType.Prefab, list); foreach (ZDO item in list) { MarkerData markerData = new MarkerData(); markerData.ZDO = item; markerData.Type = markerType; markerData.Creator = item.GetLong(ZDOVars.s_creator, 0L); markerData.IsActivePortal = false; s_dmm.Markers.Add(item.m_uid, markerData); } list.Clear(); } } } [HarmonyPatch(typeof(ZNetScene), "AddInstance")] private static class ZNetScene_AddInstance_Patch { [HarmonyPostfix] private static void ZNetScene_AddInstance_Postfix(ZDO zdo) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) HUDCompass.Log.Trace("ZNetScene_AddInstance_Patch_Postfix"); foreach (MarkerType markerType in s_dmm.MarkerTypes) { if (zdo.GetPrefab() == StringExtensionMethods.GetStableHashCode(markerType.Prefab) && !s_dmm.Markers.ContainsKey(zdo.m_uid)) { MarkerData markerData = new MarkerData(); markerData.ZDO = zdo; markerData.Type = markerType; markerData.IsActivePortal = false; markerData.Creator = zdo.GetLong(ZDOVars.s_creator, 0L); s_dmm.Markers.Add(zdo.m_uid, markerData); break; } } } } [HarmonyPatch(typeof(ZNet), "SendPeriodicData")] private static class ZNet_SendPeriodicData_Patch { [HarmonyPrefix] private static bool ZNet_SendPeriodicData_Prefix(ZNet __instance, float dt) { HUDCompass.Log.Trace("ZNet_SendPeriodicData_Patch_Prefix"); dmm_playerPinPeriodicTimer += dt; if (dmm_playerPinPeriodicTimer < Cfg.playerPinUpdateInterval.Value) { return true; } dmm_playerPinPeriodicTimer = 0f; if (__instance.IsServer()) { __instance.SendNetTime(); __instance.SendPlayerList(); } return true; } } [HarmonyPatch(typeof(Minimap), "UpdatePins")] private static class Minimap_UpdatePins_Patch { [HarmonyPostfix] private static void Minimap_UpdatePins_Postfix(Minimap __instance, float ___m_largeZoom) { //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) HUDCompass.Log.Trace("Minimap_UpdatePins_Patch_Postfix"); s_dmm.PinData.Clear(); if (s_dmm.Markers.Count <= 0) { return; } RawImage val = (Minimap.instance.m_largeRoot.activeSelf ? Minimap.instance.m_mapImageLarge : Minimap.instance.m_mapImageSmall); float size = (Minimap.instance.m_largeRoot.activeSelf ? Minimap.instance.m_pinSizeLarge : Minimap.instance.m_pinSizeSmall); RectTransform parent = (Minimap.instance.m_largeRoot.activeSelf ? Minimap.instance.m_pinRootLarge : Minimap.instance.m_pinRootSmall); foreach (MarkerData value in s_dmm.Markers.Values) { bool flag = IsInControlByPlayer(value.ZDO); Vector3 position = value.ZDO.GetPosition(); value.IsActivePortal = value.Type.Prefab == "portal_wood" && value.ZDO.GetConnectionZDOID((ConnectionType)1) != ZDOID.None; if (Cfg.showDynamicPinsOnCompass.Value && value.Type.Show && !flag) { s_dmm.PinData.Add(s_dmm.MarkerToPinData(value)); } if (Cfg.showDynamicPinsOnMap.Value && value.Type.Show && !flag && IsPointVisible(position, val)) { DrawMarker(value, size, parent, val, ___m_largeZoom, Minimap.instance.m_largeRoot.activeSelf); } else { MarkerData.Destroy(value); } } } } [HarmonyPatch(typeof(Minimap), "Start")] private static class Minimap_Start_Patch { [HarmonyPostfix] private static void Minimap_Start_Postfix(Minimap __instance) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) HUDCompass.Log.Debug("Minimap_Start_Patch_Postfix"); if (!((Object)(object)s_dmm.PortalMarkerSprite == (Object)null)) { return; } foreach (SpriteData icon in Minimap.instance.m_icons) { if (((Object)icon.m_icon).name == "mapicon_portal") { s_dmm.PortalMarkerSprite = icon.m_icon; s_dmm.MarkerTypes.Find((MarkerType x) => x.Prefab == "portal_wood").Sprite = s_dmm.PortalMarkerSprite; HUDCompass.Log.Debug("Found icon " + ((Object)icon.m_icon).name); } } } } public List<MarkerType> MarkerTypes; public Dictionary<ZDOID, MarkerData> Markers; public Sprite PortalMarkerSprite; public List<PinData> PinData; private Sprite ShipMarkerSprite; private Sprite CartMarkerSprite; private static DynamicMapMarkers s_dmm; private static float dmm_playerPinPeriodicTimer; private static float dmm_dynamicPinPeriodicTimer; private static float dmm_staticPinPeriodicTimer; public DynamicMapMarkers() { s_dmm = this; MarkerTypes = new List<MarkerType>(); Markers = new Dictionary<ZDOID, MarkerData>(); PinData = new List<PinData>(); ShipMarkerSprite = HUDCompass.s_imageHelper.LoadSprite("mapicon_anchor.png", 2, 2, linear: false, 50f); CartMarkerSprite = HUDCompass.s_imageHelper.LoadSprite("mapicon_cart.png", 2, 2, linear: false, 50f); MarkerTypes.Add(new MarkerType("Raft", ShipMarkerSprite, "$ship_raft", MarkerGroup.Ship, Cfg.showShips.ConfigEntry)); MarkerTypes.Add(new MarkerType("Karve", ShipMarkerSprite, "$ship_karve", MarkerGroup.Ship, Cfg.showShips.ConfigEntry)); MarkerTypes.Add(new MarkerType("VikingShip", ShipMarkerSprite, "$ship_longship", MarkerGroup.Ship, Cfg.showShips.ConfigEntry)); MarkerTypes.Add(new MarkerType("Cart", CartMarkerSprite, "$tool_cart", MarkerGroup.Cart, Cfg.showCarts.ConfigEntry)); MarkerTypes.Add(new MarkerType("portal_wood", PortalMarkerSprite, "$piece_portal", MarkerGroup.Portal, Cfg.showPortals.ConfigEntry)); } public PinData MarkerToPinData(MarkerData marker) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Expected O, but got Unknown if (marker != null) { return new PinData { m_icon = marker.Type.Sprite, m_pos = marker.ZDO.m_position, m_name = (marker.IsActivePortal ? MarkerGroup.ActivePortal.ToString() : marker.Type.Group.ToString()), m_type = (PinType)8, m_ownerID = marker.Creator }; } return null; } public void DestroyMarkers() { foreach (MarkerData value in Markers.Values) { MarkerData.Destroy(value); } Markers.Clear(); } public static bool GetAllZDOsWithPrefab(string prefab, List<ZDO> zdos) { int stableHashCode = StringExtensionMethods.GetStableHashCode(prefab); foreach (ZDO value in ZDOMan.instance.m_objectsByID.Values) { if (value.GetPrefab() == stableHashCode) { zdos.Add(value); } } zdos.RemoveAll((Predicate<ZDO>)ZDOMan.InvalidZDO); return true; } private static bool IsInControlByPlayer(ZDO zdo) { ZNetView val = ZNetScene.instance.FindInstance(zdo); if ((Object)(object)val != (Object)null) { GameObject gameObject = ((Component)val).gameObject; if ((Object)(object)gameObject != (Object)null) { Ship component = gameObject.GetComponent<Ship>(); if ((Object)(object)component != (Object)null) { return component.HaveControllingPlayer(); } Vagon component2 = gameObject.GetComponent<Vagon>(); object obj; if (component2 == null) { obj = null; } else { ConfigurableJoint attachJoin = component2.m_attachJoin; obj = ((attachJoin != null) ? ((Joint)attachJoin).connectedBody : null); } if ((Object)obj != (Object)null) { return true; } } } return false; } private static void DrawMarker(MarkerData data, float size, RectTransform parent, RawImage rawImage, float largeMapZoom, bool isLargeMap) { //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0308: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_02d3: Unknown result type (might be due to invalid IL or missing references) GameObject val = data.Marker; GameObject val2 = data.Nametag; RectTransform val4; if ((Object)(object)val == (Object)null || (Object)(object)val.transform.parent != (Object)(object)parent) { if ((Object)(object)val != (Object)null) { Object.Destroy((Object)(object)val); } val = (data.Marker = Object.Instantiate<GameObject>(Minimap.instance.m_pinPrefab)); Transform transform = val.transform; val4 = (RectTransform)(object)((transform is RectTransform) ? transform : null); Image component = val.GetComponent<Image>(); component.sprite = data.Type.Sprite; string prefab = data.Type.Prefab; if (!(prefab == "portal_wood")) { if (prefab == "Cart") { ((Graphic)component).color = Cfg.cartColor.Value; } else { ((Graphic)component).color = Cfg.shipColor.Value; } } else { ((Graphic)component).color = (data.IsActivePortal ? Cfg.activePortalColor.Value : Cfg.portalColor.Value); } _ = Player.m_localPlayer; if (data.Creator != HUDCompass.s_localPlayerID) { ((Graphic)component).color = new Color(((Graphic)component).color.r * 0.7f, ((Graphic)component).color.b * 0.7f, ((Graphic)component).color.g * 0.7f, ((Graphic)component).color.a * 0.8f); } ((Transform)val4).SetParent((Transform)(object)parent); val4.SetSizeWithCurrentAnchors((Axis)0, size); val4.SetSizeWithCurrentAnchors((Axis)1, size); } Transform transform2 = val.transform; val4 = (RectTransform)(object)((transform2 is RectTransform) ? transform2 : null); WorldToMapPoint(data.ZDO.GetPosition(), out var mx, out var my); Vector2 anchoredPosition = (val4.anchoredPosition = MapPointToLocalGuiPos(mx, my, rawImage)); Transform val6 = val.transform.Find("Checked"); if ((Object)(object)val6 != (Object)null) { ((Component)val6).gameObject.SetActive(false); } if (!isLargeMap && !Cfg.showTypeOnMinimap.Value) { return; } RectTransform component2; if ((Object)(object)val2 == (Object)null || (Object)(object)val2.transform.parent != (Object)(object)parent) { if ((Object)(object)val2 != (Object)null) { Object.Destroy((Object)(object)val2); } if (isLargeMap) { val2 = Object.Instantiate<GameObject>(Minimap.instance.m_pinNamePrefab, (Transform)(object)parent); TMP_Text componentInChildren = val2.GetComponentInChildren<TMP_Text>(); componentInChildren.text = Localization.instance.Localize(data.Type.Name); string prefab = data.Type.Prefab; if (!(prefab == "portal_wood")) { if (prefab == "Cart") { ((Graphic)componentInChildren).color = Cfg.cartColor.Value; } else { ((Graphic)componentInChildren).color = Cfg.shipColor.Value; } } else { string @string = data.ZDO.GetString(ZDOVars.s_tag, ""); componentInChildren.text = @string; ((Graphic)componentInChildren).color = (data.IsActivePortal ? Cfg.activePortalColor.Value : Cfg.portalColor.Value); } component2 = val2.GetComponent<RectTransform>(); if ((Object)(object)component2 != (Object)null) { ((Transform)component2).SetParent((Transform)(object)parent); data.Nametag = val2; } } } Transform transform3 = val2.transform; component2 = (RectTransform)(object)((transform3 is RectTransform) ? transform3 : null); component2.anchoredPosition = anchoredPosition; } private static bool IsPointVisible(Vector3 p, RawImage map) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) WorldToMapPoint(p, out var mx, out var my); float num = mx; Rect uvRect = map.uvRect; if (num > ((Rect)(ref uvRect)).xMin) { float num2 = mx; uvRect = map.uvRect; if (num2 < ((Rect)(ref uvRect)).xMax) { float num3 = my; uvRect = map.uvRect; if (num3 > ((Rect)(ref uvRect)).yMin) { float num4 = my; uvRect = map.uvRect; return num4 < ((Rect)(ref uvRect)).yMax; } } } return false; } private static void WorldToMapPoint(Vector3 p, out float mx, out float my) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) int num = Minimap.instance.m_textureSize / 2; mx = p.x / Minimap.instance.m_pixelSize + (float)num; my = p.z / Minimap.instance.m_pixelSize + (float)num; mx /= Minimap.instance.m_textureSize; my /= Minimap.instance.m_textureSize; } private static Vector2 MapPointToLocalGuiPos(float mx, float my, RawImage img) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) Vector2 result = default(Vector2); Rect val = img.uvRect; float num = mx - ((Rect)(ref val)).xMin; val = img.uvRect; result.x = num / ((Rect)(ref val)).width; val = img.uvRect; float num2 = my - ((Rect)(ref val)).yMin; val = img.uvRect; result.y = num2 / ((Rect)(ref val)).height; ref float x = ref result.x; float num3 = x; val = ((Graphic)img).rectTransform.rect; x = num3 * ((Rect)(ref val)).width; ref float y = ref result.y; float num4 = y; val = ((Graphic)img).rectTransform.rect; y = num4 * ((Rect)(ref val)).height; return result; } } [BepInPlugin("neobotics.valheim_mod.hudcompass", "HUDCompass", "1.0.0")] [BepInProcess("valheim.exe")] [BepInProcess("valheim_server.exe")] public class HUDCompass : BaseUnityPlugin { [HarmonyPatch(typeof(Player), "OnSpawned")] private static class Player_OnSpawned_Patch { [HarmonyPostfix] private static void Player_OnSpawned_Postfix(Player __instance) { Log.Debug("Player_OnSpawned_Patch_Postfix"); s_localPlayerID = Game.instance.GetPlayerProfile().GetPlayerID(); } } [HarmonyPatch(typeof(Hud), "Awake")] internal static class HudAwakeCompassPatch { internal static void Postfix(Hud __instance) { //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Expected O, but got Unknown //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Expected O, but got Unknown //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Expected O, but got Unknown //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_020b: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_02de: Unknown result type (might be due to invalid IL or missing references) //IL_02e8: Expected O, but got Unknown //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_0319: Unknown result type (might be due to invalid IL or missing references) //IL_0328: Unknown result type (might be due to invalid IL or missing references) //IL_032d: Unknown result type (might be due to invalid IL or missing references) //IL_033b: Unknown result type (might be due to invalid IL or missing references) //IL_0340: Unknown result type (might be due to invalid IL or missing references) //IL_0349: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0258: Expected O, but got Unknown //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_0289: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_029d: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Unknown result type (might be due to invalid IL or missing references) Log.Debug("Hud_Awake_Postfix"); if (s_imageHelper.TryLoadImage("compass.png", 2, 2, linear: true, out var image) && ((Texture)image).width > 0) { float width = (float)((Texture)image).width / 2f; s_spriteCompass = s_imageHelper.LoadSprite(image); if (s_imageHelper.TryLoadImage("mask.png", 2, 2, linear: true, out var image2) && ((Texture)image2).width > 0) { s_spriteMask = s_imageHelper.LoadSprite(image2, null, width, ((Texture)image2).height); if (s_imageHelper.TryLoadImage("center.png", 2, 2, linear: true, out var image3) && ((Texture)image3).width > 0) { s_spriteCenter = s_imageHelper.LoadSprite(image3); } } s_objectParent = new GameObject(); ((Object)s_objectParent).name = "Compass"; ((Transform)s_objectParent.AddComponent<RectTransform>()).SetParent(__instance.m_rootObject.transform); GameObject val = new GameObject(); ((Object)val).name = "Mask"; RectTransform obj = val.AddComponent<RectTransform>(); ((Transform)obj).SetParent(s_objectParent.transform); Rect rect = s_spriteCompass.rect; float width2 = ((Rect)(ref rect)).width; rect = s_spriteCompass.rect; obj.sizeDelta = new Vector2(width2, ((Rect)(ref rect)).height); ((Transform)obj).localScale = Vector3.one * Cfg.compassScale.Value; obj.anchoredPosition = Vector2.zero; Image obj2 = val.AddComponent<Image>(); obj2.sprite = s_spriteMask; obj2.preserveAspect = true; val.AddComponent<Mask>().showMaskGraphic = false; s_objectCompass = new GameObject(); ((Object)s_objectCompass).name = "Image"; RectTransform obj3 = s_objectCompass.AddComponent<RectTransform>(); ((Transform)obj3).SetParent(val.transform); ((Transform)obj3).localScale = Vector3.one; obj3.anchoredPosition = Vector2.zero; rect = s_spriteCompass.rect; float width3 = ((Rect)(ref rect)).width; rect = s_spriteCompass.rect; obj3.sizeDelta = new Vector2(width3, ((Rect)(ref rect)).height); Image obj4 = s_objectCompass.AddComponent<Image>(); obj4.sprite = s_spriteCompass; obj4.preserveAspect = true; if ((Object)(object)s_spriteCenter != (Object)null) { s_objectCenterMark = new GameObject(); ((Object)s_objectCenterMark).name = "CenterMark"; RectTransform obj5 = s_objectCenterMark.AddComponent<RectTransform>(); ((Transform)obj5).SetParent(val.transform); ((Transform)obj5).localScale = Vector3.one; obj5.anchoredPosition = Vector2.zero; rect = s_spriteCenter.rect; float width4 = ((Rect)(ref rect)).width; rect = s_spriteCenter.rect; obj5.sizeDelta = new Vector2(width4, ((Rect)(ref rect)).height); Image obj6 = s_objectCenterMark.AddComponent<Image>(); obj6.sprite = s_spriteCenter; obj6.preserveAspect = true; } s_objectPins = new GameObject(); ((Object)s_objectPins).name = "Pins"; RectTransform obj7 = s_objectPins.AddComponent<RectTransform>(); ((Transform)obj7).SetParent(val.transform); ((Transform)obj7).localScale = Vector3.one; obj7.anchoredPosition = Vector2.zero; rect = s_spriteMask.rect; float width5 = ((Rect)(ref rect)).width; rect = s_spriteMask.rect; obj7.sizeDelta = new Vector2(width5, ((Rect)(ref rect)).height); } else { Log.Error("Invalid compass image"); } } } [HarmonyPatch(typeof(Hud), "Update")] internal static class HudUpdateCompassPatch { internal static void Prefix(Hud __instance) { //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0291: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Expected O, but got Unknown //IL_03ee: Unknown result type (might be due to invalid IL or missing references) //IL_03f5: Unknown result type (might be due to invalid IL or missing references) //IL_04ab: Unknown result type (might be due to invalid IL or missing references) //IL_04b0: Unknown result type (might be due to invalid IL or missing references) //IL_04b5: Unknown result type (might be due to invalid IL or missing references) //IL_0491: Unknown result type (might be due to invalid IL or missing references) //IL_0496: Unknown result type (might be due to invalid IL or missing references) //IL_049b: Unknown result type (might be due to invalid IL or missing references) //IL_04b7: Unknown result type (might be due to invalid IL or missing references) //IL_04be: Unknown result type (might be due to invalid IL or missing references) //IL_0542: Unknown result type (might be due to invalid IL or missing references) //IL_0547: Unknown result type (might be due to invalid IL or missing references) //IL_055f: Unknown result type (might be due to invalid IL or missing references) //IL_057a: Unknown result type (might be due to invalid IL or missing references) //IL_0503: Unknown result type (might be due to invalid IL or missing references) //IL_05d6: Unknown result type (might be due to invalid IL or missing references) //IL_05dd: Unknown result type (might be due to invalid IL or missing references) //IL_05e7: Unknown result type (might be due to invalid IL or missing references) //IL_05f6: Unknown result type (might be due to invalid IL or missing references) //IL_0607: Unknown result type (might be due to invalid IL or missing references) //IL_0728: Unknown result type (might be due to invalid IL or missing references) //IL_073a: Unknown result type (might be due to invalid IL or missing references) //IL_0740: Unknown result type (might be due to invalid IL or missing references) //IL_074a: Unknown result type (might be due to invalid IL or missing references) //IL_0678: Unknown result type (might be due to invalid IL or missing references) //IL_06d6: Unknown result type (might be due to invalid IL or missing references) //IL_06e8: Unknown result type (might be due to invalid IL or missing references) //IL_06fa: Unknown result type (might be due to invalid IL or missing references) //IL_070c: Unknown result type (might be due to invalid IL or missing references) //IL_071c: Unknown result type (might be due to invalid IL or missing references) //IL_068b: Unknown result type (might be due to invalid IL or missing references) //IL_069e: Unknown result type (might be due to invalid IL or missing references) //IL_06b1: Unknown result type (might be due to invalid IL or missing references) if (!Cfg.configEnabled.Value || !Object.op_Implicit((Object)(object)Player.m_localPlayer)) { return; } if ((Object)(object)s_spriteCompass == (Object)null) { Log.Debug("Compass is null"); return; } if ((Object)(object)s_spriteMask == (Object)null) { Log.Debug("Mask is null"); return; } float num = ((!Cfg.compassUsePlayerDirection.Value) ? ((Component)GameCamera.instance).transform.eulerAngles.y : ((Component)Player.m_localPlayer).transform.eulerAngles.y); if (num > 180f) { num -= 360f; } num *= -(float)Math.PI / 180f; Rect rect = s_objectCompass.GetComponent<Image>().sprite.rect; float num2 = 1f; CanvasScaler val = GuiScaler.m_scalers?.Find((GuiScaler x) => ((Object)x.m_canvasScaler).name == "LoadingGUI")?.m_canvasScaler; if ((Object)(object)val != (Object)null) { num2 = val.scaleFactor; } ((Transform)s_objectCompass.GetComponent<RectTransform>()).localPosition = Vector3.right * (((Rect)(ref rect)).width / 2f) * num / ((float)Math.PI * 2f) - new Vector3(((Rect)(ref rect)).width * 0.125f, 0f, 0f); ((Graphic)s_objectCompass.GetComponent<Image>()).color = Cfg.colorCompass.Value; ((Transform)s_objectParent.GetComponent<RectTransform>()).localScale = Vector3.one * Cfg.compassScale.Value; s_objectParent.GetComponent<RectTransform>().anchoredPosition = new Vector2(0f, ((float)Screen.height / num2 - (float)((Texture)s_objectCompass.GetComponent<Image>().sprite.texture).height * Cfg.compassScale.Value) / 2f) - Vector2.up * (float)Cfg.compassYOffset.Value; if ((Object)(object)s_objectCenterMark != (Object)null) { if (Cfg.compassShowCenterMark.Value) { ((Graphic)s_objectCenterMark.GetComponent<Image>()).color = Cfg.colorCenterMark.Value; s_objectCenterMark.SetActive(true); } else { s_objectCenterMark.SetActive(false); } } else { Log.Debug("Center is null"); } _ = s_objectPins.transform.childCount; List<string> list = new List<string>(); foreach (Transform item in s_objectPins.transform) { Transform val2 = item; list.Add(((Object)val2).name); } List<PinData> list2 = new List<PinData>(); list2.AddRange(Minimap.instance.m_pins); list2.AddRange(Minimap.instance.m_locationPins.Values); if (Cfg.compassShowPlayerPins.Value) { list2.AddRange(Minimap.instance.m_playerPins); } PinData deathPin = Minimap.instance.m_deathPin; if (deathPin != null) { list2.Add(deathPin); } if (Cfg.showDynamicPinsOnCompass.Value) { list2.AddRange(s_dmm.PinData); } Transform transform = ((Component)Player.m_localPlayer).transform; float num3 = 0f; if (1f - Cfg.scalePinsMin.Value > 0f) { num3 = (float)Cfg.distancePinsMax.Value / (1f - Cfg.scalePinsMin.Value); } Cfg.ignoredPinNames.Value.Contains("*"); foreach (PinData item2 in list2) { string text = ((object)(Vector3)(ref item2.m_pos)).ToString(); list.Remove(text); Transform val3 = s_objectPins.transform.Find(text); float num4 = Vector3.Distance(transform.position, item2.m_pos); bool flag = MatchTypeOrName(s_alwaysVisible, item2); bool num5 = MatchType(s_ignoredTypes, item2); bool flag2 = MatchNameOrWildcard(s_ignoredNames, s_ignoredWildcardNames, item2.m_name); bool flag3 = false; if (!num5 && !flag2 && (flag || IsInBounds(num4, Cfg.distancePinsMin.Value, Cfg.distancePinsMax.Value))) { flag3 = true; } if ((Object)(object)val3 != (Object)null) { ((Component)val3).gameObject.SetActive(flag3); } if (!flag3) { continue; } Vector3 val4 = ((!Cfg.compassUsePlayerDirection.Value) ? ((Component)GameCamera.instance).transform.InverseTransformPoint(item2.m_pos) : transform.InverseTransformPoint(item2.m_pos)); num = Mathf.Atan2(val4.x, val4.z); RectTransform val6; Image val7; if ((Object)(object)val3 == (Object)null) { if (Log.LogLevel >= Logging.LogLevels.Trace) { Logging log = Log; object[] obj = new object[5] { item2.m_name, item2.m_type, null, null, null }; Sprite icon = item2.m_icon; obj[2] = ((icon != null) ? ((Object)icon).name : null); obj[3] = num4; obj[4] = flag; log.Trace(string.Format("Adding new pin object for name {0} type {1} icon {2} distance {3} always show {4}", obj)); } GameObject val5 = new GameObject { name = ((object)(Vector3)(ref item2.m_pos)).ToString() }; val6 = val5.AddComponent<RectTransform>(); ((Transform)val6).SetParent(s_objectPins.transform); val6.anchoredPosition = Vector2.zero; val7 = val5.AddComponent<Image>(); } else { _ = ((Component)val3).gameObject; val6 = ((Component)val3).GetComponent<RectTransform>(); val7 = ((Component)val3).GetComponent<Image>(); } float num6 = (flag ? 1f : ((Cfg.scalePinsMin.Value < 1f) ? ((num3 - num4) / num3) : 1f)); ((Transform)val6).localScale = Vector3.one * num6 * 0.5f * Cfg.scalePins.Value; ((Graphic)val7).color = Cfg.colorPins.Value; val7.sprite = item2.m_icon; if (Cfg.useDynamicColorsOnCompass.Value) { switch (item2.m_name) { case "Ship": ((Graphic)val7).color = Cfg.shipColor.Value; break; case "Cart": ((Graphic)val7).color = Cfg.cartColor.Value; break; case "Portal": ((Graphic)val7).color = Cfg.portalColor.Value; break; case "ActivePortal": ((Graphic)val7).color = Cfg.activePortalColor.Value; break; } } if (item2.m_ownerID != 0L && item2.m_ownerID != s_localPlayerID) { ((Graphic)val7).color = new Color(((Graphic)val7).color.r * 0.7f, ((Graphic)val7).color.b * 0.7f, ((Graphic)val7).color.g * 0.7f, ((Graphic)val7).color.a * 0.8f); } ((Transform)val6).localPosition = Vector3.right * (((Rect)(ref rect)).width / 2f) * num / ((float)Math.PI * 2f); } foreach (string item3 in list) { Object.Destroy((Object)(object)((Component)s_objectPins.transform.Find(item3)).gameObject); } } } internal const string PLUGIN_NAME = "HUDCompass"; internal const string PLUGIN_VERSION = "1.0.0"; internal const string PLUGIN_GUID = "neobotics.valheim_mod.hudcompass"; internal const string FILE_COMPASS = "compass.png"; internal const string FILE_MASK = "mask.png"; internal const string FILE_CENTER = "center.png"; private static HUDCompass s_instance; private static Harmony harmony; internal static GameObject s_objectCompass; internal static GameObject s_objectPins; internal static GameObject s_objectParent; internal static GameObject s_objectCenterMark; internal static List<string> s_ignoredNames = new List<string>(); internal static List<string> s_ignoredWildcardNames = new List<string>(); internal static List<string> s_ignoredTypes = new List<string>(); internal static List<string> s_alwaysVisible = new List<string>(); internal static Sprite s_spriteCompass = null; internal static Sprite s_spriteMask = null; internal static Sprite s_spriteCenter = null; public static Logging Log; public static DynamicMapMarkers s_dmm = null; public static long s_localPlayerID = 0L; public static ImageHelper s_imageHelper; private static Dictionary<string, string> s_typeAlias = new Dictionary<string, string> { { "mapicon_fire", "Fire" }, { "mapicon_house", "House" }, { "mapicon_trader", "Halder" }, { "mapicon_hilder", "Hilder" }, { "mapicon_start", "Start" }, { "mapicon_pin", "Pin" }, { "mapicon_portal", "Portal" }, { "mapicon_cart", "Cart" }, { "mapicon_anchor", "Ship" } }; private void Awake() { //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Expected O, but got Unknown s_instance = this; Log = Logging.GetLogger(Logging.LogLevels.Info, "HUDCompass"); s_imageHelper = new ImageHelper("HUDCompass.Resources"); ServerConfiguration.Instance.Setup(((BaseUnityPlugin)this).Config, (BaseUnityPlugin)(object)s_instance); Cfg.BepInExConfig((BaseUnityPlugin)(object)s_instance); ServerConfiguration.Instance.CreateConfigWatcher(); if (Cfg.configEnabled.Value) { Log.Debug("neobotics.valheim_mod.hudcompass v1.0.0 enabled in configuration."); SettingChanged_IgnoredNames(); SettingChanged_IgnoredTypes(); SettingChanged_VisibleBehavior(); s_dmm = new DynamicMapMarkers(); harmony = new Harmony(((BaseUnityPlugin)this).Info.Metadata.GUID); harmony.PatchAll(Assembly.GetExecutingAssembly()); harmony.PatchAll(typeof(DynamicMapMarkers)); Log.Info("Awake"); } else { Log.Debug("neobotics.valheim_mod.hudcompass v1.0.0 not enabled in configuration."); } } private void Start() { Game.isModded = true; } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); s_dmm.DestroyMarkers(); Harmony obj = harmony; if (obj != null) { obj.UnpatchSelf(); } } private static bool MatchNameOrWildcard(List<string> exact, List<string> wildcard, string name) { if (exact.Contains(name)) { return true; } if (wildcard.Count > 0) { foreach (string item in wildcard) { if (item == name.Substring(0, item.Length - 1)) { return true; } } } return false; } private static bool MatchType(List<string> matches, PinData pin) { if (pin == null) { return false; } Sprite icon = pin.m_icon; string item = ((((icon != null) ? ((Object)icon).name : null) != null && s_typeAlias.ContainsKey(((Object)pin.m_icon).name)) ? s_typeAlias[((Object)pin.m_icon).name] : ((object)(PinType)(ref pin.m_type)).ToString()); return matches.Contains(item); } private static bool MatchTypeOrName(List<string> matches, PinData pin) { if (pin == null) { return false; } if (!MatchType(matches, pin)) { return matches.Contains(pin.m_name); } return true; } private static bool IsInBounds(float dist, float min, float max) { if (dist <= max) { return dist >= min; } return false; } public static void SettingChanged_IgnoredNames(object sender, EventArgs e) { SettingChanged_IgnoredNames(); } public static void SettingChanged_IgnoredNames() { s_ignoredNames.Clear(); s_ignoredWildcardNames.Clear(); string[] array = Cfg.ignoredPinNames.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.EndsWith("*")) { s_ignoredWildcardNames.Add(text.Substring(0, text.Length - 1)); } else { s_ignoredNames.Add(text); } } } public static void SettingChanged_IgnoredTypes(object sender, EventArgs e) { SettingChanged_IgnoredTypes(); } public static void SettingChanged_IgnoredTypes() { s_ignoredTypes.Clear(); string[] array = Cfg.ignoredPinTypes.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string text in array) { s_ignoredTypes.Add(text.Trim()); } } public static void SettingChanged_VisibleBehavior(object sender, EventArgs e) { SettingChanged_VisibleBehavior(); } public static void SettingChanged_VisibleBehavior() { s_alwaysVisible.Clear(); string[] array = Cfg.alwaysVisible.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string text in array) { s_alwaysVisible.Add(text.Trim()); } } } public class MarkerData { public MarkerType Type { get; set; } public GameObject Marker { get; set; } public ZDO ZDO { get; set; } public GameObject Nametag { get; set; } public bool IsActivePortal { get; set; } public long Creator { get; set; } public static void Destroy(MarkerData md) { Object.Destroy((Object)(object)md.Marker); Object.Destroy((Object)(object)md.Nametag); } } public class MarkerType { public string Prefab { get; } public Sprite Sprite { get; set; } public string Name { get; } public MarkerGroup Group { get; set; } private ConfigEntry<bool> _showConifgEntry { get; } public bool Show => _showConifgEntry.Value; public MarkerType(string prefab, Sprite sprite, string name, MarkerGroup group, ConfigEntry<bool> show) { Prefab = prefab; Sprite = sprite; Name = name; Group = group; _showConifgEntry = show; } }
plugins/RustyMods-PortalStations/PortalStations.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using PieceManager; using PortalStations.Managers; using PortalStations.Stations; using ServerSync; using TMPro; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("PortalStations")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("PortalStations")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("E0E2F92E-557C-4A05-9D89-AA92A0BD75C4")] [assembly: AssemblyFileVersion("1.0.6")] [assembly: AssemblyCompany("RustyMods")] [assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.6.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<8d7594b7-f2cd-45d0-9b99-4e4febaeab83>Embedded] internal sealed class <8d7594b7-f2cd-45d0-9b99-4e4febaeab83>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [<8d7594b7-f2cd-45d0-9b99-4e4febaeab83>Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [CompilerGenerated] internal sealed class <d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [<8d7594b7-f2cd-45d0-9b99-4e4febaeab83>Embedded] internal sealed class <aec202c8-4aef-4311-9f25-b963dcadb146>NullableContextAttribute : Attribute { public readonly byte Flag; public <aec202c8-4aef-4311-9f25-b963dcadb146>NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace PieceManager { [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] [PublicAPI] public static class MaterialReplacer { [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] public enum ShaderType { PieceShader, VegetationShader, RockShader, RugShader, GrassShader, CustomCreature, UseUnityShader } private static readonly Dictionary<GameObject, bool> ObjectToSwap; internal static readonly Dictionary<string, Material> OriginalMaterials; private static readonly Dictionary<GameObject, ShaderType> ObjectsForShaderReplace; private static bool hasRun; static MaterialReplacer() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown OriginalMaterials = new Dictionary<string, Material>(); ObjectToSwap = new Dictionary<GameObject, bool>(); ObjectsForShaderReplace = new Dictionary<GameObject, ShaderType>(); Harmony val = new Harmony("org.bepinex.helpers.PieceManager"); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZoneSystem), "Start", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(MaterialReplacer), "ReplaceAllMaterialsWithOriginal", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static void RegisterGameObjectForShaderSwap(GameObject go, ShaderType type) { if (!ObjectsForShaderReplace.ContainsKey(go)) { ObjectsForShaderReplace.Add(go, type); } } public static void RegisterGameObjectForMatSwap(GameObject go, bool isJotunnMock = false) { if (!ObjectToSwap.ContainsKey(go)) { ObjectToSwap.Add(go, isJotunnMock); } } private static void GetAllMaterials() { Material[] array = Resources.FindObjectsOfTypeAll<Material>(); Material[] array2 = array; foreach (Material val in array2) { OriginalMaterials[((Object)val).name] = val; } } [HarmonyPriority(700)] private static void ReplaceAllMaterialsWithOriginal() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 if ((int)SystemInfo.graphicsDeviceType == 4 || hasRun) { return; } if (OriginalMaterials.Count <= 0) { GetAllMaterials(); } foreach (Renderer item in ObjectToSwap.Keys.SelectMany([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (GameObject gameObject) => gameObject.GetComponentsInChildren<Renderer>(true))) { ObjectToSwap.TryGetValue(((Component)item).gameObject, out var value); Material[] array = (Material[])(object)new Material[item.sharedMaterials.Length]; int num = 0; Material[] sharedMaterials = item.sharedMaterials; foreach (Material val in sharedMaterials) { string text = (value ? "JVLmock_" : "_REPLACE_"); if (((Object)val).name.StartsWith(text, StringComparison.Ordinal)) { string text2 = ((Object)val).name.Replace(" (Instance)", string.Empty).Replace(text, ""); if (OriginalMaterials.ContainsKey(text2)) { array[num] = OriginalMaterials[text2]; } else { Debug.LogWarning((object)("No suitable material found to replace: " + text2)); OriginalMaterials[text2] = array[num]; } num++; } } item.materials = array; item.sharedMaterials = array; } foreach (Renderer item2 in ObjectsForShaderReplace.Keys.SelectMany([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (GameObject gameObject) => gameObject.GetComponentsInChildren<Renderer>(true))) { ObjectsForShaderReplace.TryGetValue(((Component)((Component)item2).gameObject.transform.root).gameObject, out var value2); if ((Object)(object)item2 == (Object)null) { continue; } Material[] sharedMaterials2 = item2.sharedMaterials; foreach (Material val2 in sharedMaterials2) { if ((Object)(object)val2 == (Object)null) { continue; } string name = ((Object)val2.shader).name; switch (value2) { case ShaderType.PieceShader: val2.shader = Shader.Find("Custom/Piece"); break; case ShaderType.VegetationShader: val2.shader = Shader.Find("Custom/Vegetation"); break; case ShaderType.RockShader: val2.shader = Shader.Find("Custom/StaticRock"); break; case ShaderType.RugShader: val2.shader = Shader.Find("Custom/Rug"); break; case ShaderType.GrassShader: val2.shader = Shader.Find("Custom/Grass"); break; case ShaderType.CustomCreature: val2.shader = Shader.Find("Custom/Creature"); break; case ShaderType.UseUnityShader: if ((Object)(object)Shader.Find(name) != (Object)null) { val2.shader = Shader.Find(name); } break; default: val2.shader = Shader.Find("ToonDeferredShading2017"); break; } } } hasRun = true; } } [PublicAPI] public enum CraftingTable { None, [InternalName("piece_workbench")] Workbench, [InternalName("piece_cauldron")] Cauldron, [InternalName("forge")] Forge, [InternalName("piece_artisanstation")] ArtisanTable, [InternalName("piece_stonecutter")] StoneCutter, [InternalName("piece_magetable")] MageTable, [InternalName("blackforge")] BlackForge, Custom } [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] public class InternalName : Attribute { public readonly string internalName; public InternalName(string internalName) { this.internalName = internalName; } } [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] [PublicAPI] public class ExtensionList { public readonly List<ExtensionConfig> ExtensionStations = new List<ExtensionConfig>(); public void Set(CraftingTable table, int maxStationDistance = 5) { ExtensionStations.Add(new ExtensionConfig { Table = table, maxStationDistance = maxStationDistance }); } public void Set(string customTable, int maxStationDistance = 5) { ExtensionStations.Add(new ExtensionConfig { Table = CraftingTable.Custom, custom = customTable, maxStationDistance = maxStationDistance }); } } public struct ExtensionConfig { public CraftingTable Table; public float maxStationDistance; [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(2)] public string custom; } [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] [PublicAPI] public class CraftingStationList { public readonly List<CraftingStationConfig> Stations = new List<CraftingStationConfig>(); public void Set(CraftingTable table) { Stations.Add(new CraftingStationConfig { Table = table }); } public void Set(string customTable) { Stations.Add(new CraftingStationConfig { Table = CraftingTable.Custom, custom = customTable }); } } public struct CraftingStationConfig { public CraftingTable Table; public int level; [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(2)] public string custom; } [PublicAPI] public enum BuildPieceCategory { Misc = 0, Crafting = 1, Building = 2, Furniture = 3, All = 100, Custom = 99 } [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] [PublicAPI] public class RequiredResourcesList { public readonly List<Requirement> Requirements = new List<Requirement>(); public void Add(string item, int amount, bool recover) { Requirements.Add(new Requirement { itemName = item, amount = amount, recover = recover }); } } public struct Requirement { [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(1)] public string itemName; public int amount; public bool recover; } public struct SpecialProperties { [Description("Admins should be the only ones that can build this piece.")] public bool AdminOnly; [Description("Turns off generating a config for this build piece.")] public bool NoConfig; } [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] [PublicAPI] public class BuildingPieceCategory { public BuildPieceCategory Category; public string custom = ""; public void Set(BuildPieceCategory category) { Category = category; } public void Set(string customCategory) { Category = BuildPieceCategory.Custom; custom = customCategory; } } [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] [PublicAPI] public class PieceTool { public readonly HashSet<string> Tools = new HashSet<string>(); public void Add(string tool) { Tools.Add(tool); } } [PublicAPI] [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] public class BuildPiece { [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] internal class PieceConfig { public ConfigEntry<string> craft = null; public ConfigEntry<BuildPieceCategory> category = null; public ConfigEntry<string> customCategory = null; public ConfigEntry<string> tools = null; public ConfigEntry<CraftingTable> extensionTable = null; public ConfigEntry<string> customExtentionTable = null; public ConfigEntry<float> maxStationDistance = null; public ConfigEntry<CraftingTable> table = null; public ConfigEntry<string> customTable = null; } [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(2)] [UsedImplicitly] public string Category; [UsedImplicitly] [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(new byte[] { 2, 1 })] public Action<ConfigEntryBase> CustomDrawer; } [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] private class SerializedRequirements { public readonly List<Requirement> Reqs; public SerializedRequirements(List<Requirement> reqs) { Reqs = reqs; } public SerializedRequirements(string reqs) { Reqs = reqs.Split(new char[1] { ',' }).Select([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (string r) => { string[] array = r.Split(new char[1] { ':' }); Requirement result = default(Requirement); result.itemName = array[0]; result.amount = ((array.Length <= 1 || !int.TryParse(array[1], out var result2)) ? 1 : result2); bool result3 = default(bool); result.recover = array.Length <= 2 || !bool.TryParse(array[2], out result3) || result3; return result; }).ToList(); } public override string ToString() { return string.Join(",", Reqs.Select([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (Requirement r) => $"{r.itemName}:{r.amount}:{r.recover}")); } public static Requirement[] toPieceReqs(SerializedRequirements craft) { Dictionary<string, Requirement> dictionary = craft.Reqs.Where((Requirement r) => r.itemName != "").ToDictionary((Func<Requirement, string>)([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (Requirement r) => r.itemName), (Func<Requirement, Requirement>)([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (Requirement r) => { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) ItemDrop val2 = ResItem(r); return (val2 == null) ? ((Requirement)null) : new Requirement { m_amount = r.amount, m_resItem = val2, m_recover = r.recover }; })); return dictionary.Values.Where([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (Requirement v) => v != null).ToArray(); [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(2)] static ItemDrop ResItem(Requirement r) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(r.itemName); ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null); if ((Object)(object)val == (Object)null) { Debug.LogWarning((object)("The required item '" + r.itemName + "' does not exist.")); } return val; } } } internal static readonly List<BuildPiece> registeredPieces = new List<BuildPiece>(); internal static Dictionary<BuildPiece, PieceConfig> pieceConfigs = new Dictionary<BuildPiece, PieceConfig>(); [Description("Disables generation of the configs for your pieces. This is global, this turns it off for all pieces in your mod.")] public static bool ConfigurationEnabled = true; public readonly GameObject Prefab; [Description("Specifies the resources needed to craft the piece.\nUse .Add to add resources with their internal ID and an amount.\nUse one .Add for each resource type the building piece should need.")] public readonly RequiredResourcesList RequiredItems = new RequiredResourcesList(); [Description("Sets the category for the building piece.")] public readonly BuildingPieceCategory Category = new BuildingPieceCategory(); [Description("Specifies the tool needed to build your piece.\nUse .Add to add a tool.")] public readonly PieceTool Tool = new PieceTool(); [Description("Specifies the crafting station needed to build your piece.\nUse .Add to add a crafting station, using the CraftingTable enum and a minimum level for the crafting station.")] public CraftingStationList Crafting = new CraftingStationList(); [Description("Makes this piece a station extension")] public ExtensionList Extension = new ExtensionList(); [Description("Change the extended/special properties of your build piece.")] public SpecialProperties SpecialProperties; [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(2)] private LocalizeKey _name; [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(2)] private LocalizeKey _description; internal string[] activeTools = null; [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(2)] private static object configManager; [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(2)] private static Localization _english; [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(2)] internal static BaseUnityPlugin _plugin = null; private static bool hasConfigSync = true; [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(2)] private static object _configSync; public LocalizeKey Name { get { LocalizeKey name = _name; if (name != null) { return name; } Piece component = Prefab.GetComponent<Piece>(); if (component.m_name.StartsWith("$")) { _name = new LocalizeKey(component.m_name); } else { string text = "$piece_" + ((Object)Prefab).name.Replace(" ", "_"); _name = new LocalizeKey(text).English(component.m_name); component.m_name = text; } return _name; } } public LocalizeKey Description { get { LocalizeKey description = _description; if (description != null) { return description; } Piece component = Prefab.GetComponent<Piece>(); if (component.m_description.StartsWith("$")) { _description = new LocalizeKey(component.m_description); } else { string text = "$piece_" + ((Object)Prefab).name.Replace(" ", "_") + "_description"; _description = new LocalizeKey(text).English(component.m_description); component.m_description = text; } return _description; } } private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English")); internal static BaseUnityPlugin plugin { get { //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown if (_plugin != null) { return _plugin; } IEnumerable<TypeInfo> source; try { source = Assembly.GetExecutingAssembly().DefinedTypes.ToList(); } catch (ReflectionTypeLoadException ex) { source = from t in ex.Types where t != null select t.GetTypeInfo(); } _plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); return _plugin; } } [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(2)] private static object configSync { [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(2)] get { if (_configSync != null || !hasConfigSync) { return _configSync; } Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync"); if ((object)type != null) { _configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " PieceManager"); type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString()); type.GetProperty("IsLocked").SetValue(_configSync, true); } else { hasConfigSync = false; } return _configSync; } } public BuildPiece(string assetBundleFileName, string prefabName, string folderName = "assets") : this(PiecePrefabManager.RegisterAssetBundle(assetBundleFileName, folderName), prefabName) { } public BuildPiece(AssetBundle bundle, string prefabName) { Prefab = PiecePrefabManager.RegisterPrefab(bundle, prefabName); registeredPieces.Add(this); } internal static void Patch_FejdStartup(FejdStartup __instance) { //IL_0282: Unknown result type (might be due to invalid IL or missing references) //IL_028c: Expected O, but got Unknown //IL_032a: Unknown result type (might be due to invalid IL or missing references) //IL_0334: Expected O, but got Unknown //IL_03d2: Unknown result type (might be due to invalid IL or missing references) //IL_03ac: Unknown result type (might be due to invalid IL or missing references) //IL_03b1: Unknown result type (might be due to invalid IL or missing references) //IL_042d: Unknown result type (might be due to invalid IL or missing references) //IL_0437: Expected O, but got Unknown //IL_05a7: Unknown result type (might be due to invalid IL or missing references) //IL_05b1: Expected O, but got Unknown //IL_088b: Unknown result type (might be due to invalid IL or missing references) //IL_0895: Expected O, but got Unknown //IL_061c: Unknown result type (might be due to invalid IL or missing references) //IL_0626: Expected O, but got Unknown //IL_06c2: Unknown result type (might be due to invalid IL or missing references) //IL_06cc: Expected O, but got Unknown //IL_0900: Unknown result type (might be due to invalid IL or missing references) //IL_090a: Expected O, but got Unknown Type configManagerType = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (Assembly a) => a.GetName().Name == "ConfigurationManager")?.GetType("ConfigurationManager.ConfigurationManager"); configManager = ((configManagerType == null) ? null : Chainloader.ManagerObject.GetComponent(configManagerType)); foreach (BuildPiece registeredPiece in registeredPieces) { registeredPiece.activeTools = registeredPiece.Tool.Tools.DefaultIfEmpty("Hammer").ToArray(); } if (!ConfigurationEnabled) { return; } bool saveOnConfigSet = plugin.Config.SaveOnConfigSet; plugin.Config.SaveOnConfigSet = false; foreach (BuildPiece registeredPiece2 in registeredPieces) { BuildPiece piece = registeredPiece2; if (piece.SpecialProperties.NoConfig) { continue; } PieceConfig pieceConfig2 = (pieceConfigs[piece] = new PieceConfig()); PieceConfig cfg = pieceConfig2; Piece piecePrefab = piece.Prefab.GetComponent<Piece>(); string pieceName = piecePrefab.m_name; string englishName = new Regex("[=\\n\\t\\\\\"\\'\\[\\]]*").Replace(english.Localize(pieceName), "").Trim(); string localizedName = Localization.instance.Localize(pieceName).Trim(); int order = 0; cfg.category = config(englishName, "Build Table Category", piece.Category.Category, new ConfigDescription("Build Category where " + localizedName + " is available.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = (order -= 1), Category = localizedName } })); ConfigurationManagerAttributes customTableAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), Browsable = (cfg.category.Value == BuildPieceCategory.Custom), Category = localizedName }; cfg.customCategory = config(englishName, "Custom Build Category", piece.Category.custom, new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes })); cfg.category.SettingChanged += BuildTableConfigChanged; cfg.customCategory.SettingChanged += BuildTableConfigChanged; if (cfg.category.Value == BuildPieceCategory.Custom) { piecePrefab.m_category = PiecePrefabManager.GetCategory(cfg.customCategory.Value); } else { piecePrefab.m_category = (PieceCategory)cfg.category.Value; } cfg.tools = config(englishName, "Tools", string.Join(", ", piece.activeTools), new ConfigDescription("Comma separated list of tools where " + localizedName + " is available.", (AcceptableValueBase)null, new object[1] { customTableAttributes })); piece.activeTools = (from s in cfg.tools.Value.Split(new char[1] { ',' }) select s.Trim()).ToArray(); cfg.tools.SettingChanged += [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (object _, EventArgs _) => { Inventory[] source = (from c in Player.s_players.Select([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (Player p) => ((Humanoid)p).GetInventory()).Concat(from c in Object.FindObjectsOfType<Container>() select c.GetInventory()) where c != null select c).ToArray(); Dictionary<string, List<PieceTable>> dictionary = (from kv in (from i in (from p in ObjectDB.instance.m_items select p.GetComponent<ItemDrop>() into c where Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((Component)c).GetComponent<ZNetView>()) select c).Concat(ItemDrop.s_instances) select new KeyValuePair<string, ItemData>(Utils.GetPrefabName(((Component)i).gameObject), i.m_itemData)).Concat(from i in source.SelectMany([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (Inventory i) => i.GetAllItems()) select new KeyValuePair<string, ItemData>(((Object)i.m_dropPrefab).name, i)) where Object.op_Implicit((Object)(object)kv.Value.m_shared.m_buildPieces) group kv by kv.Key).ToDictionary([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (IGrouping<string, KeyValuePair<string, ItemData>> g) => g.Key, [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (IGrouping<string, KeyValuePair<string, ItemData>> g) => g.Select([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (KeyValuePair<string, ItemData> kv) => kv.Value.m_shared.m_buildPieces).Distinct().ToList()); string[] array5 = piece.activeTools; foreach (string key in array5) { if (dictionary.TryGetValue(key, out var value3)) { foreach (PieceTable item3 in value3) { item3.m_pieces.Remove(piece.Prefab); } } } piece.activeTools = (from s in cfg.tools.Value.Split(new char[1] { ',' }) select s.Trim()).ToArray(); if (Object.op_Implicit((Object)(object)ObjectDB.instance)) { string[] array6 = piece.activeTools; foreach (string key2 in array6) { if (dictionary.TryGetValue(key2, out var value4)) { foreach (PieceTable item4 in value4) { if (!item4.m_pieces.Contains(piece.Prefab)) { item4.m_pieces.Add(piece.Prefab); } } } } if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)Player.m_localPlayer.m_buildPieces)) { ((Humanoid)Player.m_localPlayer).SetPlaceMode(Player.m_localPlayer.m_buildPieces); } } }; StationExtension pieceExtensionComp; List<ConfigurationManagerAttributes> hideWhenNoneAttributes2; if (piece.Extension.ExtensionStations.Count > 0) { pieceExtensionComp = piece.Prefab.GetOrAddComponent<StationExtension>(); PieceConfig pieceConfig3 = cfg; string group = englishName; CraftingTable table = piece.Extension.ExtensionStations.First().Table; string text = "Crafting station that " + localizedName + " extends."; object[] array = new object[1]; ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes(); int num = order - 1; order = num; configurationManagerAttributes.Order = num; array[0] = configurationManagerAttributes; pieceConfig3.extensionTable = config(group, "Extends Station", table, new ConfigDescription(text, (AcceptableValueBase)null, array)); cfg.customExtentionTable = config(englishName, "Custom Extend Station", piece.Extension.ExtensionStations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes })); PieceConfig pieceConfig4 = cfg; string group2 = englishName; float maxStationDistance = piece.Extension.ExtensionStations.First().maxStationDistance; string text2 = "Distance from the station that " + localizedName + " can be placed."; object[] array2 = new object[1]; ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes(); num = order - 1; order = num; configurationManagerAttributes2.Order = num; array2[0] = configurationManagerAttributes2; pieceConfig4.maxStationDistance = config(group2, "Max Station Distance", maxStationDistance, new ConfigDescription(text2, (AcceptableValueBase)null, array2)); hideWhenNoneAttributes2 = new List<ConfigurationManagerAttributes>(); cfg.extensionTable.SettingChanged += ExtensionTableConfigChanged; cfg.customExtentionTable.SettingChanged += ExtensionTableConfigChanged; cfg.maxStationDistance.SettingChanged += ExtensionTableConfigChanged; ConfigurationManagerAttributes configurationManagerAttributes3 = new ConfigurationManagerAttributes(); num = order - 1; order = num; configurationManagerAttributes3.Order = num; configurationManagerAttributes3.Browsable = cfg.extensionTable.Value != CraftingTable.None; ConfigurationManagerAttributes item = configurationManagerAttributes3; hideWhenNoneAttributes2.Add(item); } List<ConfigurationManagerAttributes> hideWhenNoneAttributes; if (piece.Crafting.Stations.Count > 0) { hideWhenNoneAttributes = new List<ConfigurationManagerAttributes>(); PieceConfig pieceConfig5 = cfg; string group3 = englishName; CraftingTable table2 = piece.Crafting.Stations.First().Table; string text3 = "Crafting station where " + localizedName + " is available."; object[] array3 = new object[1]; ConfigurationManagerAttributes configurationManagerAttributes4 = new ConfigurationManagerAttributes(); int num = order - 1; order = num; configurationManagerAttributes4.Order = num; array3[0] = configurationManagerAttributes4; pieceConfig5.table = config(group3, "Crafting Station", table2, new ConfigDescription(text3, (AcceptableValueBase)null, array3)); cfg.customTable = config(englishName, "Custom Crafting Station", piece.Crafting.Stations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes })); cfg.table.SettingChanged += TableConfigChanged; cfg.customTable.SettingChanged += TableConfigChanged; ConfigurationManagerAttributes configurationManagerAttributes5 = new ConfigurationManagerAttributes(); num = order - 1; order = num; configurationManagerAttributes5.Order = num; configurationManagerAttributes5.Browsable = cfg.table.Value != CraftingTable.None; ConfigurationManagerAttributes item2 = configurationManagerAttributes5; hideWhenNoneAttributes.Add(item2); } cfg.craft = itemConfig("Crafting Costs", new SerializedRequirements(piece.RequiredItems.Requirements).ToString(), "Item costs to craft " + localizedName); cfg.craft.SettingChanged += [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (object _, EventArgs _) => { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && (Object)(object)ObjectDB.instance.GetItemPrefab("Wood") != (Object)null) { Requirement[] resources = SerializedRequirements.toPieceReqs(new SerializedRequirements(cfg.craft.Value)); piecePrefab.m_resources = resources; Piece[] array4 = Object.FindObjectsOfType<Piece>(); foreach (Piece val in array4) { if (val.m_name == pieceName) { val.m_resources = resources; } } } }; void BuildTableConfigChanged(object o, EventArgs e) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) if (registeredPieces.Count > 0) { if (cfg.category.Value == BuildPieceCategory.Custom) { piecePrefab.m_category = PiecePrefabManager.GetCategory(cfg.customCategory.Value); } else { piecePrefab.m_category = (PieceCategory)cfg.category.Value; } if (Object.op_Implicit((Object)(object)Hud.instance)) { PiecePrefabManager.CreateCategoryTabs(); } } customTableAttributes.Browsable = cfg.category.Value == BuildPieceCategory.Custom; ReloadConfigDisplay(); } void ExtensionTableConfigChanged(object o, EventArgs e) { if (piece.RequiredItems.Requirements.Count > 0) { CraftingTable value2 = cfg.extensionTable.Value; CraftingTable craftingTable = value2; if (craftingTable == CraftingTable.Custom) { StationExtension obj2 = pieceExtensionComp; GameObject prefab2 = ZNetScene.instance.GetPrefab(cfg.customExtentionTable.Value); obj2.m_craftingStation = ((prefab2 != null) ? prefab2.GetComponent<CraftingStation>() : null); } else { pieceExtensionComp.m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(cfg.extensionTable.Value.ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent<CraftingStation>(); } pieceExtensionComp.m_maxStationDistance = cfg.maxStationDistance.Value; } customTableAttributes.Browsable = cfg.extensionTable.Value == CraftingTable.Custom; foreach (ConfigurationManagerAttributes item5 in hideWhenNoneAttributes2) { item5.Browsable = cfg.extensionTable.Value != CraftingTable.None; } ReloadConfigDisplay(); plugin.Config.Save(); } void TableConfigChanged(object o, EventArgs e) { if (piece.RequiredItems.Requirements.Count > 0) { switch (cfg.table.Value) { case CraftingTable.None: piecePrefab.m_craftingStation = null; break; case CraftingTable.Custom: { Piece obj = piecePrefab; GameObject prefab = ZNetScene.instance.GetPrefab(cfg.customTable.Value); obj.m_craftingStation = ((prefab != null) ? prefab.GetComponent<CraftingStation>() : null); break; } default: piecePrefab.m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(cfg.table.Value.ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent<CraftingStation>(); break; } } customTableAttributes.Browsable = cfg.table.Value == CraftingTable.Custom; foreach (ConfigurationManagerAttributes item6 in hideWhenNoneAttributes) { item6.Browsable = cfg.table.Value != CraftingTable.None; } ReloadConfigDisplay(); plugin.Config.Save(); } ConfigEntry<string> itemConfig(string name, string value, string desc) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown ConfigurationManagerAttributes configurationManagerAttributes6 = new ConfigurationManagerAttributes { CustomDrawer = DrawConfigTable, Order = (order -= 1), Category = localizedName }; return config(englishName, name, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes6 })); } } if (saveOnConfigSet) { plugin.Config.SaveOnConfigSet = true; plugin.Config.Save(); } void ReloadConfigDisplay() { configManagerType?.GetMethod("BuildSettingList").Invoke(configManager, Array.Empty<object>()); } } [HarmonyPriority(700)] internal static void Patch_ObjectDBInit(ObjectDB __instance) { if ((Object)(object)__instance.GetItemPrefab("Wood") == (Object)null) { return; } foreach (BuildPiece registeredPiece in registeredPieces) { pieceConfigs.TryGetValue(registeredPiece, out var value); registeredPiece.Prefab.GetComponent<Piece>().m_resources = SerializedRequirements.toPieceReqs((value == null) ? new SerializedRequirements(registeredPiece.RequiredItems.Requirements) : new SerializedRequirements(value.craft.Value)); foreach (ExtensionConfig extensionStation in registeredPiece.Extension.ExtensionStations) { switch ((value == null || registeredPiece.Extension.ExtensionStations.Count > 0) ? extensionStation.Table : value.extensionTable.Value) { case CraftingTable.None: registeredPiece.Prefab.GetComponent<StationExtension>().m_craftingStation = null; break; case CraftingTable.Custom: { GameObject prefab = ZNetScene.instance.GetPrefab((value == null || registeredPiece.Extension.ExtensionStations.Count > 0) ? extensionStation.custom : value.customExtentionTable.Value); if (prefab != null) { registeredPiece.Prefab.GetComponent<StationExtension>().m_craftingStation = prefab.GetComponent<CraftingStation>(); } else { Debug.LogWarning((object)("Custom crafting station '" + ((value == null || registeredPiece.Extension.ExtensionStations.Count > 0) ? extensionStation.custom : value.customExtentionTable.Value) + "' does not exist")); } break; } default: if (value != null && value.table.Value == CraftingTable.None) { registeredPiece.Prefab.GetComponent<StationExtension>().m_craftingStation = null; } else { registeredPiece.Prefab.GetComponent<StationExtension>().m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(((value == null || registeredPiece.Extension.ExtensionStations.Count > 0) ? extensionStation.Table : value.extensionTable.Value).ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent<CraftingStation>(); } break; } } foreach (CraftingStationConfig station in registeredPiece.Crafting.Stations) { switch ((value == null || registeredPiece.Crafting.Stations.Count > 0) ? station.Table : value.table.Value) { case CraftingTable.None: registeredPiece.Prefab.GetComponent<Piece>().m_craftingStation = null; break; case CraftingTable.Custom: { GameObject prefab2 = ZNetScene.instance.GetPrefab((value == null || registeredPiece.Crafting.Stations.Count > 0) ? station.custom : value.customTable.Value); if (prefab2 != null) { registeredPiece.Prefab.GetComponent<Piece>().m_craftingStation = prefab2.GetComponent<CraftingStation>(); } else { Debug.LogWarning((object)("Custom crafting station '" + ((value == null || registeredPiece.Crafting.Stations.Count > 0) ? station.custom : value.customTable.Value) + "' does not exist")); } break; } default: if (value != null && value.table.Value == CraftingTable.None) { registeredPiece.Prefab.GetComponent<Piece>().m_craftingStation = null; } else { registeredPiece.Prefab.GetComponent<Piece>().m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(((value == null || registeredPiece.Crafting.Stations.Count > 0) ? station.Table : value.table.Value).ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent<CraftingStation>(); } break; } } } } public void Snapshot(float lightIntensity = 1.3f, Quaternion? cameraRotation = null) { SnapshotPiece(Prefab, lightIntensity, cameraRotation); } internal void SnapshotPiece(GameObject prefab, float lightIntensity = 1.3f, Quaternion? cameraRotation = null) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0239: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Unknown result type (might be due to invalid IL or missing references) //IL_0263: Unknown result type (might be due to invalid IL or missing references) //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0275: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_02d6: Unknown result type (might be due to invalid IL or missing references) //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_0322: Unknown result type (might be due to invalid IL or missing references) //IL_0333: Unknown result type (might be due to invalid IL or missing references) //IL_0338: Unknown result type (might be due to invalid IL or missing references) //IL_036f: Unknown result type (might be due to invalid IL or missing references) //IL_0376: Expected O, but got Unknown //IL_0394: Unknown result type (might be due to invalid IL or missing references) //IL_03d5: Unknown result type (might be due to invalid IL or missing references) //IL_03da: Unknown result type (might be due to invalid IL or missing references) //IL_03e4: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)prefab == (Object)null) && (prefab.GetComponentsInChildren<Renderer>().Any() || prefab.GetComponentsInChildren<MeshFilter>().Any())) { Camera component = new GameObject("CameraIcon", new Type[1] { typeof(Camera) }).GetComponent<Camera>(); component.backgroundColor = Color.clear; component.clearFlags = (CameraClearFlags)2; ((Component)component).transform.position = new Vector3(10000f, 10000f, 10000f); ((Component)component).transform.rotation = (Quaternion)(((??)cameraRotation) ?? Quaternion.Euler(0f, 180f, 0f)); component.fieldOfView = 0.5f; component.farClipPlane = 100000f; component.cullingMask = 8; Light component2 = new GameObject("LightIcon", new Type[1] { typeof(Light) }).GetComponent<Light>(); ((Component)component2).transform.position = new Vector3(10000f, 10000f, 10000f); ((Component)component2).transform.rotation = Quaternion.Euler(5f, 180f, 5f); component2.type = (LightType)1; component2.cullingMask = 8; component2.intensity = lightIntensity; GameObject val = Object.Instantiate<GameObject>(prefab); Transform[] componentsInChildren = val.GetComponentsInChildren<Transform>(); foreach (Transform val2 in componentsInChildren) { ((Component)val2).gameObject.layer = 3; } val.transform.position = Vector3.zero; val.transform.rotation = Quaternion.Euler(23f, 51f, 25.8f); ((Object)val).name = ((Object)prefab).name; MeshRenderer[] componentsInChildren2 = val.GetComponentsInChildren<MeshRenderer>(); Vector3 val3 = componentsInChildren2.Aggregate(Vector3.positiveInfinity, [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (Vector3 cur, MeshRenderer renderer) => { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) Bounds bounds2 = ((Renderer)renderer).bounds; return Vector3.Min(cur, ((Bounds)(ref bounds2)).min); }); Vector3 val4 = componentsInChildren2.Aggregate(Vector3.negativeInfinity, [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (Vector3 cur, MeshRenderer renderer) => { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) Bounds bounds = ((Renderer)renderer).bounds; return Vector3.Max(cur, ((Bounds)(ref bounds)).max); }); val.transform.position = new Vector3(10000f, 10000f, 10000f) - (val3 + val4) / 2f; Vector3 val5 = val4 - val3; TimedDestruction val6 = val.AddComponent<TimedDestruction>(); val6.Trigger(1f); Rect val7 = default(Rect); ((Rect)(ref val7))..ctor(0f, 0f, 128f, 128f); component.targetTexture = RenderTexture.GetTemporary((int)((Rect)(ref val7)).width, (int)((Rect)(ref val7)).height); component.fieldOfView = 20f; float num = Mathf.Max(val5.x, val5.y) + 0.1f; float num2 = num / Mathf.Tan(component.fieldOfView * ((float)Math.PI / 180f)) * 1.1f; ((Component)component).transform.position = new Vector3(10000f, 10000f, 10000f) + new Vector3(0f, 0f, num2); component.Render(); RenderTexture active = RenderTexture.active; RenderTexture.active = component.targetTexture; Texture2D val8 = new Texture2D((int)((Rect)(ref val7)).width, (int)((Rect)(ref val7)).height, (TextureFormat)4, false); val8.ReadPixels(new Rect(0f, 0f, (float)(int)((Rect)(ref val7)).width, (float)(int)((Rect)(ref val7)).height), 0, 0); val8.Apply(); RenderTexture.active = active; prefab.GetComponent<Piece>().m_icon = Sprite.Create(val8, new Rect(0f, 0f, (float)(int)((Rect)(ref val7)).width, (float)(int)((Rect)(ref val7)).height), Vector2.one / 2f); ((Component)component2).gameObject.SetActive(false); component.targetTexture.Release(); ((Component)component).gameObject.SetActive(false); val.SetActive(false); Object.DestroyImmediate((Object)(object)val); Object.Destroy((Object)(object)component); Object.Destroy((Object)(object)component2); Object.Destroy((Object)(object)((Component)component).gameObject); Object.Destroy((Object)(object)((Component)component2).gameObject); } } private static void DrawConfigTable(ConfigEntryBase cfg) { //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Expected O, but got Unknown //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Expected O, but got Unknown //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_01e0: Expected O, but got Unknown //IL_020c: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Expected O, but got Unknown //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Expected O, but got Unknown bool valueOrDefault = cfg.Description.Tags.Select([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (object a) => (a.GetType().Name == "ConfigurationManagerAttributes") ? ((bool?)a.GetType().GetField("ReadOnly")?.GetValue(a)) : null).FirstOrDefault((bool? v) => v.HasValue).GetValueOrDefault(); List<Requirement> list = new List<Requirement>(); bool flag = false; int num = (int)(configManager?.GetType().GetProperty("RightColumnWidth", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(nonPublic: true) .Invoke(configManager, Array.Empty<object>()) ?? ((object)130)); GUILayout.BeginVertical(Array.Empty<GUILayoutOption>()); foreach (Requirement req in new SerializedRequirements((string)cfg.BoxedValue).Reqs) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); int num2 = req.amount; if (int.TryParse(GUILayout.TextField(num2.ToString(), new GUIStyle(GUI.skin.textField) { fixedWidth = 40f }, Array.Empty<GUILayoutOption>()), out var result) && result != num2 && !valueOrDefault) { num2 = result; flag = true; } string text = GUILayout.TextField(req.itemName, new GUIStyle(GUI.skin.textField) { fixedWidth = num - 40 - 67 - 21 - 21 - 12 }, Array.Empty<GUILayoutOption>()); string text2 = (valueOrDefault ? req.itemName : text); flag = flag || text2 != req.itemName; bool flag2 = req.recover; if (GUILayout.Toggle(req.recover, "Recover", new GUIStyle(GUI.skin.toggle) { fixedWidth = 67f }, Array.Empty<GUILayoutOption>()) != req.recover) { flag2 = !flag2; flag = true; } if (GUILayout.Button("x", new GUIStyle(GUI.skin.button) { fixedWidth = 21f }, Array.Empty<GUILayoutOption>()) && !valueOrDefault) { flag = true; } else { list.Add(new Requirement { amount = num2, itemName = text2, recover = flag2 }); } if (GUILayout.Button("+", new GUIStyle(GUI.skin.button) { fixedWidth = 21f }, Array.Empty<GUILayoutOption>()) && !valueOrDefault) { flag = true; list.Add(new Requirement { amount = 1, itemName = "", recover = false }); } GUILayout.EndHorizontal(); } GUILayout.EndVertical(); if (flag) { cfg.BoxedValue = new SerializedRequirements(list).ToString(); } } private static ConfigEntry<T> config<[<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(2)] T>(string group, string name, T value, ConfigDescription description) { ConfigEntry<T> val = plugin.Config.Bind<T>(group, name, value, description); configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T)) .Invoke(configSync, new object[1] { val }); return val; } private static ConfigEntry<T> config<[<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(2)] T>(string group, string name, T value, string description) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())); } } public static class GoExtensions { [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] public static T GetOrAddComponent<[<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] T>(this GameObject gameObject) where T : Component { return gameObject.GetComponent<T>() ?? gameObject.AddComponent<T>(); } } [PublicAPI] [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] public class LocalizeKey { private static readonly List<LocalizeKey> keys = new List<LocalizeKey>(); public readonly string Key; public readonly Dictionary<string, string> Localizations = new Dictionary<string, string>(); public LocalizeKey(string key) { Key = key.Replace("$", ""); } public void Alias(string alias) { Localizations.Clear(); if (!alias.Contains("$")) { alias = "$" + alias; } Localizations["alias"] = alias; Localization.instance.AddWord(Key, Localization.instance.Localize(alias)); } public LocalizeKey English(string key) { return addForLang("English", key); } public LocalizeKey Swedish(string key) { return addForLang("Swedish", key); } public LocalizeKey French(string key) { return addForLang("French", key); } public LocalizeKey Italian(string key) { return addForLang("Italian", key); } public LocalizeKey German(string key) { return addForLang("German", key); } public LocalizeKey Spanish(string key) { return addForLang("Spanish", key); } public LocalizeKey Russian(string key) { return addForLang("Russian", key); } public LocalizeKey Romanian(string key) { return addForLang("Romanian", key); } public LocalizeKey Bulgarian(string key) { return addForLang("Bulgarian", key); } public LocalizeKey Macedonian(string key) { return addForLang("Macedonian", key); } public LocalizeKey Finnish(string key) { return addForLang("Finnish", key); } public LocalizeKey Danish(string key) { return addForLang("Danish", key); } public LocalizeKey Norwegian(string key) { return addForLang("Norwegian", key); } public LocalizeKey Icelandic(string key) { return addForLang("Icelandic", key); } public LocalizeKey Turkish(string key) { return addForLang("Turkish", key); } public LocalizeKey Lithuanian(string key) { return addForLang("Lithuanian", key); } public LocalizeKey Czech(string key) { return addForLang("Czech", key); } public LocalizeKey Hungarian(string key) { return addForLang("Hungarian", key); } public LocalizeKey Slovak(string key) { return addForLang("Slovak", key); } public LocalizeKey Polish(string key) { return addForLang("Polish", key); } public LocalizeKey Dutch(string key) { return addForLang("Dutch", key); } public LocalizeKey Portuguese_European(string key) { return addForLang("Portuguese_European", key); } public LocalizeKey Portuguese_Brazilian(string key) { return addForLang("Portuguese_Brazilian", key); } public LocalizeKey Chinese(string key) { return addForLang("Chinese", key); } public LocalizeKey Japanese(string key) { return addForLang("Japanese", key); } public LocalizeKey Korean(string key) { return addForLang("Korean", key); } public LocalizeKey Hindi(string key) { return addForLang("Hindi", key); } public LocalizeKey Thai(string key) { return addForLang("Thai", key); } public LocalizeKey Abenaki(string key) { return addForLang("Abenaki", key); } public LocalizeKey Croatian(string key) { return addForLang("Croatian", key); } public LocalizeKey Georgian(string key) { return addForLang("Georgian", key); } public LocalizeKey Greek(string key) { return addForLang("Greek", key); } public LocalizeKey Serbian(string key) { return addForLang("Serbian", key); } public LocalizeKey Ukrainian(string key) { return addForLang("Ukrainian", key); } private LocalizeKey addForLang(string lang, string value) { Localizations[lang] = value; if (Localization.instance.GetSelectedLanguage() == lang) { Localization.instance.AddWord(Key, value); } else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key)) { Localization.instance.AddWord(Key, value); } return this; } [HarmonyPriority(300)] internal static void AddLocalizedKeys(Localization __instance, string language) { foreach (LocalizeKey key in keys) { string value2; if (key.Localizations.TryGetValue(language, out var value) || key.Localizations.TryGetValue("English", out value)) { __instance.AddWord(key.Key, value); } else if (key.Localizations.TryGetValue("alias", out value2)) { Localization.instance.AddWord(key.Key, Localization.instance.Localize(value2)); } } } } [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] public static class LocalizationCache { private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>(); internal static void LocalizationPostfix(Localization __instance, string language) { string key = localizations.FirstOrDefault([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (KeyValuePair<string, Localization> l) => l.Value == __instance).Key; if (key != null) { localizations.Remove(key); } if (!localizations.ContainsKey(language)) { localizations.Add(language, __instance); } } public static Localization ForLanguage([<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(2)] string language = null) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out var value)) { return value; } value = new Localization(); if (language != null) { value.SetupLanguage(language); } return value; } } [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] public class AdminSyncing { private static bool isServer; internal static bool registeredOnClient; [HarmonyPriority(700)] internal static void AdminStatusSync(ZNet __instance) { isServer = __instance.IsServer(); if (BuildPiece._plugin != null) { if (isServer) { ZRoutedRpc.instance.Register<ZPackage>(BuildPiece._plugin.Info.Metadata.Name + " PMAdminStatusSync", (Action<long, ZPackage>)RPC_AdminPieceAddRemove); } else if (!registeredOnClient) { ZRoutedRpc.instance.Register<ZPackage>(BuildPiece._plugin.Info.Metadata.Name + " PMAdminStatusSync", (Action<long, ZPackage>)RPC_AdminPieceAddRemove); registeredOnClient = true; } } if (isServer) { ((MonoBehaviour)ZNet.instance).StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List<ZNetPeer> peers, bool isAdmin) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown ZPackage val = new ZPackage(); val.Write(isAdmin); ((MonoBehaviour)ZNet.instance).StartCoroutine(sendZPackage(peers, val)); } static IEnumerator WatchAdminListChanges() { List<string> currentList = new List<string>(ZNet.instance.m_adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!ZNet.instance.m_adminList.GetList().SequenceEqual(currentList)) { currentList = new List<string>(ZNet.instance.m_adminList.GetList()); List<ZNetPeer> adminPeer = (from p in ZNet.instance.GetPeers() where ZNet.instance.ListContainsId(ZNet.instance.m_adminList, p.m_rpc.GetSocket().GetHostName()) select p).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } private static IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write(4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List<IEnumerator<bool>> writers = (from peer in peers where peer.IsReady() select peer into p select TellPeerAdminStatus(p, package)).ToList(); writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); } } private static IEnumerator<bool> TellPeerAdminStatus(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc != null) { SendPackage(package); } void SendPackage(ZPackage pkg) { BaseUnityPlugin plugin = BuildPiece._plugin; string text = ((plugin != null) ? plugin.Info.Metadata.Name : null) + " PMAdminStatusSync"; if (isServer) { peer.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg }); } } yield break; } internal static void RPC_AdminPieceAddRemove(long sender, ZPackage package) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown ZNetPeer peer = ZNet.instance.GetPeer(sender); bool flag = false; try { flag = package.ReadBool(); } catch { } if (isServer) { ZRoutedRpc instance = ZRoutedRpc.instance; long everybody = ZRoutedRpc.Everybody; BaseUnityPlugin plugin = BuildPiece._plugin; instance.InvokeRoutedRPC(everybody, ((plugin != null) ? plugin.Info.Metadata.Name : null) + " PMAdminStatusSync", new object[1] { (object)new ZPackage() }); if (ZNet.instance.ListContainsId(ZNet.instance.m_adminList, peer.m_rpc.GetSocket().GetHostName())) { ZPackage val = new ZPackage(); val.Write(true); ZRpc rpc = peer.m_rpc; BaseUnityPlugin plugin2 = BuildPiece._plugin; rpc.Invoke(((plugin2 != null) ? plugin2.Info.Metadata.Name : null) + " PMAdminStatusSync", new object[1] { val }); } return; } foreach (BuildPiece registeredPiece in BuildPiece.registeredPieces) { if (!registeredPiece.SpecialProperties.AdminOnly) { continue; } Piece component = registeredPiece.Prefab.GetComponent<Piece>(); string name = component.m_name; string text = Localization.instance.Localize(name).Trim(); if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || (Object)(object)ObjectDB.instance.GetItemPrefab("Wood") == (Object)null) { continue; } Piece[] array = Object.FindObjectsOfType<Piece>(); foreach (Piece val2 in array) { if (flag) { if (val2.m_name == name) { val2.m_enabled = true; } } else if (val2.m_name == name) { val2.m_enabled = false; } } List<GameObject> pieces = ObjectDB.instance.GetItemPrefab("Hammer").GetComponent<ItemDrop>().m_itemData.m_shared.m_buildPieces.m_pieces; if (flag) { if (!pieces.Contains(ZNetScene.instance.GetPrefab(((Object)component).name))) { pieces.Add(ZNetScene.instance.GetPrefab(((Object)component).name)); } } else if (pieces.Contains(ZNetScene.instance.GetPrefab(((Object)component).name))) { pieces.Remove(ZNetScene.instance.GetPrefab(((Object)component).name)); } } } } [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] internal class RegisterClientRPCPatch { private static void Postfix(ZNet __instance, ZNetPeer peer) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown if (!__instance.IsServer()) { ZRpc rpc = peer.m_rpc; BaseUnityPlugin plugin = BuildPiece._plugin; rpc.Register<ZPackage>(((plugin != null) ? plugin.Info.Metadata.Name : null) + " PMAdminStatusSync", (Action<ZRpc, ZPackage>)RPC_InitialAdminSync); return; } ZPackage val = new ZPackage(); val.Write(__instance.ListContainsId(__instance.m_adminList, peer.m_rpc.GetSocket().GetHostName())); ZRpc rpc2 = peer.m_rpc; BaseUnityPlugin plugin2 = BuildPiece._plugin; rpc2.Invoke(((plugin2 != null) ? plugin2.Info.Metadata.Name : null) + " PMAdminStatusSync", new object[1] { val }); } private static void RPC_InitialAdminSync(ZRpc rpc, ZPackage package) { AdminSyncing.RPC_AdminPieceAddRemove(0L, package); } } [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] public static class PiecePrefabManager { [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] private struct BundleId { [UsedImplicitly] public string assetBundleFileName; [UsedImplicitly] public string folderName; } private static readonly Dictionary<BundleId, AssetBundle> bundleCache; private static readonly List<GameObject> piecePrefabs; private static readonly Dictionary<string, PieceCategory> PieceCategories; private static readonly Dictionary<string, PieceCategory> OtherPieceCategories; private const string _hiddenCategoryMagic = "(HiddenCategory)"; static PiecePrefabManager() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Expected O, but got Unknown //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Expected O, but got Unknown //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Expected O, but got Unknown //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Expected O, but got Unknown //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Expected O, but got Unknown //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Expected O, but got Unknown //IL_0242: Unknown result type (might be due to invalid IL or missing references) //IL_024f: Expected O, but got Unknown //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Expected O, but got Unknown //IL_02bb: Unknown result type (might be due to invalid IL or missing references) //IL_02c7: Expected O, but got Unknown //IL_02f6: Unknown result type (might be due to invalid IL or missing references) //IL_0303: Expected O, but got Unknown //IL_0333: Unknown result type (might be due to invalid IL or missing references) //IL_033f: Expected O, but got Unknown //IL_036f: Unknown result type (might be due to invalid IL or missing references) //IL_037b: Expected O, but got Unknown //IL_03ab: Unknown result type (might be due to invalid IL or missing references) //IL_03b7: Expected O, but got Unknown //IL_03e5: Unknown result type (might be due to invalid IL or missing references) //IL_0400: Unknown result type (might be due to invalid IL or missing references) //IL_040d: Expected O, but got Unknown //IL_040d: Expected O, but got Unknown //IL_043c: Unknown result type (might be due to invalid IL or missing references) //IL_0449: Expected O, but got Unknown //IL_0478: Unknown result type (might be due to invalid IL or missing references) //IL_0485: Expected O, but got Unknown //IL_04b4: Unknown result type (might be due to invalid IL or missing references) //IL_04c1: Expected O, but got Unknown //IL_04f0: Unknown result type (might be due to invalid IL or missing references) //IL_04fd: Expected O, but got Unknown bundleCache = new Dictionary<BundleId, AssetBundle>(); piecePrefabs = new List<GameObject>(); PieceCategories = new Dictionary<string, PieceCategory>(); OtherPieceCategories = new Dictionary<string, PieceCategory>(); Harmony val = new Harmony("org.bepinex.helpers.PieceManager"); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(BuildPiece), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_ObjectDBInit", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(BuildPiece), "Patch_ObjectDBInit", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "CopyOtherDB", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_ObjectDBInit", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(AdminSyncing), "AdminStatusSync", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNetScene), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_ZNetSceneAwake", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNetScene), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "RefFixPatch_ZNetSceneAwake", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "PrevCategory", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_PieceTable_PrevCategory", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "PrevCategory", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "PrevCategory_Transpiler", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "NextCategory", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_PieceTable_NextCategory", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "NextCategory", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "NextCategory_Transpiler", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "SetCategory", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "SetCategory_Transpiler", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "UpdateAvailable", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "UpdateAvailable_Transpiler", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "UpdateAvailable", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "UpdateAvailable_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "UpdateAvailable_Postfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Player), "SetPlaceMode", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_SetPlaceMode", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Hud), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Hud_AwakeCreateTabs", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Enum), "GetValues", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "EnumGetValuesPatch", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Enum), "GetNames", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "EnumGetNamesPatch", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static AssetBundle RegisterAssetBundle(string assetBundleFileName, string folderName = "assets") { BundleId bundleId = default(BundleId); bundleId.assetBundleFileName = assetBundleFileName; bundleId.folderName = folderName; BundleId key = bundleId; if (!bundleCache.TryGetValue(key, out var value)) { Dictionary<BundleId, AssetBundle> dictionary = bundleCache; AssetBundle? obj = ((IEnumerable<AssetBundle>)Resources.FindObjectsOfTypeAll<AssetBundle>()).FirstOrDefault((Func<AssetBundle, bool>)([<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] (AssetBundle a) => ((Object)a).name == assetBundleFileName)) ?? AssetBundle.LoadFromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + folderName + "." + assetBundleFileName)); AssetBundle result = obj; dictionary[key] = obj; return result; } return value; } public static IEnumerable<GameObject> FixRefs(AssetBundle assetBundle) { return assetBundle.LoadAllAssets<GameObject>(); } public static GameObject RegisterPrefab(string assetBundleFileName, string prefabName, string folderName = "assets") { return RegisterPrefab(RegisterAssetBundle(assetBundleFileName, folderName), prefabName); } public static GameObject RegisterPrefab(AssetBundle assets, string prefabName) { GameObject val = assets.LoadAsset<GameObject>(prefabName); piecePrefabs.Add(val); return val; } public static Sprite RegisterSprite(string assetBundleFileName, string prefabName, string folderName = "assets") { return RegisterSprite(RegisterAssetBundle(assetBundleFileName, folderName), prefabName); } public static Sprite RegisterSprite(AssetBundle assets, string prefabName) { return assets.LoadAsset<Sprite>(prefabName); } private static void EnumGetValuesPatch(Type enumType, ref Array __result) { if (!(enumType != typeof(PieceCategory)) && PieceCategories.Count != 0) { PieceCategory[] array = (PieceCategory[])(object)new PieceCategory[__result.Length + PieceCategories.Count]; __result.CopyTo(array, 0); PieceCategories.Values.CopyTo(array, __result.Length); __result = array; } } private static void EnumGetNamesPatch(Type enumType, ref string[] __result) { if (!(enumType != typeof(PieceCategory)) && PieceCategories.Count != 0) { __result = CollectionExtensions.AddRangeToArray<string>(__result, PieceCategories.Keys.ToArray()); } } public static Dictionary<PieceCategory, string> GetPieceCategoriesMap() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) Array values = Enum.GetValues(typeof(PieceCategory)); string[] names = Enum.GetNames(typeof(PieceCategory)); Dictionary<PieceCategory, string> dictionary = new Dictionary<PieceCategory, string>(); for (int i = 0; i < values.Length; i++) { dictionary[(PieceCategory)values.GetValue(i)] = names[i]; } return dictionary; } public static PieceCategory GetCategory(string name) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) if (Enum.TryParse<PieceCategory>(name, ignoreCase: true, out PieceCategory result)) { return result; } if (PieceCategories.TryGetValue(name, out result)) { return result; } if (OtherPieceCategories.TryGetValue(name, out result)) { return result; } Dictionary<PieceCategory, string> pieceCategoriesMap = GetPieceCategoriesMap(); foreach (KeyValuePair<PieceCategory, string> item in pieceCategoriesMap) { if (item.Value == name) { result = item.Key; OtherPieceCategories[name] = result; return result; } } result = (PieceCategory)(pieceCategoriesMap.Count - 1); PieceCategories[name] = result; string categoryToken = GetCategoryToken(name); Localization.instance.AddWord(categoryToken, name); return result; } internal static void CreateCategoryTabs() { int num = MaxCategory(); for (int i = Hud.instance.m_buildCategoryNames.Count; i < num; i++) { Hud.instance.m_buildCategoryNames.Add(""); } for (int j = Hud.instance.m_pieceCategoryTabs.Length; j < num; j++) { GameObject val = CreateCategoryTab(); Hud.instance.m_pieceCategoryTabs = CollectionExtensions.AddItem<GameObject>((IEnumerable<GameObject>)Hud.instance.m_pieceCategoryTabs, val).ToArray(); } if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)Player.m_localPlayer.m_buildPieces)) { RepositionCategories(Player.m_localPlayer.m_buildPieces); Player.m_localPlayer.UpdateAvailablePiecesList(); } } private static GameObject CreateCategoryTab() { //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) Transform transform = Hud.instance.m_pieceCategoryRoot.transform; GameObject val = Object.Instantiate<GameObject>(Hud.instance.m_pieceCategoryTabs[0], transform); val.SetActive(false); UIInputHandler orAddComponent = val.GetOrAddComponent<UIInputHandler>(); orAddComponent.m_onLeftDown = (Action<UIInputHandler>)Delegate.Combine(orAddComponent.m_onLeftDown, new Action<UIInputHandler>(Hud.instance.OnLeftClickCategory)); TMP_Text[] componentsInChildren = val.GetComponentsInChildren<TMP_Text>(); foreach (TMP_Text val2 in componentsInChildren) { val2.rectTransform.offsetMin = new Vector2(3f, 1f); val2.rectTransform.offsetMax = new Vector2(-3f, -1f); val2.enableAutoSizing = true; val2.fontSizeMin = 12f; val2.fontSizeMax = 20f; val2.lineSpacing = 0.8f; val2.textWrappingMode = (TextWrappingModes)1; val2.overflowMode = (TextOverflowModes)3; } return val; } private static int MaxCategory() { return Enum.GetValues(typeof(PieceCategory)).Length - 1; } private static List<CodeInstruction> TranspileMaxCategory(IEnumerable<CodeInstruction> instructions, int maxOffset) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected O, but got Unknown //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Expected O, but got Unknown //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected O, but got Unknown int num = 4 + maxOffset; List<CodeInstruction> list = new List<CodeInstruction>(); foreach (CodeInstruction instruction in instructions) { if (CodeInstructionExtensions.LoadsConstant(instruction, (long)num)) { list.Add(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "MaxCategory", (Type[])null, (Type[])null))); if (maxOffset != 0) { list.Add(new CodeInstruction(OpCodes.Ldc_I4, (object)maxOffset)); list.Add(new CodeInstruction(OpCodes.Add, (object)null)); } } else { list.Add(instruction); } } return list; } private static IEnumerable<CodeInstruction> NextCategory_Transpiler(IEnumerable<CodeInstruction> instructions) { return TranspileMaxCategory(instructions, 0); } private static IEnumerable<CodeInstruction> PrevCategory_Transpiler(IEnumerable<CodeInstruction> instructions) { return TranspileMaxCategory(instructions, -1); } private static IEnumerable<CodeInstruction> SetCategory_Transpiler(IEnumerable<CodeInstruction> instructions) { return TranspileMaxCategory(instructions, -1); } private static IEnumerable<CodeInstruction> UpdateAvailable_Transpiler(IEnumerable<CodeInstruction> instructions) { return TranspileMaxCategory(instructions, 0); } private static HashSet<PieceCategory> CategoriesInPieceTable(PieceTable pieceTable) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) HashSet<PieceCategory> hashSet = new HashSet<PieceCategory>(); foreach (GameObject piece in pieceTable.m_pieces) { hashSet.Add(piece.GetComponent<Piece>().m_category); } return hashSet; } private static void RepositionCategories(PieceTable pieceTable) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Invalid comparison between Unknown and I4 //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Unknown result type (might be due to invalid IL or missing references) //IL_023a: Expected O, but got Unknown //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02b5: Invalid comparison between Unknown and I4 //IL_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Expected I4, but got Unknown RectTransform val = (RectTransform)Hud.instance.m_pieceCategoryTabs[0].transform; RectTransform val2 = (RectTransform)Hud.instance.m_pieceCategoryRoot.transform; RectTransform val3 = (RectTransform)Hud.instance.m_pieceSelectionWindow.transform; Rect rect = val.rect; Vector2 size = ((Rect)(ref rect)).size; HashSet<PieceCategory> hashSet = CategoriesInPieceTable(pieceTable); Dictionary<PieceCategory, string> pieceCategoriesMap = GetPieceCategoriesMap(); bool flag = hashSet.Count == 1 && (int)hashSet.First() == 0; pieceTable.m_useCategories = !flag; rect = val2.rect; int num = Mathf.Max((int)(((Rect)(ref rect)).width / size.x), 1); int num2 = VisibleTabCount(hashSet); float num3 = (0f - size.x) * (float)num / 2f + size.x / 2f; float num4 = (size.y + 1f) * Mathf.Floor((float)(num2 - 1) / (float)num) + 5f; Vector2 val4 = default(Vector2); ((Vector2)(ref val4))..ctor(num3, num4); int num5 = 0; for (int i = 0; i < Hud.instance.m_pieceCategoryTabs.Length; i++) { GameObject val5 = Hud.instance.m_pieceCategoryTabs[i]; string text = pieceCategoriesMap[(PieceCategory)i]; bool flag2 = hashSet.Contains((PieceCategory)i); SetTabActive(val5, text, flag2); if (flag2) { RectTransform component = val5.GetComponent<RectTransform>(); float num6 = size.x * (float)(num5 % num); float num7 = (0f - (size.y + 1f)) * Mathf.Floor((float)num5 / (float)num); component.anchoredPosition = val4 + new Vector2(num6, num7); component.anchorMin = new Vector2(0.5f, 0f); component.anchorMax = new Vector2(0.5f, 1f); num5++; } if (PieceCategories.ContainsKey(text)) { Hud.instance.m_buildCategoryNames[i] = "$" + GetCategoryToken(text); } } Transform obj = ((Transform)val3).Find("Bkg2"); RectTransform val6 = (RectTransform)((obj != null) ? ((Component)obj).transform : null); if (Object.op_Implicit((Object)(object)val6)) { float num8 = (size.y + 1f) * (float)Mathf.Max(0, Mathf.FloorToInt((float)(num5 - 1) / (float)num)); val6.offsetMax = new Vector2(val6.offsetMax.x, num8); } else { Debug.LogWarning((object)"RefreshCategories: Could not find background image"); } if ((int)Player.m_localPlayer.m_buildPieces.m_selectedCategory >= Hud.instance.m_buildCategoryNames.Count) { Player.m_localPlayer.m_buildPieces.SetCategory((int)hashSet.First()); } ((Component)Hud.instance).GetComponentInParent<Localize>().RefreshLocalization(); } private static int VisibleTabCount(HashSet<PieceCategory> visibleCategories) { int num = 0; for (int i = 0; i < Hud.instance.m_pieceCategoryTabs.Length; i++) { if (visibleCategories.Contains((PieceCategory)i)) { num++; } } return num; } private static void SetTabActive(GameObject tab, string tabName, bool active) { tab.SetActive(active); if (active) { ((Object)tab).name = tabName.Replace("(HiddenCategory)", ""); } else { ((Object)tab).name = tabName + "(HiddenCategory)"; } } private static string GetCategoryToken(string name) { char[] endChars = Localization.instance.m_endChars; string text = string.Concat(name.ToLower().Split(endChars)); return "piecemanager_cat_" + text; } private static void Patch_SetPlaceMode(Player __instance) { if (Object.op_Implicit((Object)(object)__instance.m_buildPieces)) { RepositionCategories(__instance.m_buildPieces); } } private static void Patch_PieceTable_NextCategory(PieceTable __instance) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) if (__instance.m_pieces.Count != 0 && __instance.m_useCategories) { GameObject val = Hud.instance.m_pieceCategoryTabs[__instance.m_selectedCategory]; if (((Object)val).name.Contains("(HiddenCategory)")) { __instance.NextCategory(); } } } private static void Patch_PieceTable_PrevCategory(PieceTable __instance) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) if (__instance.m_pieces.Count != 0 && __instance.m_useCategories) { GameObject val = Hud.instance.m_pieceCategoryTabs[__instance.m_selectedCategory]; if (((Object)val).name.Contains("(HiddenCategory)")) { __instance.PrevCategory(); } } } private static void UpdateAvailable_Prefix(PieceTable __instance) { if (__instance.m_availablePieces.Count > 0) { int num = MaxCategory() - __instance.m_availablePieces.Count; for (int i = 0; i < num; i++) { __instance.m_availablePieces.Add(new List<Piece>()); } } } private static void UpdateAvailable_Postfix(PieceTable __instance) { Array.Resize(ref __instance.m_selectedPiece, __instance.m_availablePieces.Count); Array.Resize(ref __instance.m_lastSelectedPiece, __instance.m_availablePieces.Count); } [HarmonyPriority(200)] private static void Hud_AwakeCreateTabs() { CreateCategoryTabs(); } [HarmonyPriority(700)] private static void Patch_ZNetSceneAwake(ZNetScene __instance) { foreach (GameObject piecePrefab in piecePrefabs) { if (!__instance.m_prefabs.Contains(piecePrefab)) { __instance.m_prefabs.Add(piecePrefab); } } } [HarmonyPriority(700)] private static void RefFixPatch_ZNetSceneAwake(ZNetScene __instance) { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) foreach (GameObject piecePrefab in piecePrefabs) { if (__instance.m_prefabs.Contains(piecePrefab) && Object.op_Implicit((Object)(object)piecePrefab.GetComponent<StationExtension>())) { piecePrefab.GetComponent<Piece>().m_isUpgrade = true; piecePrefab.GetComponent<StationExtension>().m_connectionPrefab = __instance.GetPrefab("piece_workbench_ext3").GetComponent<StationExtension>().m_connectionPrefab; piecePrefab.GetComponent<StationExtension>().m_connectionOffset = __instance.GetPrefab("piece_workbench_ext3").GetComponent<StationExtension>().m_connectionOffset; } } } [HarmonyPriority(300)] private static void Patch_ObjectDBInit(ObjectDB __instance) { foreach (BuildPiece registeredPiece in BuildPiece.registeredPieces) { string[] activeTools = registeredPiece.activeTools; foreach (string text in activeTools) { GameObject itemPrefab = __instance.GetItemPrefab(text); PieceTable val = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_buildPieces : null); if (val != null && !val.m_pieces.Contains(registeredPiece.Prefab)) { val.m_pieces.Add(registeredPiece.Prefab); } } } } } } namespace PortalStations { [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(1)] [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(0)] [BepInPlugin("RustyMods.PortalStations", "PortalStations", "1.0.6")] public class PortalStationsPlugin : BaseUnityPlugin { [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] public enum Toggle { On = 1, Off = 0 } [<aec202c8-4aef-4311-9f25-b963dcadb146>NullableContext(0)] private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order = null; [UsedImplicitly] public bool? Browsable = null; [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(2)] [UsedImplicitly] public string Category = null; [<d1c336ec-4c24-4fcb-b6d8-c1ee54c1e26a>Nullable(new byte[] { 2, 1 })] [UsedImplicitly] public Action<ConfigEntryBase> CustomDrawer = null; } internal const string ModName = "PortalStations"; internal const string ModVersion = "1.0.6"; internal const string Author = "RustyMods"; private const string ModGUID = "RustyMods.PortalStations"; private static string ConfigFileName = "RustyMods.PortalStations.cfg"; private static string ConfigFileFullPath; internal static string ConnectionError; private readonly Harmony _harmony = new Harmony("RustyMods.PortalStations"); public static readonly ManualLogSource PortalStationsLogger; private static readonly ConfigSync ConfigSync; public static PortalStationsPlugin _plugin; public static AssetBundle _asset; private static ConfigEntry<Toggle> _serverConfigLocked; public static ConfigEntry<Toggle> _TeleportAnything; public static ConfigEntry<string> _DeviceFuel; public static ConfigEntry<Toggle> _DeviceUseFuel; public static ConfigEntry<int> _DevicePerFuelAmount; public static ConfigEntry<int> _DeviceAdditionalDistancePerUpgrade; public static ConfigEntry<Toggle> _PortalToPlayers; public static ConfigEntry<string> _TinKey; public static ConfigEntry<string> _CopperKey; public static ConfigEntry<string> _BronzeKey; public static ConfigEntry<string> _IronKey; public static ConfigEntry<string> _SilverKey; public static ConfigEntry<string> _BlackMetalKey; public static ConfigEntry<string> _DragonEggKey; public static ConfigEntry<string> _DvergerNeedleKey; public static ConfigEntry<string> _FlameMetalKey; public static ConfigEntry<Toggle> _UsePortalKeys; public static ConfigEntry<Toggle> _UsePrivateKeys; public static ConfigEntry<string> _StationTitle; public static ConfigEntry<string> _PortableStationTitle; public static ConfigEntry<string> _StationDestinationText; public static ConfigEntry<string> _StationCloseText; public static ConfigEntry<string> _StationFilterText; public static ConfigEntry<string> _StationSetNameText; public static ConfigEntry<string> _StationUseText; public static ConfigEntry<string> _StationRenameText; public static ConfigEntry<string> _NotEnoughFuelText; public static ConfigEntry<string> _PublicText; public static ConfigEntry<Toggle> _OnlyAdminRename; public void Awake() { _plugin = this; _asset = GetAssetBundle("portal_station_assets"); _serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only."); ConfigSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked); InitPieces(); InitItems(); InitConfigs(); PortalStations.Stations.Stations.InitCoroutine(); Assembly executingAssembly = Assembly.GetExecutingAssembly(); _harmony.PatchAll(executingAssembly); SetupWatcher(); } private void InitPieces() { BuildPiece buildPiece = new BuildPiece("portal_station_assets", "portalstation"); buildPiece.Name.English("Ancient Portal"); buildPiece.Description.English("Teleportation portal"); buildPiece.RequiredItems.Add("Stone", 20, recover: true); buildPiece.RequiredItems.Add("SurtlingCore", 2, recover: true); buildPiece.RequiredItems.Add("FineWood", 20, recover: true); buildPiece.RequiredItems.Add("GreydwarfEye", 10, recover: true); buildPiece.Category.Set(BuildPieceCategory.Misc); buildPiece.Crafting.Set(PieceManager.CraftingTable.Workbench); MaterialReplacer.RegisterGameObjectForShaderSwap(((Component)buildPiece.Prefab.transform.Find("Visual Root")).gameObject, MaterialReplacer.ShaderType.PieceShader); MaterialReplacer.RegisterGameObjectForMatSwap(((Component)Utils.FindChild(buildPiece.Prefab.transform, "vanilla_effects", (IterativeSearchType)0)).gameObject); buildPiece.Prefab.AddComponent<PortalStation>(); PieceEffectsSetter.PrefabsToSet.Add(buildPiece.Prefab); PortalStations.Stations.Stations.PrefabsToSearch.Add(((Object)buildPiece.Prefab).name); BuildPiece buildPiece2 = new BuildPiece("portal_station_assets", "portalStationOne"); buildPiece2.Name.English("Chained Portal"); buildPiece2.Description.English("Teleportation portal"); buildPiece2.RequiredItems.Add("Stone", 20, recover: true); buildPiece2.RequiredItems.Add("SurtlingCore", 2, recover: true); buildPiece2.RequiredItems.Add("FineWood", 20, recover: true); buildPiece2.RequiredItems.Add("GreydwarfEye", 10, recover: true); buildPiece2.Category.Set(BuildPieceCategory.Misc); buildPiece2.Crafting.Set(PieceManager.CraftingTable.Workbench); MaterialReplacer.RegisterGameObjectForMatSwap(((Component)Utils.FindChild(buildPiece2.Prefab.transform, "vanilla_effects", (IterativeSearchType)0)).gameObject); buildPiece2.Prefab.AddComponent<PortalStation>(); PieceEffectsSetter.PrefabsToSet.Add(buildPiece2.Prefab); PortalStations.Stations.Stations.PrefabsToSearch.Add(((Object)buildPiece2.Prefab).name); BuildPiece buildPiece3 = new BuildPiece("portal_station_assets", "portalPlatform"); buildPiece3.Name.English("Platform Portal"); buildPiece3.Description.English("Teleportation portal"); buildPiece3.RequiredItems.Add("Stone", 20, recover: true); buildPiece3.RequiredItems.Add("SurtlingCore", 2, recover: true); buildPiece3.RequiredItems.Add("FineWood", 20, recover: true); buildPiece3.RequiredItems.Add("Gr