using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using Splatform; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("TheGreatestMap")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+f63023aec05304404628a9f8b2b391aa382eeb99")] [assembly: AssemblyProduct("TheGreatestMap")] [assembly: AssemblyTitle("TheGreatestMap")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace JetBrains.Annotations { [AttributeUsage(AttributeTargets.All)] internal sealed class PublicAPIAttribute : Attribute { public PublicAPIAttribute() { } public PublicAPIAttribute(string comment) { } } [AttributeUsage(AttributeTargets.All)] internal sealed class UsedImplicitlyAttribute : Attribute { } } namespace ServerSync { [PublicAPI] public abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] public class SyncedConfigEntry(ConfigEntry sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry SourceConfig = sourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } public abstract class CustomSyncedValueBase { public object? LocalBaseValue; public readonly string Identifier; public readonly Type Type; private object? boxedValue; protected bool localIsOwner; public readonly int Priority; public object? BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action? ValueChanged; protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [PublicAPI] public sealed class CustomSyncedValue : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [PublicAPI] public class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { public static ZRpc? currentRpc; [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register(configSync2.Name + " ConfigSync", (Action)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List CurrentList = new List(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List(adminList.GetList()); List list = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId != null) ? ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })) : adminList.Contains(hostName); }).ToList(); SendAdmin(ZNet.instance.GetPeers().Except(list).ToList(), isAdmin: false); SendAdmin(list, isAdmin: true); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register(configSync.Name + " ConfigSync", (Action)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary configValues = new Dictionary(); public readonly Dictionary customValues = new Dictionary(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished; public volatile int versionMatchQueued = -1; public readonly List Package = new List(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFabSocket)this)..ctor(); } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix(ref Dictionary? __state, ZNet __instance, ZRpc rpc) { //IL_0073: Unknown result type (might be due to invalid IL or missing references) if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend != 0) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); object? value = fieldInfo.GetValue(val); ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null); if (val2 != null) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId); } fieldInfo.SetValue(val, bufferingSocket); } if (__state == null) { __state = new Dictionary(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List list = new List(); if (configSync.CurrentVersion != null) { list.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); list.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)methodInfo == null) ? ((object)val.Contains(rpc.GetSocket().GetHostName())) : methodInfo.Invoke(ZNet.instance, new object[2] { val, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, list, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section; public string key; public Type type; public object? value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } private class InvalidDeserializationTypeException : Exception { public string expected; public string received; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet configSyncs; private readonly HashSet allConfigs = new HashSet(); private HashSet allCustomValues = new HashSet(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary> configValueCache = new Dictionary>(); private readonly List> cacheExpirations = new List>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0051; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (num) { return !lockExempt; } goto IL_0051; IL_0051: return false; } set { forceConfigLocking = value; } } public bool IsAdmin { get { if (!lockExempt) { return isSourceOfTruth; } return true; } } public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } public event Action? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry AddConfigEntry(ConfigEntry configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry syncedEntry = ownConfigEntryBase as SyncedConfigEntry; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty()).Concat(new SyncedConfigEntry[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(0L, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry AddLockingConfigEntry(ConfigEntry lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(0L, customValue); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { //IL_0209: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Expected O, but got Unknown //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Expected O, but got Unknown //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(delegate(KeyValuePair kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out var value)) { value = new SortedDictionary(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4) != 0) { MemoryStream stream = new MemoryStream(package.ReadByteArray()); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; val2.Save(); } foreach (KeyValuePair customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int num2 = 0; num2 < num; num2++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected)); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown"))); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName)); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match.")); } continue; } Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs")); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } if (!configSync.IsSourceOfTruth && config.SynchronizedConfig && config.LocalBaseValue != null) { if (!configSync.IsLocked) { if (config == configSync.lockedConfig) { return lockExempt; } return true; } return false; } return true; } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (val == null) { val = item.BaseConfig.ConfigFile; saveOnConfigSet = val.SaveOnConfigSet; val.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (val != null) { val.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer.m_socket.IsConnected()) { ZPackage val = new ZPackage(); val.Write((byte)2); val.Write(packageIdentifier); val.Write(fragment); val.Write(fragments); val.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(val); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg }); } } IEnumerable waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty().GetEnumerator(); } List list = (List)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != 0L) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] array = package.GetArray(); if (array != null && array.LongLength > 10000) { ZPackage val = new ZPackage(); val.Write((byte)4); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal)) { deflateStream.Write(array, 0, array.Length); } val.Write(memoryStream.ToArray()); package = val; } List> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private static OwnConfigEntryBase? configData(ConfigEntryBase config) { return config.Description.Tags?.OfType().SingleOrDefault(); } public static SyncedConfigEntry? ConfigData(ConfigEntry config) { return ((ConfigEntryBase)config).Description.Tags?.OfType>().SingleOrDefault(); } private static T configAttribute(ConfigEntryBase config) { return config.Description.Tags.OfType().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { if (!type.IsEnum) { return type; } return Enum.GetUnderlyingType(type); } private static ZPackage ConfigsToPackage(IEnumerable? configs = null, IEnumerable? customValues = null, IEnumerable? packageEntries = null, bool partial = true) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown List list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List(); List list2 = customValues?.ToList() ?? new List(); ZPackage val = new ZPackage(); val.Write(partial ? ((byte)1) : ((byte)0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty()) { AddEntryToPackage(val, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(val, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(val, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return val; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, object? value) { Type type = value?.GetType(); if (value is Enum) { value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture); } else { if (value is ICollection collection) { package.Write(collection.Count); { foreach (object item in collection) { AddValueToZPackage(package, item); } return; } } if ((object)type != null && type.IsValueType && !type.IsPrimitive) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); package.Write(fields.Length); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { package.Write(GetZPackageTypeString(fieldInfo.FieldType)); AddValueToZPackage(package, fieldInfo.GetValue(value)); } return; } } ZRpc.Serialize(new object[1] { value }, ref package); } private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type) { if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); int num = package.ReadInt(); if (num != fields.Length) { throw new InvalidDeserializationTypeException { received = $"(field count: {num})", expected = $"(field count: {fields.Length})" }; } object uninitializedObject = FormatterServices.GetUninitializedObject(type); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { string text = package.ReadString(); if (text != GetZPackageTypeString(fieldInfo.FieldType)) { throw new InvalidDeserializationTypeException { received = text, expected = GetZPackageTypeString(fieldInfo.FieldType), field = fieldInfo.Name }; } fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType)); } return uninitializedObject; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { int num2 = package.ReadInt(); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type); Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments); FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic); for (int j = 0; j < num2; j++) { object obj = ReadValueWithTypeFromZPackage(package, type2); dictionary.Add(field.GetValue(obj), field2.GetValue(obj)); } return dictionary; } if (type != typeof(List) && type.IsGenericType) { Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]); if ((object)type3 != null && type3.IsAssignableFrom(type)) { int num3 = package.ReadInt(); object obj2 = Activator.CreateInstance(type); MethodInfo method = type3.GetMethod("Add"); for (int k = 0; k < num3; k++) { method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) }); } return obj2; } } ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo)); AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type); List source = new List(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [PublicAPI] [HarmonyPatch] public class VersionCheck { private static readonly HashSet versionChecks; private static readonly Dictionary notProcessedNames; public string Name; private string? displayName; private string? currentVersion; private string? minimumRequiredVersion; public bool ModRequired = true; private string? ReceivedCurrentVersion; private string? ReceivedMinimumRequiredVersion; private readonly List ValidatedClients = new List(); private ConfigSync? ConfigSync; public string DisplayName { get { return displayName ?? Name; } set { displayName = value; } } public string CurrentVersion { get { return currentVersion ?? "0.0.0"; } set { currentVersion = value; } } public string MinimumRequiredVersion { get { string text = minimumRequiredVersion; if (text == null) { if (!ModRequired) { return "0.0.0"; } text = CurrentVersion; } return text; } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null)); if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony val = new Harmony("org.bepinex.helpers.ServerSync"); foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) }) where t.IsClass select t) { val.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet(); notProcessedNames = new Dictionary(); typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1] { new Action(PatchServerSync) }); } public VersionCheck(string name) { Name = name; ModRequired = true; versionChecks.Add(this); } public VersionCheck(ConfigSync configSync) { ConfigSync = configSync; Name = ConfigSync.Name; versionChecks.Add(this); } public void Initialize() { ReceivedCurrentVersion = null; ReceivedMinimumRequiredVersion = null; if (ConfigSync != null) { Name = ConfigSync.Name; DisplayName = ConfigSync.DisplayName; CurrentVersion = ConfigSync.CurrentVersion; MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion; ModRequired = ConfigSync.ModRequired; } } private bool IsVersionOk() { if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null) { return !ModRequired; } bool num = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion); bool flag = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion); return num && flag; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } if (!(new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion))) { return DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + "."; } return DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + "."; } private string ErrorServer(ZRpc rpc) { return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion; } private string Error(ZRpc? rpc = null) { if (rpc != null) { return ErrorServer(rpc); } return ErrorClient(); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray(); } private static void Logout() { Game.instance.Logout(true, true); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", new object[1] { 3 }); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action? original) { string text = pkg.ReadString(); string text2 = pkg.ReadString(); string text3 = pkg.ReadString(); bool flag = false; foreach (VersionCheck versionCheck in versionChecks) { if (!(text != versionCheck.Name)) { Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + ".")); versionCheck.ReceivedMinimumRequiredVersion = text2; versionCheck.ReceivedCurrentVersion = text3; if (ZNet.instance.IsServer() && versionCheck.IsVersionOk()) { versionCheck.ValidatedClients.Add(rpc); } flag = true; } } if (flag) { return; } pkg.SetPos(0); if (original != null) { original(rpc, pkg); if (pkg.GetPos() == 0) { notProcessedNames.Add(text, text3); } } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; for (int i = 0; i < array2.Length; i++) { Debug.LogWarning((object)array2[i].Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Expected O, but got Unknown notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck"))) { object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")]; Action action = (Action)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register("ServerSync VersionCheck", (Action)delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register("ServerSync VersionCheck", (Action)CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + ".")); ZPackage val = new ZPackage(); val.Write(versionCheck.Name); val.Write(versionCheck.MinimumRequiredVersion); val.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val }); } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] [HarmonyPrefix] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] [HarmonyPostfix] private static void ShowConnectionError(FejdStartup __instance) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_0221: 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_023b: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_026b: Unknown result type (might be due to invalid IL or missing references) if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3) { return; } object obj = AccessTools.Field(typeof(FejdStartup), "m_connectionFailedError")?.GetValue(__instance); if (obj == null) { return; } PropertyInfo property = obj.GetType().GetProperty("text"); if (property == null) { return; } bool flag = false; VersionCheck[] failedClient = GetFailedClient(); if (failedClient.Length != 0) { string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error())); property.SetValue(obj, (string)property.GetValue(obj) + "\n" + text); flag = true; } foreach (KeyValuePair item in notProcessedNames.OrderBy((KeyValuePair kv) => kv.Key)) { string text2 = (string)property.GetValue(obj); if (!text2.Contains(item.Key)) { property.SetValue(obj, text2 + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed."); flag = true; } } if (flag) { RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; obj.GetType().GetMethod("ForceMeshUpdate", Type.EmptyTypes)?.Invoke(obj, null); float num = (float)(obj.GetType().GetProperty("renderedHeight")?.GetValue(obj) ?? ((object)0f)) + 105f; RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } } namespace TheGreatestMap { internal static class Access { internal static readonly FieldRef> Pins = AccessTools.FieldRefAccess>("m_pins"); internal static readonly FieldRef NamePin = AccessTools.FieldRefAccess("m_namePin"); internal static readonly FieldRef SelectedType = AccessTools.FieldRefAccess("m_selectedType"); internal static readonly FieldRef PinUpdateRequired = AccessTools.FieldRefAccess("m_pinUpdateRequired"); internal static readonly FieldRef VisibleIconTypes = AccessTools.FieldRefAccess("m_visibleIconTypes"); private static readonly MethodInfo _worldToMapPoint = AccessTools.Method(typeof(Minimap), "WorldToMapPoint", (Type[])null, (Type[])null); internal static readonly FieldRef NView = AccessTools.FieldRefAccess("m_nview"); internal static readonly FieldRef ZAnim = AccessTools.FieldRefAccess("m_zanim"); internal static readonly FieldRef VisEquip = AccessTools.FieldRefAccess("m_visEquipment"); internal static readonly FieldRef InteractMask = AccessTools.FieldRefAccess("m_interactMask"); private static readonly MethodInfo _showHandItems = AccessTools.Method(typeof(Humanoid), "ShowHandItems", (Type[])null, (Type[])null); internal static readonly FieldRef ProxyInstance = AccessTools.FieldRefAccess("m_instance"); internal static readonly FieldRef RoutedId = AccessTools.FieldRefAccess("m_id"); internal static readonly FieldRef TableView = AccessTools.FieldRefAccess("m_nview"); internal static readonly FieldRef Explored = AccessTools.FieldRefAccess("m_explored"); internal static readonly FieldRef ExploredOthers = AccessTools.FieldRefAccess("m_exploredOthers"); private static readonly MethodInfo _readExploredArray = AccessTools.Method(typeof(Minimap), "ReadExploredArray", (Type[])null, (Type[])null); private static readonly MethodInfo _tableWrite = AccessTools.Method(typeof(MapTable), "OnWrite", (Type[])null, (Type[])null); internal static void WorldToMapPoint(Minimap map, Vector3 p, out float mx, out float my) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) object[] array = new object[3] { p, 0f, 0f }; _worldToMapPoint.Invoke(map, array); mx = (float)array[1]; my = (float)array[2]; } internal static void ShowHandItems(Humanoid humanoid) { _showHandItems.Invoke(humanoid, new object[2] { false, true }); } internal static List ReadExploredArray(Minimap map, ZPackage pkg, int version) { Type parameterType = _readExploredArray.GetParameters()[1].ParameterType; return (List)_readExploredArray.Invoke(map, new object[2] { pkg, Enum.ToObject(parameterType, version) }); } internal static bool TableWrite(MapTable table, Humanoid user) { return (bool)_tableWrite.Invoke(table, new object[3] { null, user, null }); } } internal static class Buildings { internal sealed class Result { public Vector3 Centroid; public int Pieces; public string Id; } private const float LinkDistance = 3f; private const int MaxPieces = 400; private static readonly Dictionary _cache = new Dictionary(); private static readonly Collider[] _buffer = (Collider[])(object)new Collider[128]; private static int _mask = -1; private const int MinPieces = 4; internal static string LastRejectReason; private static int Mask { get { if (_mask < 0) { _mask = LayerMask.GetMask(new string[5] { "piece", "piece_nonsolid", "Default", "static_solid", "Default_small" }); } return _mask; } } internal static void Clear() { _cache.Clear(); } internal static Result Peek(GameObject piece) { GameObject val = RootOf(piece); if (!((Object)(object)val != (Object)null) || !_cache.TryGetValue(((Object)val).GetInstanceID(), out var value)) { return null; } return value; } internal static Result Resolve(GameObject piece, Vector3 locationCenter, float locationRadius) { //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_0266: Unknown result type (might be due to invalid IL or missing references) //IL_026b: 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_028b: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_0299: 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_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_02ba: Unknown result type (might be due to invalid IL or missing references) //IL_02da: Unknown result type (might be due to invalid IL or missing references) LastRejectReason = null; GameObject val = RootOf(piece); if ((Object)(object)val == (Object)null) { return null; } if (_cache.TryGetValue(((Object)val).GetInstanceID(), out var value)) { if (value == null) { LastRejectReason = "already judged not part of a building"; } return value; } if (!IsBuildingPiece(val)) { LastRejectReason = "'" + Utils.GetPrefabName(val) + "' is a fence, pole or similar, not part of a building"; return null; } float num = locationRadius + 8f; List list = new List(); HashSet hashSet = new HashSet { ((Object)val).GetInstanceID() }; Queue queue = new Queue(); queue.Enqueue(val); while (queue.Count > 0 && list.Count < 400) { GameObject val2 = queue.Dequeue(); list.Add(val2); int num2 = Physics.OverlapSphereNonAlloc(val2.transform.position, 3f, _buffer, Mask); for (int i = 0; i < num2; i++) { GameObject val3 = RootOf(((Component)_buffer[i]).gameObject); if ((Object)(object)val3 == (Object)null) { continue; } int instanceID = ((Object)val3).GetInstanceID(); if (!hashSet.Contains(instanceID)) { hashSet.Add(instanceID); if (IsBuildingPiece(val3) && !(Geo.FlatDistance(val3.transform.position, locationCenter) > num)) { queue.Enqueue(val3); } } } } bool flag = false; foreach (GameObject item in list) { string text = Utils.GetPrefabName(item).ToLowerInvariant(); if (text.Contains("floor") || text.Contains("wall") || text.Contains("roof") || text.Contains("door")) { flag = true; break; } } if (list.Count < 4 || !flag) { LastRejectReason = string.Format("{0} connected piece(s) with{1} a floor, wall, roof or door: not a building", list.Count, flag ? "" : "out"); foreach (GameObject item2 in list) { _cache[((Object)item2).GetInstanceID()] = null; } return null; } Vector3 val4 = Vector3.zero; foreach (GameObject item3 in list) { val4 += item3.transform.position; } Vector3 val5 = val4 / (float)list.Count; Result result = new Result { Centroid = val5, Pieces = list.Count, Id = "b" + Mathf.RoundToInt(val5.x / 2f) + "," + Mathf.RoundToInt(val5.z / 2f) }; foreach (GameObject item4 in list) { _cache[((Object)item4).GetInstanceID()] = result; } return result; } private static GameObject RootOf(GameObject go) { if ((Object)(object)go == (Object)null) { return null; } ZNetView componentInParent = go.GetComponentInParent(); if ((Object)(object)componentInParent != (Object)null) { return ((Component)componentInParent).gameObject; } Piece componentInParent2 = go.GetComponentInParent(); if ((Object)(object)componentInParent2 != (Object)null) { return ((Component)componentInParent2).gameObject; } WearNTear componentInParent3 = go.GetComponentInParent(); if (!((Object)(object)componentInParent3 != (Object)null)) { return null; } return ((Component)componentInParent3).gameObject; } private static bool IsBuildingPiece(GameObject root) { if (!Catalog.IsWorldPiece(root)) { return false; } string text = Utils.GetPrefabName(root).ToLowerInvariant(); if (!text.Contains("fence") && !text.Contains("pole") && !text.Contains("stake") && !text.Contains("gate") && !text.Contains("path")) { return !text.Contains("sign"); } return false; } } internal enum Category { Berries, Mushrooms, Herbs, Ore, Dungeon, Runestone, Trader, Camp, BossAltar, Portal, Structure } internal static class Categories { internal static readonly Category[] All = (Category[])Enum.GetValues(typeof(Category)); private static readonly Dictionary KnownIcons = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "Crypt2", "TrophySkeleton" }, { "Crypt3", "TrophySkeleton" }, { "Crypt4", "TrophySkeleton" }, { "SunkenCrypt4", "CryptKey" }, { "MountainCave02", "TrophyUlv" }, { "TrollCave02", "TrophyFrostTroll" }, { "Mistlands_DvergrTownEntrance1", "TrophySeeker" }, { "Mistlands_DvergrTownEntrance2", "TrophySeeker" }, { "Vendor_BlackForest", "Coins" }, { "Hildir_camp", "Coins" }, { "BogWitch_Camp", "Coins" }, { "GoblinCamp2", "TrophyGoblin" }, { "WoodVillage1", "TrophyDraugr" }, { "Eikthyrnir", "TrophyEikthyr" }, { "GDKing", "TrophyTheElder" }, { "Bonemass", "TrophyBonemass" }, { "Dragonqueen", "TrophyDragonQueen" }, { "GoblinKing", "TrophyGoblinKing" }, { "Mistlands_DvergrBossEntrance1", "TrophySeekerQueen" }, { "FaderLocation", "TrophyFader" } }; internal static bool UsesPrefabList(Category c) { if (c != Category.Runestone) { return c != Category.Portal; } return false; } internal static string Label(Category c) { return c switch { Category.BossAltar => "Boss Altars", Category.Dungeon => "Dungeons", Category.Runestone => "Runestones", Category.Trader => "Traders", Category.Camp => "Camps", Category.Portal => "Portals", Category.Structure => "Structures", _ => c.ToString(), }; } internal static bool DefaultEnabled(Category c) { return c != Category.Structure; } internal static string KnownIcon(string prefab) { if (string.IsNullOrEmpty(prefab) || !KnownIcons.TryGetValue(prefab, out var value)) { return null; } return value; } internal static string DefaultIcon(Category c) { return c switch { Category.Berries => "Raspberry", Category.Mushrooms => "Mushroom", Category.Herbs => "Dandelion", Category.Ore => "CopperOre", Category.Dungeon => "CryptKey", Category.Runestone => "pin:Memorial", Category.Trader => "Coins", Category.Camp => "pin:Icon0", Category.BossAltar => "pin:Boss", Category.Portal => "pin:Icon4", Category.Structure => "pin:Icon1", _ => "pin:Icon3", }; } internal static float DefaultSpacing(Category c) { switch (c) { case Category.Berries: case Category.Mushrooms: case Category.Herbs: return 1f; case Category.Ore: return 5f; case Category.Portal: return 5f; case Category.Structure: return 6f; default: return 20f; } } internal static float DefaultLookDistance(Category c) { switch (c) { case Category.Berries: case Category.Mushrooms: case Category.Herbs: return 20f; case Category.Ore: return 40f; case Category.Runestone: return 30f; case Category.Portal: return 40f; default: return 80f; } } internal static int DefaultSize(Category c) { switch (c) { case Category.Berries: case Category.Mushrooms: case Category.Herbs: return 60; case Category.Ore: return 80; default: return 100; } } internal static float DefaultLabelSpacing(Category c) { switch (c) { case Category.Berries: case Category.Mushrooms: case Category.Herbs: case Category.Ore: case Category.Dungeon: case Category.Runestone: case Category.Camp: case Category.BossAltar: case Category.Structure: return -1f; default: return 0f; } } internal static string DefaultPrefabs(Category c) { return c switch { Category.Berries => "RaspberryBush=Raspberries,BlueberryBush=Blueberries,CloudberryBush=Cloudberries", Category.Mushrooms => "Pickable_Mushroom=Mushrooms,Pickable_Mushroom_yellow=Yellow Mushrooms,Pickable_Mushroom_blue=Blue Mushrooms,Pickable_Mushroom_Magecap=Magecap,Pickable_Mushroom_JotunPuffs=Jotun Puffs,Pickable_SmokePuff=Smoke Puffs", Category.Herbs => "Pickable_Thistle=Thistle,Pickable_Dandelion=Dandelion,Pickable_Flax_Wild=Wild Flax,Pickable_Barley_Wild=Wild Barley,Pickable_SeedCarrot=Carrot Seeds,Pickable_SeedTurnip=Turnip Seeds,Pickable_SeedOnion=Onion Seeds,Pickable_Fiddlehead=Fiddlehead", Category.Ore => "rock4_copper=Copper,MineRock_Tin=Tin,silvervein=Silver,MineRock_Obsidian=Obsidian,MineRock_Meteorite=Meteorite,mudpile_beacon=Scrap Pile,mudpile2=Scrap Pile,mudpile=Scrap Pile,Pickable_Tar=Tar Pit,giant_brain=Petrified Bone,giant_helmet1=Petrified Bone,giant_helmet2=Petrified Bone,giant_ribs=Petrified Bone,giant_skull=Petrified Bone,giant_sword1=Petrified Bone,giant_sword2=Petrified Bone", Category.Dungeon => "Crypt2=Burial Chambers|TrophySkeleton,Crypt3=Burial Chambers|TrophySkeleton,Crypt4=Burial Chambers|TrophySkeleton,SunkenCrypt4=Sunken Crypt|CryptKey,MountainCave02=Frost Cave|TrophyUlv,TrollCave02=Troll Cave|TrophyFrostTroll,Mistlands_DvergrTownEntrance1=Infested Mine|TrophySeeker,Mistlands_DvergrTownEntrance2=Infested Mine|TrophySeeker", Category.Trader => "Vendor_BlackForest=Haldor|Coins,Hildir_camp=Hildir|Coins,BogWitch_Camp=Bog Witch|Coins", Category.Camp => "GoblinCamp2=Fuling Village|TrophyGoblin,WoodVillage1=Draugr Village|TrophyDraugr", Category.BossAltar => "Eikthyrnir=Eikthyr|TrophyEikthyr,GDKing=The Elder|TrophyTheElder,Bonemass=Bonemass|TrophyBonemass,Dragonqueen=Moder|TrophyDragonQueen,GoblinKing=Yagluth|TrophyGoblinKing,Mistlands_DvergrBossEntrance1=The Queen|TrophySeekerQueen,FaderLocation=Fader|TrophyFader", Category.Structure => "WoodFarm1=Abandoned Farm,WoodHouse*=Abandoned House,AbandonedLogCabin*=Log Cabin,StoneTowerRuins*=Stone Tower Ruins,StoneHouse*=Stone House,Ruin*=Ruins,SwampHut*=Swamp Hut,SwampRuin*=Swamp Ruins,SwampWell*=Swamp Well,StoneHenge*=Stonehenge,StoneTower*=Stone Tower,StoneCircle*=Stone Circle,Dolmen*=Dolmen,MountainGrave*=Mountain Grave,MountainWell*=Mountain Well,DrakeNest*=Drake Nest,Greydwarf_camp*=Greydwarf Nest,ShipSetting*=Ship Setting,Waymarker*=Waymarker,InfestedTree*=Infested Tree,Mistlands_GuardTower*=Dvergr Guard Tower,Mistlands_Excavation*=Dvergr Excavation,Mistlands_Harbour*=Dvergr Harbour,Mistlands_Lighthouse*=Dvergr Lighthouse,Mistlands_Giant*=Giant Remains,Mistlands_Swords*=Petrified Swords,Mistlands_Statue*=Dvergr Statue,Mistlands_Viaduct*=Viaduct,CharredRuins*=Charred Ruins,AshlandRuins*=Ashlands Ruins,FortressRuins*=Fortress Ruins,PlaceofMystery*=Place of Mystery", _ => "", }; } internal static string CatalogNote(Category c) { return c switch { Category.Dungeon => "Any location with an interior also counts as a dungeon even if it is not listed.", Category.Ore => "Matches MineRock5, MineRock, Destructible and Pickable objects by prefab name.", Category.Structure => "Entries ending in * match by prefix. Unlisted outdoor locations also count when 'Structures Include Unlisted' is on.", _ => "", }; } } internal sealed class Found { public string Key; public Category Cat; public string Icon; public string Name; public Vector3 Pos; public Vector3 Center; public float Radius; public long FoundAt; public Vector3 DedupeCenter { get { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (!(Radius > 0f)) { return Pos; } return Center; } } } internal static class Catalog { private sealed class Entry { public Category Cat; public string Name; public string Icon; } private static readonly Dictionary _byPrefab = new Dictionary(); private static readonly List> _byPrefix = new List>(); private static string[] _structureExclusions = new string[0]; private static bool _built; internal const float BuildingRadius = 5f; internal static void Invalidate() { _built = false; } private static void Rebuild() { _byPrefab.Clear(); _byPrefix.Clear(); Category[] all = Categories.All; string[] array; foreach (Category category in all) { if (!TgmConfig.CategoryPrefabs.TryGetValue(category, out var value)) { continue; } array = (value.Value ?? "").Split(new char[1] { ',' }); for (int j = 0; j < array.Length; j++) { string text = array[j].Trim(); if (text.Length == 0) { continue; } string text2 = text; string text3 = null; string text4 = null; int num = text.IndexOf('|'); if (num >= 0) { text4 = text.Substring(num + 1).Trim(); text = text.Substring(0, num); text2 = text; } int num2 = text.IndexOf('='); if (num2 > 0) { text2 = text.Substring(0, num2).Trim(); text3 = text.Substring(num2 + 1).Trim(); } if (text2.Length == 0) { continue; } Entry value2 = new Entry { Cat = category, Name = (string.IsNullOrEmpty(text3) ? null : text3), Icon = (string.IsNullOrEmpty(text4) ? null : text4) }; if (text2.EndsWith("*")) { string text5 = text2.Substring(0, text2.Length - 1); if (text5.Length > 0) { _byPrefix.Add(new KeyValuePair(text5, value2)); } } else { _byPrefab[text2] = value2; } } } _byPrefix.Sort((KeyValuePair a, KeyValuePair b) => b.Key.Length.CompareTo(a.Key.Length)); List list = new List(); array = (TgmConfig.StructuresExcludePrefixes.Value ?? "").Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i++) { string text6 = array[i].Trim(); if (text6.Length > 0) { list.Add(text6); } } _structureExclusions = list.ToArray(); _built = true; } private static bool Lookup(string prefab, out Entry entry) { if (!_built) { Rebuild(); } entry = null; if (string.IsNullOrEmpty(prefab)) { return false; } if (_byPrefab.TryGetValue(prefab, out entry)) { return true; } foreach (KeyValuePair item in _byPrefix) { if (prefab.StartsWith(item.Key, StringComparison.OrdinalIgnoreCase)) { entry = item.Value; return true; } } return false; } private static bool IsExcludedStructure(string prefab) { string[] structureExclusions = _structureExclusions; foreach (string value in structureExclusions) { if (prefab.StartsWith(value, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } internal static string FallbackIcon(Category cat) { ConfigEntry value; return IconRegistry.Normalize(TgmConfig.CategoryIcon.TryGetValue(cat, out value) ? value.Value : null) ?? IconRegistry.Normalize(Categories.DefaultIcon(cat)); } internal static bool TryClassify(GameObject go, out Found found) { //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_0396: Unknown result type (might be due to invalid IL or missing references) //IL_03a8: 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_03c8: Unknown result type (might be due to invalid IL or missing references) //IL_02a9: Unknown result type (might be due to invalid IL or missing references) //IL_03e9: Unknown result type (might be due to invalid IL or missing references) //IL_03fb: Unknown result type (might be due to invalid IL or missing references) //IL_034f: Unknown result type (might be due to invalid IL or missing references) //IL_0416: Unknown result type (might be due to invalid IL or missing references) //IL_0454: Unknown result type (might be due to invalid IL or missing references) //IL_0459: Unknown result type (might be due to invalid IL or missing references) //IL_0462: Unknown result type (might be due to invalid IL or missing references) //IL_0467: Unknown result type (might be due to invalid IL or missing references) found = null; if ((Object)(object)go == (Object)null) { return false; } if (!_built) { Rebuild(); } TeleportWorld componentInParent = go.GetComponentInParent(); if ((Object)(object)componentInParent != (Object)null) { string text = SafeText(componentInParent); found = Make(Category.Portal, string.IsNullOrEmpty(text) ? "Portal" : text, null, ((Component)componentInParent).transform.position, KeyOf(((Component)componentInParent).gameObject, "portal")); return true; } RuneStone componentInParent2 = go.GetComponentInParent(); if ((Object)(object)componentInParent2 != (Object)null) { found = Make(Category.Runestone, Loc(componentInParent2.GetHoverName(), "Runestone"), null, ((Component)componentInParent2).transform.position, KeyOf(((Component)componentInParent2).gameObject, "rune")); return true; } Vegvisir componentInParent3 = go.GetComponentInParent(); if ((Object)(object)componentInParent3 != (Object)null) { found = Make(Category.Runestone, Loc(componentInParent3.GetHoverName(), "Vegvisir"), null, ((Component)componentInParent3).transform.position, KeyOf(((Component)componentInParent3).gameObject, "vegvisir")); return true; } Pickable componentInParent4 = go.GetComponentInParent(); if ((Object)(object)componentInParent4 != (Object)null) { string prefabName = Utils.GetPrefabName(((Component)componentInParent4).gameObject); if (Lookup(prefabName, out var entry)) { string icon = entry.Icon ?? Categories.KnownIcon(prefabName) ?? IconRegistry.ItemKey(componentInParent4.m_itemPrefab); found = Make(entry.Cat, entry.Name ?? Loc(componentInParent4.GetHoverName(), Prettify(prefabName)), icon, ((Component)componentInParent4).transform.position, KeyOf(((Component)componentInParent4).gameObject, prefabName)); return true; } } MineRock5 componentInParent5 = go.GetComponentInParent(); if ((Object)(object)componentInParent5 != (Object)null) { string prefabName2 = Utils.GetPrefabName(((Component)componentInParent5).gameObject); if (Lookup(prefabName2, out var entry2)) { string icon2 = entry2.Icon ?? Categories.KnownIcon(prefabName2) ?? FirstDrop(componentInParent5.m_dropItems); found = Make(entry2.Cat, entry2.Name ?? Loc(componentInParent5.m_name, Prettify(prefabName2)), icon2, ((Component)componentInParent5).transform.position, KeyOf(((Component)componentInParent5).gameObject, prefabName2)); return true; } } MineRock componentInParent6 = go.GetComponentInParent(); if ((Object)(object)componentInParent6 != (Object)null) { string prefabName3 = Utils.GetPrefabName(((Component)componentInParent6).gameObject); if (Lookup(prefabName3, out var entry3)) { string icon3 = entry3.Icon ?? Categories.KnownIcon(prefabName3) ?? FirstDrop(componentInParent6.m_dropItems); found = Make(entry3.Cat, entry3.Name ?? Loc(componentInParent6.m_name, Prettify(prefabName3)), icon3, ((Component)componentInParent6).transform.position, KeyOf(((Component)componentInParent6).gameObject, prefabName3)); return true; } } Destructible componentInParent7 = go.GetComponentInParent(); if ((Object)(object)componentInParent7 != (Object)null) { string prefabName4 = Utils.GetPrefabName(((Component)componentInParent7).gameObject); if (Lookup(prefabName4, out var entry4)) { DropOnDestroyed component = ((Component)componentInParent7).GetComponent(); string icon4 = entry4.Icon ?? Categories.KnownIcon(prefabName4) ?? (((Object)(object)component != (Object)null) ? FirstDrop(component.m_dropWhenDestroyed) : null); found = Make(entry4.Cat, entry4.Name ?? Prettify(prefabName4), icon4, ((Component)componentInParent7).transform.position, KeyOf(((Component)componentInParent7).gameObject, prefabName4)); return true; } } Location componentInParent8 = go.GetComponentInParent(); if ((Object)(object)componentInParent8 != (Object)null && ClassifyLocation(Utils.GetPrefabName(((Component)componentInParent8).gameObject), componentInParent8.m_hasInterior, ((Component)componentInParent8).transform.position, componentInParent8.m_exteriorRadius, go.transform.position, out found)) { return true; } if (IsWorldPiece(go) && LocationIndex.TryFind(go.transform.position, out var best) && ClassifyLocation(best.Prefab, best.HasInterior, best.Pos, best.Radius, go.transform.position, out found)) { if (found.Cat == Category.Structure) { Buildings.Result result = Buildings.Resolve(go, best.Pos, best.Radius); if (result == null) { found = null; return false; } Found obj = found; obj.Key = obj.Key + ":" + result.Id; found.Pos = result.Centroid; found.Center = result.Centroid; found.Radius = 5f; } return true; } return false; } internal static bool TryClassifyLocation(LocationIndex.Entry entry, out Found found) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) found = null; if (entry == null) { return false; } if (!_built) { Rebuild(); } return ClassifyLocation(entry.Prefab, entry.HasInterior, entry.Pos, entry.Radius, entry.Pos, out found); } private static bool ClassifyLocation(string prefab, bool hasInterior, Vector3 center, float radius, Vector3 hitPos, out Found found) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_009c: 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) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) found = null; if (string.IsNullOrEmpty(prefab)) { return false; } string key = "loc:" + prefab + ":" + RoundKey(center); string icon = null; Category category; string name; if (Lookup(prefab, out var entry)) { category = entry.Cat; name = entry.Name ?? Prettify(prefab); icon = entry.Icon ?? Categories.KnownIcon(prefab); } else if (hasInterior) { category = Category.Dungeon; name = Prettify(prefab); } else { if (!TgmConfig.StructuresIncludeUnlisted.Value || IsExcludedStructure(prefab)) { return false; } category = Category.Structure; name = Prettify(prefab); } found = Make(category, name, icon, (category == Category.Structure) ? hitPos : center, key); found.Center = center; found.Radius = Mathf.Max(radius, 4f); return true; } internal static bool IsWorldPiece(GameObject go) { Piece componentInParent = go.GetComponentInParent(); if ((Object)(object)componentInParent != (Object)null) { return !componentInParent.IsPlacedByPlayer(); } if (!((Object)(object)go.GetComponentInParent() != (Object)null) && !((Object)(object)go.GetComponentInParent() != (Object)null)) { return (Object)(object)go.GetComponentInParent() != (Object)null; } return true; } private static Found Make(Category cat, string name, string icon, Vector3 pos, string key) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) string icon2 = IconRegistry.Normalize(icon) ?? FallbackIcon(cat); return new Found { Key = key, Cat = cat, Icon = icon2, Name = (name ?? ""), Pos = pos }; } private static string FirstDrop(DropTable table) { //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_0023: 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) if (table == null || table.m_drops == null) { return null; } foreach (DropData drop in table.m_drops) { if ((Object)(object)drop.m_item != (Object)null) { return IconRegistry.ItemKey(drop.m_item); } } return null; } private unsafe static string KeyOf(GameObject go, string prefix) { //IL_0049: 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) //IL_0029: Unknown result type (might be due to invalid IL or missing references) ZNetView componentInParent = go.GetComponentInParent(); if ((Object)(object)componentInParent != (Object)null && componentInParent.IsValid()) { ZDOID uid = componentInParent.GetZDO().m_uid; return prefix + ":" + ((object)(*(ZDOID*)(&uid))/*cast due to .constrained prefix*/).ToString(); } return prefix + ":" + RoundKey(go.transform.position); } private static string RoundKey(Vector3 p) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0026: 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) return Mathf.RoundToInt(p.x) + "," + Mathf.RoundToInt(p.y) + "," + Mathf.RoundToInt(p.z); } private static string SafeText(TeleportWorld portal) { try { return portal.GetText(); } catch { return null; } } private static string Loc(string text, string fallback) { if (string.IsNullOrEmpty(text)) { return fallback; } try { string text2 = ((Localization.instance != null) ? Localization.instance.Localize(text) : text); return string.IsNullOrEmpty(text2) ? fallback : text2; } catch { return fallback; } } internal static string Prettify(string prefab) { if (string.IsNullOrEmpty(prefab)) { return ""; } string input = Regex.Replace(prefab, "[\\d_]+", " "); input = Regex.Replace(input, "([a-z])([A-Z])", "$1 $2"); input = Regex.Replace(input, "\\s+", " ").Trim(); if (input.Length != 0) { return input; } return prefab; } } internal static class ClientPins { private static readonly Dictionary _pinById = new Dictionary(); private static readonly Dictionary _idByPin = new Dictionary(); private static readonly Color AutoTint = new Color(1f, 0.93f, 0.72f, 1f); private static bool _applyingRemote; internal static bool InTableRead; internal static bool ApplyingRemote => _applyingRemote; internal static int Count => Store.Pins.Count; internal static int SuppressionCount => Store.Suppressions.Count; internal static int TombstoneCount => Store.Tombstones.Count; internal static IEnumerable All => Store.Pins.Values; private static Minimap Map => Minimap.instance; private static MapStore Store => PersonalMap.Store; internal static void Reset() { PersonalMap.Reset(); _pinById.Clear(); _idByPin.Clear(); InTableRead = false; } private static int LocalType(SharedPin shared) { if (!string.IsNullOrEmpty(shared.Icon)) { return IconRegistry.TypeFor(shared.Icon); } if (!PinTypes.IsCustom(shared.Type)) { return shared.Type; } return 3; } internal static MergeResult ApplyMerge(MapStore incoming) { MergeResult mergeResult = Store.Merge(incoming); if (!mergeResult.Any) { return mergeResult; } foreach (Tombstone newTombstone in mergeResult.NewTombstones) { RemovePinData(newTombstone.Id); } foreach (SharedPin changedPin in mergeResult.ChangedPins) { ReplacePinData(changedPin); } PersonalMap.MarkDirty(); return mergeResult; } internal static void ClearSuppressions() { Store.Suppressions.Clear(); PersonalMap.MarkDirty(); } internal static SharedPin CreateShared(string name, Vector3 pos, string icon, string kind, bool auto, bool isChecked = false) { //IL_006c: 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) Player localPlayer = Player.m_localPlayer; string text = IconRegistry.Normalize(icon) ?? "pin:Icon3"; SharedPin sharedPin = new SharedPin { Id = SharedPin.NewId(), OwnerId = (((Object)(object)localPlayer != (Object)null) ? localPlayer.GetPlayerID() : 0), Author = (((Object)(object)localPlayer != (Object)null) ? localPlayer.GetPlayerName() : ""), Name = (name ?? ""), Pos = pos, Type = IconRegistry.TypeFor(text), Icon = text, Kind = (kind ?? ""), Checked = isChecked, Auto = auto, Created = MapStore.Now }; Store.Upsert(sharedPin); EnsurePin(sharedPin); PersonalMap.Touch(); return sharedPin; } internal static SharedPin AdoptLocalPin(PinData pinData, bool auto) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected I4, but got Unknown //IL_007c: 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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Expected I4, but got Unknown //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Expected I4, but got Unknown if (pinData == null || IsOurs(pinData) || PinTypes.IsCustom((int)pinData.m_type)) { return null; } Player localPlayer = Player.m_localPlayer; SharedPin sharedPin = new SharedPin { Id = SharedPin.NewId(), OwnerId = (((Object)(object)localPlayer != (Object)null) ? localPlayer.GetPlayerID() : 0), Author = (((Object)(object)localPlayer != (Object)null) ? localPlayer.GetPlayerName() : ""), Name = (pinData.m_name ?? ""), Pos = pinData.m_pos, Type = (int)pinData.m_type, Icon = IconRegistry.KeyForVanilla((int)pinData.m_type), Checked = pinData.m_checked, Auto = auto, Created = MapStore.Now }; pinData.m_save = true; pinData.m_ownerID = 0L; Store.Upsert(sharedPin); _pinById[sharedPin.Id] = pinData; _idByPin[pinData] = sharedPin.Id; PersonalMap.Touch(); return sharedPin; } internal static int ImportLocalPins() { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected I4, but got Unknown //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected I4, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected I4, but got Unknown //IL_006c: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Map == (Object)null) { return 0; } int num = 0; foreach (PinData item in new List(Access.Pins.Invoke(Map))) { if (item.m_save && !IsOurs(item) && PinTypes.IsPlayerPlaceable((int)item.m_type) && !PinTypes.IsCustom((int)item.m_type)) { if (HasOwnPinNear(IconRegistry.KeyForVanilla((int)item.m_type), item.m_pos, 1f)) { Map.RemovePin(item); } else if (AdoptLocalPin(item, auto: false) != null) { num++; } } } return num; } internal static int ClearLocalPins() { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected I4, but got Unknown if ((Object)(object)Map == (Object)null) { return 0; } int num = 0; foreach (PinData item in new List(Access.Pins.Invoke(Map))) { if (!IsOurs(item) && PinTypes.IsPlayerPlaceable((int)item.m_type)) { Map.RemovePin(item); num++; } } return num; } internal static bool TryCheckOff(string icon, Vector3 pos, float radius) { //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) SharedPin sharedPin = null; float num = float.MaxValue; foreach (SharedPin value2 in Store.Pins.Values) { if (!value2.Checked && IconRegistry.SameKey(value2.Icon, icon)) { float num2 = Geo.FlatDistance(value2.Pos, pos); if (num2 <= radius && num2 < num) { num = num2; sharedPin = value2; } } } if (sharedPin == null) { return false; } sharedPin.Checked = true; Store.Upsert(sharedPin); if (_pinById.TryGetValue(sharedPin.Id, out var value)) { value.m_checked = true; if ((Object)(object)Map != (Object)null) { Access.PinUpdateRequired.Invoke(Map) = true; } } PersonalMap.Touch(); return true; } internal static int EraseKindNear(Category kind, Vector3 pos, float radius) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) List list = new List(); foreach (SharedPin value in Store.Pins.Values) { if (value.Auto && KindOf(value) == kind && Geo.FlatDistance(value.Pos, pos) <= radius) { list.Add(value.Id); } } foreach (string item in list) { RemovePinData(item); Store.Delete(item, out var _); } if (list.Count > 0) { PersonalMap.Touch(); } return list.Count; } internal static Category? KindOf(SharedPin pin) { if (pin.KindCategory.HasValue) { return pin.KindCategory; } if (pin.Auto && IconRegistry.SameKey(pin.Icon, "pin:Icon1")) { return Category.Structure; } return null; } internal static int ApplyLabelRules(Category? only) { //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) int num = 0; Category[] all = Categories.All; foreach (Category category in all) { if (only.HasValue && only.Value != category) { continue; } ConfigEntry value; float num2 = (TgmConfig.LabelSpacing.TryGetValue(category, out value) ? value.Value : 0f); if (num2 == 0f) { continue; } List list = new List(); foreach (SharedPin value2 in Store.Pins.Values) { if (value2.Auto && !string.IsNullOrEmpty(value2.Name) && KindOf(value2) == category) { list.Add(value2); } } list.Sort((SharedPin a, SharedPin b) => a.Created.CompareTo(b.Created)); List list2 = new List(); foreach (SharedPin item in list) { bool flag = num2 < 0f; if (!flag) { foreach (SharedPin item2 in list2) { if (SameName(item2.Name, item.Name) && Geo.FlatDistance(item2.Pos, item.Pos) <= num2) { flag = true; break; } } } if (!flag) { list2.Add(item); continue; } item.Name = ""; Store.Upsert(item); ReplacePinData(item); num++; } } if (num > 0) { PersonalMap.Touch(); } return num; } internal static bool IsOurs(PinData pin) { if (pin != null) { return _idByPin.ContainsKey(pin); } return false; } private static bool SameName(string a, string b) { return string.Equals((a ?? "").Trim(), (b ?? "").Trim(), StringComparison.OrdinalIgnoreCase); } internal static bool HasPinNear(string icon, Vector3 pos, float radius) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Invalid comparison between Unknown and I4 //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Map == (Object)null) { return false; } int num = IconRegistry.TypeFor(icon); foreach (PinData item in Access.Pins.Invoke(Map)) { if ((int)item.m_type == num && Geo.FlatDistance(item.m_pos, pos) <= radius) { return true; } } return false; } internal static bool HasLabeledPinNear(string icon, string name, Vector3 pos, float radius) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Invalid comparison between Unknown and I4 //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) if ((Object)(object)Map == (Object)null || radius <= 0f) { return false; } int num = IconRegistry.TypeFor(icon); foreach (PinData item in Access.Pins.Invoke(Map)) { if ((int)item.m_type == num && !string.IsNullOrEmpty(item.m_name) && SameName(item.m_name, name) && Geo.FlatDistance(item.m_pos, pos) <= radius) { return true; } } return false; } internal static bool HasOwnPinNear(string icon, Vector3 pos, float radius) { //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) foreach (SharedPin value in Store.Pins.Values) { if (IconRegistry.SameKey(value.Icon, icon) && Geo.FlatDistance(value.Pos, pos) <= radius) { return true; } } return false; } internal static bool IsSuppressed(string icon, Vector3 pos, float radius) { //IL_0029: 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) foreach (Suppression suppression in Store.Suppressions) { if (IconRegistry.SameKey(suppression.Icon, icon) && Geo.FlatDistance(suppression.Pos, pos) <= radius) { return true; } } return false; } internal static void RebuildPins() { if ((Object)(object)Map == (Object)null) { return; } foreach (SharedPin value in Store.Pins.Values) { EnsurePin(value); } } private static void EnsurePin(SharedPin shared) { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Map == (Object)null) { return; } if (_pinById.TryGetValue(shared.Id, out var value)) { if (Access.Pins.Invoke(Map).Contains(value)) { value.m_checked = shared.Checked; return; } _pinById.Remove(shared.Id); _idByPin.Remove(value); } PinData val = Map.AddPin(shared.Pos, (PinType)LocalType(shared), shared.Name ?? "", true, shared.Checked, 0L, default(PlatformUserID)); if (val != null) { _pinById[shared.Id] = val; _idByPin[val] = shared.Id; } } private static void ReplacePinData(SharedPin shared) { RemovePinData(shared.Id); EnsurePin(shared); } private static void RemovePinData(string id) { if (!_pinById.TryGetValue(id, out var value)) { return; } _pinById.Remove(id); _idByPin.Remove(value); if ((Object)(object)Map == (Object)null) { return; } _applyingRemote = true; try { if (Access.Pins.Invoke(Map).Contains(value)) { Map.RemovePin(value); } } finally { _applyingRemote = false; } } internal static void OnLocalRemove(PinData pin) { if (!_applyingRemote && pin != null && _idByPin.TryGetValue(pin, out var value)) { _idByPin.Remove(pin); _pinById.Remove(value); if (Store.Delete(value, out var _)) { PersonalMap.Touch(); } } } internal static void OnPinsCleared() { _pinById.Clear(); _idByPin.Clear(); } internal static void OnPinPlaced(PinData pin) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected I4, but got Unknown if (pin != null && !((Object)(object)Map == (Object)null) && TgmConfig.SharePlacedPins.Value && Access.Pins.Invoke(Map).Contains(pin) && !IsOurs(pin) && PinTypes.IsPlayerPlaceable((int)pin.m_type)) { AdoptLocalPin(pin, auto: false); } } internal static void PushCheckedChanges() { bool flag = false; foreach (KeyValuePair item in _idByPin) { if (Store.Pins.TryGetValue(item.Value, out var value) && item.Key.m_checked != value.Checked) { value.Checked = item.Key.m_checked; Store.Upsert(value); flag = true; } } if (flag) { PersonalMap.Touch(); } } internal static void SweepImportedPlayerPins() { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected I4, but got Unknown if ((Object)(object)Map == (Object)null || TgmConfig.TableCarriesPins.Value) { return; } foreach (PinData item in new List(Access.Pins.Invoke(Map))) { if (item.m_ownerID != 0L && !IsOurs(item) && PinTypes.IsPlayerPlaceable((int)item.m_type)) { Map.RemovePin(item); } } } internal static void StylePins(Minimap map) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Invalid comparison between Unknown and I4 //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) bool flag = (Object)(object)map != (Object)null && (int)map.m_mode != 2; foreach (KeyValuePair item in _idByPin) { PinData key = item.Key; if ((Object)(object)key.m_uiElement == (Object)null || !Store.Pins.TryGetValue(item.Value, out var value)) { continue; } Category? kindCategory = value.KindCategory; bool flag2 = TgmConfig.IsIconHidden(value.Icon); if (!flag2 && kindCategory.HasValue) { ConfigEntry value3; if (TgmConfig.ShowKind.TryGetValue(kindCategory.Value, out var value2) && !value2.Value) { flag2 = true; } else if (flag && TgmConfig.ShowOnMinimap.TryGetValue(kindCategory.Value, out value3) && !value3.Value) { flag2 = true; } } SetMarkerActive(key, !flag2); if (!flag2) { float num = 1f; if (kindCategory.HasValue && TgmConfig.MarkerSize.TryGetValue(kindCategory.Value, out var value4)) { num = (float)Mathf.Clamp(value4.Value, 20, 100) / 100f; } ((Transform)key.m_uiElement).localScale = new Vector3(num, num, 1f); if ((Object)(object)key.m_iconElement != (Object)null && value.Auto) { ((Graphic)key.m_iconElement).color = AutoTint; } } } } private static void SetMarkerActive(PinData pin, bool active) { GameObject gameObject = ((Component)pin.m_uiElement).gameObject; if (gameObject.activeSelf != active) { gameObject.SetActive(active); } GameObject val = ((pin.m_NamePinData != null) ? pin.m_NamePinData.PinNameGameObject : null); if ((Object)(object)val != (Object)null && val.activeSelf != active) { val.SetActive(active); } } } [HarmonyPatch(typeof(Minimap), "RemovePin", new Type[] { typeof(PinData) })] internal static class Minimap_RemovePin_Patch { private static bool Prefix(PinData pin) { if (!ClientPins.IsOurs(pin) || ClientPins.ApplyingRemote) { return true; } if (!TgmConfig.AllowErasingMarkers.Value) { TheGreatestMapMod.Message("Erasing map markers is switched off on this server."); return false; } if (!ZInput.GetKey((KeyCode)304, true) && !ZInput.GetKey((KeyCode)303, true)) { TheGreatestMapMod.Message("Hold Shift and right-click to erase a marker."); return false; } return true; } private static void Postfix(PinData pin) { ClientPins.OnLocalRemove(pin); } } [HarmonyPatch(typeof(Minimap), "ClearPins")] internal static class Minimap_ClearPins_Patch { private static void Postfix() { ClientPins.OnPinsCleared(); } } [HarmonyPatch(typeof(Minimap), "SetMapData")] internal static class Minimap_SetMapData_Patch { private static void Postfix() { ClientPins.SweepImportedPlayerPins(); ClientPins.RebuildPins(); } } [HarmonyPatch(typeof(Minimap), "OnMapLeftClick")] internal static class Minimap_OnMapLeftClick_Patch { private static bool Gated { get { if (TgmConfig.RequireMapOutToEdit.Value) { return !PocketMap.IsOut; } return false; } } private static void Prefix(Minimap __instance, ref Dictionary __state) { __state = null; if (!Gated) { return; } __state = new Dictionary(); foreach (PinData item in Access.Pins.Invoke(__instance)) { __state[item] = item.m_checked; } } private static void Postfix(Minimap __instance, Dictionary __state) { if (__state == null) { ClientPins.PushCheckedChanges(); return; } bool flag = false; foreach (KeyValuePair item in __state) { if (item.Key.m_checked != item.Value) { item.Key.m_checked = item.Value; flag = true; } } if (flag) { Access.PinUpdateRequired.Invoke(__instance) = true; TheGreatestMapMod.Message("Take out your map to cross off a marker."); } } } [HarmonyPatch(typeof(Minimap), "OnMapDblClick")] internal static class Minimap_OnMapDblClick_Patch { private static bool Prefix(Minimap __instance) { //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_0025: Invalid comparison between Unknown and I4 //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Invalid comparison between Unknown and I4 if (!TgmConfig.RequireMapOutToEdit.Value || PocketMap.IsOut) { return true; } PinType val = Access.SelectedType.Invoke(__instance); if ((int)val == 12 || (int)val == 4) { return true; } TheGreatestMapMod.Message("Take out your map to write on it."); return false; } } [HarmonyPatch(typeof(Minimap), "RemovePinUnderPointer")] internal static class Minimap_RemovePinUnderPointer_Patch { private static bool Prefix() { if (!TgmConfig.RequireMapOutToEdit.Value || PocketMap.IsOut) { return true; } TheGreatestMapMod.Message("Take out your map to erase a marker."); return false; } } [HarmonyPatch(typeof(Minimap), "OnPinTextEntered")] internal static class Minimap_OnPinTextEntered_Patch { private static void Prefix(Minimap __instance, ref PinData __state) { __state = Access.NamePin.Invoke(__instance); } private static void Postfix(PinData __state) { ClientPins.OnPinPlaced(__state); } } [HarmonyPatch(typeof(Minimap), "GetMapData")] internal static class Minimap_GetMapData_Patch { private static void Prefix(Minimap __instance, ref List __state) { __state = new List(); foreach (PinData item in Access.Pins.Invoke(__instance)) { if (item.m_save && ClientPins.IsOurs(item)) { item.m_save = false; __state.Add(item); } } } private static void Postfix(List __state) { if (__state == null) { return; } foreach (PinData item in __state) { item.m_save = true; } } } [HarmonyPatch(typeof(Minimap), "GetSharedMapData")] internal static class Minimap_GetSharedMapData_Patch { private static void Prefix(Minimap __instance, ref List __state) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected I4, but got Unknown __state = null; if (TgmConfig.TableCarriesPins.Value) { return; } __state = new List(); foreach (PinData item in Access.Pins.Invoke(__instance)) { if (item.m_save && PinTypes.IsPlayerPlaceable((int)item.m_type)) { item.m_save = false; __state.Add(item); } } } private static void Postfix(List __state) { if (__state == null) { return; } foreach (PinData item in __state) { item.m_save = true; } } } [HarmonyPatch(typeof(Minimap), "AddSharedMapData")] internal static class Minimap_AddSharedMapData_Patch { private static void Prefix() { ClientPins.InTableRead = true; } private static void Postfix() { ClientPins.InTableRead = false; ClientPins.SweepImportedPlayerPins(); } } [HarmonyPatch(typeof(Minimap), "AddPin")] internal static class Minimap_AddPin_Patch { private static bool Prefix(PinType type, ref PinData __result) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected I4, but got Unknown if (!ClientPins.InTableRead || TgmConfig.TableCarriesPins.Value) { return true; } if (!PinTypes.IsPlayerPlaceable((int)type)) { return true; } __result = null; return false; } } [HarmonyPatch(typeof(Minimap), "UpdatePins")] internal static class Minimap_UpdatePins_Style_Patch { private static void Postfix(Minimap __instance) { ClientPins.StylePins(__instance); } } internal static class Commands { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static ConsoleEvent <>9__0_0; public static ConsoleEvent <>9__0_1; public static ConsoleEvent <>9__0_2; public static ConsoleEvent <>9__0_3; public static ConsoleEvent <>9__0_4; public static ConsoleEvent <>9__0_5; public static ConsoleEvent <>9__0_6; public static ConsoleEvent <>9__0_7; public static Converter <>9__0_12; public static ConsoleEvent <>9__0_8; public static Converter <>9__0_13; public static ConsoleEvent <>9__0_9; public static ConsoleEvent <>9__0_10; public static ConsoleEvent <>9__0_11; internal void b__0_0(ConsoleEventArgs args) { int num = 0; int num2 = 0; foreach (SharedPin item in ClientPins.All) { if (item.Auto) { num++; } else { num2++; } } args.Context.AddString($"Personal map: {ClientPins.Count} markers ({num} recorded, {num2} placed), {ClientPins.TombstoneCount} erased, {ClientPins.SuppressionCount} erased spots; sharing mode: {TgmConfig.SharingMode.Value}"); args.Context.AddString($"Found but not yet recorded: {DiscoveryLedger.PendingCount}, recorded this session: {DiscoveryLedger.RecordedCount}, map out: {PocketMap.IsOut}"); if (PinStore.IsServer) { args.Context.AddString($"Shared map (this is the server): {PinStore.Count} markers, {PinStore.TombstoneCount} erased, {PinStore.SuppressionCount} erased spots"); } } internal void b__0_1(ConsoleEventArgs args) { int num = ClientPins.ImportLocalPins(); args.Context.AddString($"Shared {num} local markers."); } internal void b__0_2(ConsoleEventArgs args) { int num = ClientPins.ClearLocalPins(); args.Context.AddString($"Deleted {num} local markers."); } internal void b__0_3(ConsoleEventArgs args) { SyncEngine.SyncWithServer(announceNothing: true); args.Context.AddString("Merging with the shared map..."); } internal void b__0_4(ConsoleEventArgs args) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { args.Context.AddString("No player."); } else { args.Context.AddString(TableSync.SyncNow(localPlayer, announceMissing: false) ? "Synced." : "No cartography table within reach."); } } internal void b__0_5(ConsoleEventArgs args) { DiscoveryLedger.Clear(); Recorder.Reset(); args.Context.AddString("Forgot pending discoveries."); } internal void b__0_6(ConsoleEventArgs args) { bool flag = args.Args.Length < 2 || args.Args[1].ToLowerInvariant() != "all"; PinNetwork.SendWipe(flag); args.Context.AddString(flag ? "Asked the server to erase recorded markers." : "Asked the server to erase all shared markers."); } internal void b__0_7(ConsoleEventArgs args) { PinNetwork.SendUnsuppress(); args.Context.AddString("Asked the server to clear erased spots."); } internal void b__0_8(ConsoleEventArgs args) { Category? only = null; if (args.Args.Length >= 2) { if (!Enum.TryParse(args.Args[1], ignoreCase: true, out var result)) { args.Context.AddString("Unknown kind '" + args.Args[1] + "'. Kinds: " + string.Join(", ", Array.ConvertAll(Categories.All, (Category c) => c.ToString()))); return; } only = result; } int num = ClientPins.ApplyLabelRules(only); args.Context.AddString($"Removed labels from {num} recorded markers."); } internal string b__0_12(Category c) { return c.ToString(); } internal void b__0_9(ConsoleEventArgs args) { //IL_00b8: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { args.Context.AddString("No player."); return; } if (args.Args.Length < 2 || !Enum.TryParse(args.Args[1], ignoreCase: true, out var result)) { args.Context.AddString("Usage: tgm_erase [radius]. Kinds: " + string.Join(", ", Array.ConvertAll(Categories.All, (Category c) => c.ToString()))); return; } float result2 = 50f; if (args.Args.Length >= 3) { float.TryParse(args.Args[2], NumberStyles.Float, CultureInfo.InvariantCulture, out result2); } int num = ClientPins.EraseKindNear(result, ((Component)localPlayer).transform.position, result2); args.Context.AddString($"Erased {num} recorded {result} markers within {result2:0} m."); } internal string b__0_13(Category c) { return c.ToString(); } internal void b__0_10(ConsoleEventArgs args) { foreach (string item in Diagnostics.Describe()) { args.Context.AddString(item); TheGreatestMapMod.Log.LogInfo((object)("[TheGreatestMap] tgm_look: " + item)); } } internal void b__0_11(ConsoleEventArgs args) { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) <>c__DisplayClass0_0 CS$<>8__locals5 = new <>c__DisplayClass0_0 { player = Player.m_localPlayer }; int result = 15; if (args.Args.Length >= 2) { int.TryParse(args.Args[1], out result); } List list = new List(ClientPins.All); if ((Object)(object)CS$<>8__locals5.player != (Object)null) { list.Sort((SharedPin a, SharedPin b) => Geo.FlatDistance(a.Pos, ((Component)CS$<>8__locals5.player).transform.position).CompareTo(Geo.FlatDistance(b.Pos, ((Component)CS$<>8__locals5.player).transform.position))); } int num = 0; foreach (SharedPin item in list) { if (num++ >= result) { break; } string text = (((Object)(object)CS$<>8__locals5.player != (Object)null) ? $"{Geo.FlatDistance(item.Pos, ((Component)CS$<>8__locals5.player).transform.position):0}m" : ""); args.Context.AddString(string.Format("{0,6} {1} {2} ({3}) by {4}", text, item.Auto ? "[rec]" : "[pin]", item.Name, item.Icon, item.Author)); } if (list.Count == 0) { args.Context.AddString("No shared markers."); } } } [CompilerGenerated] private sealed class <>c__DisplayClass0_0 { public Player player; internal int b__14(SharedPin a, SharedPin b) { //IL_0001: 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_001f: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) return Geo.FlatDistance(a.Pos, ((Component)player).transform.position).CompareTo(Geo.FlatDistance(b.Pos, ((Component)player).transform.position)); } } internal static void Register() { //IL_0033: 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_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_00a5: 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) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Expected O, but got Unknown //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Expected O, but got Unknown //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Expected O, but got Unknown //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Expected O, but got Unknown //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Expected O, but got Unknown //IL_01fb: 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_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Expected O, but got Unknown //IL_026d: Unknown result type (might be due to invalid IL or missing references) //IL_0258: Unknown result type (might be due to invalid IL or missing references) //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_0263: Expected O, but got Unknown //IL_02a6: 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_0296: Unknown result type (might be due to invalid IL or missing references) //IL_029c: Expected O, but got Unknown object obj = <>c.<>9__0_0; if (obj == null) { ConsoleEvent val = delegate(ConsoleEventArgs args) { int num = 0; int num2 = 0; foreach (SharedPin item in ClientPins.All) { if (item.Auto) { num++; } else { num2++; } } args.Context.AddString($"Personal map: {ClientPins.Count} markers ({num} recorded, {num2} placed), {ClientPins.TombstoneCount} erased, {ClientPins.SuppressionCount} erased spots; sharing mode: {TgmConfig.SharingMode.Value}"); args.Context.AddString($"Found but not yet recorded: {DiscoveryLedger.PendingCount}, recorded this session: {DiscoveryLedger.RecordedCount}, map out: {PocketMap.IsOut}"); if (PinStore.IsServer) { args.Context.AddString($"Shared map (this is the server): {PinStore.Count} markers, {PinStore.TombstoneCount} erased, {PinStore.SuppressionCount} erased spots"); } }; <>c.<>9__0_0 = val; obj = (object)val; } new ConsoleCommand("tgm_status", "The Greatest Map: shared marker counts and local state", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj2 = <>c.<>9__0_1; if (obj2 == null) { ConsoleEvent val2 = delegate(ConsoleEventArgs args) { int num = ClientPins.ImportLocalPins(); args.Context.AddString($"Shared {num} local markers."); }; <>c.<>9__0_1 = val2; obj2 = (object)val2; } new ConsoleCommand("tgm_import", "Share your local map markers (the five standard icons) with everyone", (ConsoleEvent)obj2, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj3 = <>c.<>9__0_2; if (obj3 == null) { ConsoleEvent val3 = delegate(ConsoleEventArgs args) { int num = ClientPins.ClearLocalPins(); args.Context.AddString($"Deleted {num} local markers."); }; <>c.<>9__0_2 = val3; obj3 = (object)val3; } new ConsoleCommand("tgm_clearlocal", "Delete your local (non-shared) player-placed markers, including stale ones imported from tables", (ConsoleEvent)obj3, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj4 = <>c.<>9__0_3; if (obj4 == null) { ConsoleEvent val4 = delegate(ConsoleEventArgs args) { SyncEngine.SyncWithServer(announceNothing: true); args.Context.AddString("Merging with the shared map..."); }; <>c.<>9__0_3 = val4; obj4 = (object)val4; } new ConsoleCommand("tgm_resync", "Merge your personal map with the shared map now, without a cartography table", (ConsoleEvent)obj4, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj5 = <>c.<>9__0_4; if (obj5 == null) { ConsoleEvent val5 = delegate(ConsoleEventArgs args) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { args.Context.AddString("No player."); } else { args.Context.AddString(TableSync.SyncNow(localPlayer, announceMissing: false) ? "Synced." : "No cartography table within reach."); } }; <>c.<>9__0_4 = val5; obj5 = (object)val5; } new ConsoleCommand("tgm_sync", "Read and write the nearest cartography table now", (ConsoleEvent)obj5, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj6 = <>c.<>9__0_5; if (obj6 == null) { ConsoleEvent val6 = delegate(ConsoleEventArgs args) { DiscoveryLedger.Clear(); Recorder.Reset(); args.Context.AddString("Forgot pending discoveries."); }; <>c.<>9__0_5 = val6; obj6 = (object)val6; } new ConsoleCommand("tgm_forget", "Forget everything found but not yet recorded (nothing is deleted from the map)", (ConsoleEvent)obj6, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj7 = <>c.<>9__0_6; if (obj7 == null) { ConsoleEvent val7 = delegate(ConsoleEventArgs args) { bool flag = args.Args.Length < 2 || args.Args[1].ToLowerInvariant() != "all"; PinNetwork.SendWipe(flag); args.Context.AddString(flag ? "Asked the server to erase recorded markers." : "Asked the server to erase all shared markers."); }; <>c.<>9__0_6 = val7; obj7 = (object)val7; } new ConsoleCommand("tgm_wipe", "Admin: erase shared markers for everyone. tgm_wipe auto (default) erases recorded ones only; tgm_wipe all erases every shared marker", (ConsoleEvent)obj7, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj8 = <>c.<>9__0_7; if (obj8 == null) { ConsoleEvent val8 = delegate(ConsoleEventArgs args) { PinNetwork.SendUnsuppress(); args.Context.AddString("Asked the server to clear erased spots."); }; <>c.<>9__0_7 = val8; obj8 = (object)val8; } new ConsoleCommand("tgm_unsuppress", "Admin: allow recording again at spots where recorded markers were erased", (ConsoleEvent)obj8, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj9 = <>c.<>9__0_8; if (obj9 == null) { ConsoleEvent val9 = delegate(ConsoleEventArgs args) { Category? only = null; if (args.Args.Length >= 2) { if (!Enum.TryParse(args.Args[1], ignoreCase: true, out var result)) { args.Context.AddString("Unknown kind '" + args.Args[1] + "'. Kinds: " + string.Join(", ", Array.ConvertAll(Categories.All, (Category c) => c.ToString()))); return; } only = result; } int num = ClientPins.ApplyLabelRules(only); args.Context.AddString($"Removed labels from {num} recorded markers."); }; <>c.<>9__0_8 = val9; obj9 = (object)val9; } new ConsoleCommand("tgm_relabel", "Apply the label rules to existing recorded markers for everyone (tgm_relabel Structures for one kind); labels are only removed, never added", (ConsoleEvent)obj9, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj10 = <>c.<>9__0_9; if (obj10 == null) { ConsoleEvent val10 = delegate(ConsoleEventArgs args) { //IL_00b8: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; Category result; if ((Object)(object)localPlayer == (Object)null) { args.Context.AddString("No player."); } else if (args.Args.Length < 2 || !Enum.TryParse(args.Args[1], ignoreCase: true, out result)) { args.Context.AddString("Usage: tgm_erase [radius]. Kinds: " + string.Join(", ", Array.ConvertAll(Categories.All, (Category c) => c.ToString()))); } else { float result2 = 50f; if (args.Args.Length >= 3) { float.TryParse(args.Args[2], NumberStyles.Float, CultureInfo.InvariantCulture, out result2); } int num = ClientPins.EraseKindNear(result, ((Component)localPlayer).transform.position, result2); args.Context.AddString($"Erased {num} recorded {result} markers within {result2:0} m."); } }; <>c.<>9__0_9 = val10; obj10 = (object)val10; } new ConsoleCommand("tgm_erase", "Erase recorded markers of one kind near you: tgm_erase Structures [radius, default 50]. Works even when erasing by click is off; carries to everyone at the next merge", (ConsoleEvent)obj10, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj11 = <>c.<>9__0_10; if (obj11 == null) { ConsoleEvent val11 = delegate(ConsoleEventArgs args) { foreach (string item2 in Diagnostics.Describe()) { args.Context.AddString(item2); TheGreatestMapMod.Log.LogInfo((object)("[TheGreatestMap] tgm_look: " + item2)); } }; <>c.<>9__0_10 = val11; obj11 = (object)val11; } new ConsoleCommand("tgm_look", "Report what the crosshair hits and every reason it would or would not be recorded (also written to the log)", (ConsoleEvent)obj11, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj12 = <>c.<>9__0_11; if (obj12 == null) { ConsoleEvent val12 = delegate(ConsoleEventArgs args) { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) Player player = Player.m_localPlayer; int result = 15; if (args.Args.Length >= 2) { int.TryParse(args.Args[1], out result); } List list = new List(ClientPins.All); if ((Object)(object)player != (Object)null) { list.Sort((SharedPin a, SharedPin b) => Geo.FlatDistance(a.Pos, ((Component)player).transform.position).CompareTo(Geo.FlatDistance(b.Pos, ((Component)player).transform.position))); } int num = 0; foreach (SharedPin item3 in list) { if (num++ >= result) { break; } string text = (((Object)(object)player != (Object)null) ? $"{Geo.FlatDistance(item3.Pos, ((Component)player).transform.position):0}m" : ""); args.Context.AddString(string.Format("{0,6} {1} {2} ({3}) by {4}", text, item3.Auto ? "[rec]" : "[pin]", item3.Name, item3.Icon, item3.Author)); } if (list.Count == 0) { args.Context.AddString("No shared markers."); } }; <>c.<>9__0_11 = val12; obj12 = (object)val12; } new ConsoleCommand("tgm_list", "List shared markers, nearest first (tgm_list 40 for more)", (ConsoleEvent)obj12, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); } } internal static class Diagnostics { private static readonly RaycastHit[] _hits = (RaycastHit[])(object)new RaycastHit[256]; internal static List Describe() { //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_02f1: Unknown result type (might be due to invalid IL or missing references) //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Unknown result type (might be due to invalid IL or missing references) //IL_040e: Unknown result type (might be due to invalid IL or missing references) //IL_0452: Unknown result type (might be due to invalid IL or missing references) //IL_0551: Unknown result type (might be due to invalid IL or missing references) //IL_056b: Unknown result type (might be due to invalid IL or missing references) List list = new List(); Player localPlayer = Player.m_localPlayer; GameCamera instance = GameCamera.instance; if ((Object)(object)localPlayer == (Object)null || (Object)(object)instance == (Object)null) { list.Add("No player or camera."); return list; } list.Add($"map out: {PocketMap.IsOut}, recording enabled: {TgmConfig.RecordEnabled.Value}, interior: {((Character)localPlayer).InInterior()}, indexed locations: {LocationIndex.Count}"); GameObject hoverObject = ((Humanoid)localPlayer).GetHoverObject(); list.Add("hover object: " + (((Object)(object)hoverObject != (Object)null) ? ((Object)hoverObject).name : "none")); float num = TgmConfig.MaxLookDistance(); int num2 = Physics.RaycastNonAlloc(((Component)instance).transform.position, ((Component)instance).transform.forward, _hits, num, Access.InteractMask.Invoke(localPlayer)); RaycastHit val = default(RaycastHit); float num3 = float.MaxValue; bool flag = false; for (int i = 0; i < num2; i++) { RaycastHit val2 = _hits[i]; if (!((Object)(object)((RaycastHit)(ref val2)).collider == (Object)null)) { Rigidbody attachedRigidbody = ((RaycastHit)(ref val2)).collider.attachedRigidbody; if ((!((Object)(object)attachedRigidbody != (Object)null) || !((Object)(object)((Component)attachedRigidbody).gameObject == (Object)(object)((Component)localPlayer).gameObject)) && !((Object)(object)((Component)((RaycastHit)(ref val2)).collider).GetComponentInParent() == (Object)(object)localPlayer) && ((RaycastHit)(ref val2)).distance < num3) { num3 = ((RaycastHit)(ref val2)).distance; val = val2; flag = true; } } } list.Add($"ray: {num2} hits within {num:0} m" + ((num2 >= _hits.Length) ? " (buffer full)" : "")); if (!flag) { list.Add("nearest hit: nothing"); return list; } GameObject gameObject = ((Component)((RaycastHit)(ref val)).collider).gameObject; list.Add($"nearest hit: '{((Object)gameObject).name}' at {num3:0.0} m, layer {LayerMask.LayerToName(gameObject.layer)}, prefab '{Utils.GetPrefabName(gameObject)}'"); Piece componentInParent = gameObject.GetComponentInParent(); WearNTear componentInParent2 = gameObject.GetComponentInParent(); Location componentInParent3 = gameObject.GetComponentInParent(); list.Add(string.Format(" piece: {0}, wearntear: {1}, container: {2}, door: {3}, location parent: {4}", (!((Object)(object)componentInParent != (Object)null)) ? "none" : (componentInParent.IsPlacedByPlayer() ? "player-built" : "world"), (Object)(object)componentInParent2 != (Object)null, (Object)(object)gameObject.GetComponentInParent() != (Object)null, (Object)(object)gameObject.GetComponentInParent() != (Object)null, ((Object)(object)componentInParent3 != (Object)null) ? Utils.GetPrefabName(((Component)componentInParent3).gameObject) : "none")); list.Add($" world piece: {Catalog.IsWorldPiece(gameObject)}"); foreach (LocationIndex.Entry item in LocationIndex.Nearest(((RaycastHit)(ref val)).point, 3)) { float num4 = Geo.FlatDistance(((RaycastHit)(ref val)).point, item.Pos); list.Add(string.Format(" indexed location '{0}' {1:0.0} m from hit, radius {2:0.0}{3}", item.Prefab, num4, item.Radius, (num4 <= item.Radius) ? " (contains hit)" : "")); } if (LocationIndex.Count == 0) { list.Add(" no indexed locations at all (LocationProxy hook not firing?)"); } if (!Catalog.TryClassify(gameObject, out var found)) { list.Add("classified: no (nothing recordable)" + ((Buildings.LastRejectReason != null) ? (": " + Buildings.LastRejectReason) : "")); return list; } list.Add($"classified: {found.Cat} '{found.Name}' icon {found.Icon} at {found.Pos}"); Buildings.Result result = ((found.Cat == Category.Structure) ? Buildings.Peek(gameObject) : null); if (result != null) { list.Add($" building: {result.Pieces} connected pieces, centre {result.Centroid}, id {result.Id}"); } float num5 = TgmConfig.LookDistanceFor(found.Cat); list.Add(string.Format(" look distance for {0}: {1:0} m -> {2}", found.Cat, num5, (num3 <= num5) ? "in range" : "TOO FAR to count as seen")); list.Add($" kind enabled: {TgmConfig.CategoryEnabled.TryGetValue(found.Cat, out var value) && value.Value}"); list.Add($" pending (found, not yet recorded): {DiscoveryLedger.IsPending(found.Key)}, recorded this session: {DiscoveryLedger.IsRecorded(found.Key)}"); ConfigEntry value2; float num6 = (TgmConfig.MarkerSpacing.TryGetValue(found.Cat, out value2) ? value2.Value : 1f); list.Add($" marker with this icon within {num6:0.#} m: {ClientPins.HasPinNear(found.Icon, found.Pos, num6)}, erased spot here: {ClientPins.IsSuppressed(found.Icon, found.Pos, num6)}"); return list; } } internal static class DiscoveryLedger { private const int SaveVersion = 2; private static readonly Dictionary _pending = new Dictionary(); private static readonly HashSet _recorded = new HashSet(); private static readonly RaycastHit[] _hits = (RaycastHit[])(object)new RaycastHit[256]; private static float _nextScan; private static string _lookKey; private static float _lookSince; internal static int PendingCount => _pending.Count; internal static int RecordedCount => _recorded.Count; internal static bool IsPending(string key) { if (key != null) { return _pending.ContainsKey(key); } return false; } internal static bool IsRecorded(string key) { if (key != null) { return _recorded.Contains(key); } return false; } internal static void Update() { //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_008f: 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_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) if (!TgmConfig.RecordEnabled.Value) { return; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || Time.time < _nextScan) { return; } _nextScan = Time.time + 0.2f; Prune(); if (((Character)localPlayer).InInterior()) { _lookKey = null; return; } GameObject hoverObject = ((Humanoid)localPlayer).GetHoverObject(); if ((Object)(object)hoverObject != (Object)null && Catalog.TryClassify(hoverObject, out var found)) { MarkFound(found); } GameCamera instance = GameCamera.instance; if ((Object)(object)instance == (Object)null) { return; } int num = Physics.RaycastNonAlloc(((Component)instance).transform.position, ((Component)instance).transform.forward, _hits, TgmConfig.MaxLookDistance(), Access.InteractMask.Invoke(localPlayer)); RaycastHit val = default(RaycastHit); float num2 = float.MaxValue; bool flag = false; for (int i = 0; i < num; i++) { RaycastHit val2 = _hits[i]; if (!((Object)(object)((RaycastHit)(ref val2)).collider == (Object)null) && !IsPlayerCollider(((RaycastHit)(ref val2)).collider, localPlayer) && ((RaycastHit)(ref val2)).distance < num2) { num2 = ((RaycastHit)(ref val2)).distance; val = val2; flag = true; } } if (!flag || !Catalog.TryClassify(((Component)((RaycastHit)(ref val)).collider).gameObject, out var found2) || num2 > TgmConfig.LookDistanceFor(found2.Cat)) { _lookKey = null; return; } if (found2.Key != _lookKey) { _lookKey = found2.Key; _lookSince = Time.time; } if (Time.time - _lookSince >= TgmConfig.LookDwell.Value) { MarkFound(found2); } } private static bool IsPlayerCollider(Collider collider, Player player) { Rigidbody attachedRigidbody = collider.attachedRigidbody; if ((Object)(object)attachedRigidbody != (Object)null && (Object)(object)((Component)attachedRigidbody).gameObject == (Object)(object)((Component)player).gameObject) { return true; } return (Object)(object)((Component)collider).GetComponentInParent() == (Object)(object)player; } internal static void NoteInteraction(GameObject go) { if (TgmConfig.RecordEnabled.Value) { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null) && !((Object)(object)go == (Object)null) && !((Character)localPlayer).InInterior() && Catalog.TryClassify(go, out var found)) { MarkFound(found); } } } internal static void MarkFound(Found found) { if (found != null && !string.IsNullOrEmpty(found.Key) && !_recorded.Contains(found.Key)) { if (_pending.TryGetValue(found.Key, out var value)) { value.FoundAt = DateTime.UtcNow.Ticks; return; } found.FoundAt = DateTime.UtcNow.Ticks; _pending[found.Key] = found; } } internal static List Pending() { Prune(); return new List(_pending.Values); } private static void Prune() { float value = TgmConfig.FoundMemoryMinutes.Value; if (value <= 0f || _pending.Count == 0) { return; } long num = DateTime.UtcNow.Ticks - (long)(value * 600000000f); List list = new List(); foreach (KeyValuePair item in _pending) { if (item.Value.FoundAt < num) { list.Add(item.Key); } } foreach (string item2 in list) { _pending.Remove(item2); } } internal static void MarkRecorded(string key) { _pending.Remove(key); _recorded.Add(key); } internal static void Clear() { _pending.Clear(); _recorded.Clear(); _lookKey = null; } internal static bool IsLocalAttacker(HitData hit) { if (hit != null && (Object)(object)Player.m_localPlayer != (Object)null) { return (Object)(object)hit.GetAttacker() == (Object)(object)Player.m_localPlayer; } return false; } internal static string Serialize() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) Prune(); ZPackage val = new ZPackage(); val.Write(2); val.Write(_pending.Count); foreach (Found value in _pending.Values) { val.Write(value.Key ?? ""); val.Write((int)value.Cat); val.Write(value.Icon ?? ""); val.Write(value.Name ?? ""); val.Write(value.Pos); val.Write(value.FoundAt); val.Write(value.Center); val.Write(value.Radius); } return val.GetBase64(); } internal static void Deserialize(string data) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: 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_008e: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(data)) { return; } try { ZPackage val = new ZPackage(data); int num = val.ReadInt(); if (num < 1 || num > 2) { return; } int num2 = val.ReadInt(); for (int i = 0; i < num2; i++) { Found found = new Found { Key = val.ReadString(), Cat = (Category)val.ReadInt(), Icon = val.ReadString(), Name = val.ReadString(), Pos = val.ReadVector3(), FoundAt = val.ReadLong() }; if (num >= 2) { found.Center = val.ReadVector3(); found.Radius = val.ReadSingle(); } else { found.Center = found.Pos; } if (!string.IsNullOrEmpty(found.Key) && !_pending.ContainsKey(found.Key)) { _pending[found.Key] = found; } } Prune(); } catch (Exception ex) { TheGreatestMapMod.Log.LogWarning((object)("[TheGreatestMap] Could not read saved finds: " + ex.Message)); } } } [HarmonyPatch(typeof(Player), "Save")] internal static class Player_Save_Finds_Patch { private static void Prefix(Player __instance) { if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && __instance.m_customData != null) { __instance.m_customData["TheGreatestMap.Found"] = DiscoveryLedger.Serialize(); } } } [HarmonyPatch(typeof(Player), "Load")] internal static class Player_Load_Finds_Patch { private static void Postfix(Player __instance) { if (__instance.m_customData != null && __instance.m_customData.TryGetValue("TheGreatestMap.Found", out var value)) { DiscoveryLedger.Deserialize(value); } } } internal static class DiscoveryLedgerKeys { internal const string CustomData = "TheGreatestMap.Found"; } [HarmonyPatch(typeof(Pickable), "Interact")] internal static class Pickable_Interact_Patch { private static void Prefix(Pickable __instance, Humanoid character) { if ((Object)(object)character != (Object)null && (Object)(object)character == (Object)(object)Player.m_localPlayer) { DiscoveryLedger.NoteInteraction(((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(MineRock5), "Damage")] internal static class MineRock5_Damage_Patch { private static void Prefix(MineRock5 __instance, HitData hit) { if (DiscoveryLedger.IsLocalAttacker(hit)) { DiscoveryLedger.NoteInteraction(((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(MineRock), "Damage")] internal static class MineRock_Damage_Patch { private static void Prefix(MineRock __instance, HitData hit) { if (DiscoveryLedger.IsLocalAttacker(hit)) { DiscoveryLedger.NoteInteraction(((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(Destructible), "Damage")] internal static class Destructible_Damage_Patch { private static void Prefix(Destructible __instance, HitData hit) { if (DiscoveryLedger.IsLocalAttacker(hit)) { DiscoveryLedger.NoteInteraction(((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(RuneStone), "Interact")] internal static class RuneStone_Interact_Patch { private static void Prefix(RuneStone __instance, Humanoid character) { if ((Object)(object)character != (Object)null && (Object)(object)character == (Object)(object)Player.m_localPlayer) { DiscoveryLedger.NoteInteraction(((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(Vegvisir), "Interact")] internal static class Vegvisir_Interact_Patch { private static void Prefix(Vegvisir __instance, Humanoid character) { if ((Object)(object)character != (Object)null && (Object)(object)character == (Object)(object)Player.m_localPlayer) { DiscoveryLedger.NoteInteraction(((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(Teleport), "Interact")] internal static class Teleport_Interact_Patch { private static void Prefix(Teleport __instance, Humanoid character) { if ((Object)(object)character != (Object)null && (Object)(object)character == (Object)(object)Player.m_localPlayer) { DiscoveryLedger.NoteInteraction(((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(TeleportWorld), "Interact")] internal static class TeleportWorld_Interact_Patch { private static void Prefix(TeleportWorld __instance, Humanoid human) { if ((Object)(object)human != (Object)null && (Object)(object)human == (Object)(object)Player.m_localPlayer) { DiscoveryLedger.NoteInteraction(((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(Container), "Interact")] internal static class Container_Interact_Patch { private static void Prefix(Container __instance, Humanoid character) { if (!((Object)(object)character == (Object)null) && !((Object)(object)character != (Object)(object)Player.m_localPlayer)) { DiscoveryLedger.NoteInteraction(((Component)__instance).gameObject); Searched.OnSearched(((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(Beehive), "Interact")] internal static class Beehive_Interact_Patch { private static void Prefix(Beehive __instance, Humanoid character) { if (!((Object)(object)character == (Object)null) && !((Object)(object)character != (Object)(object)Player.m_localPlayer)) { DiscoveryLedger.NoteInteraction(((Component)__instance).gameObject); Searched.OnSearched(((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(Door), "Interact")] internal static class Door_Interact_Patch { private static void Prefix(Door __instance, Humanoid character) { if ((Object)(object)character != (Object)null && (Object)(object)character == (Object)(object)Player.m_localPlayer) { DiscoveryLedger.NoteInteraction(((Component)__instance).gameObject); } } } internal static class IconRegistry { internal const int Base = 100; internal const string FallbackKey = "pin:Icon3"; private static readonly Dictionary _typeByKey = new Dictionary(); private static readonly List _keys = new List(); internal static int MaxType => 100 + _keys.Count - 1; internal static string Normalize(string key) { if (string.IsNullOrEmpty(key)) { return null; } key = key.Trim(); if (key.Length == 0) { return null; } if (key.StartsWith("item:", StringComparison.OrdinalIgnoreCase)) { return "item:" + key.Substring(5).Trim(); } if (key.StartsWith("pin:", StringComparison.OrdinalIgnoreCase)) { return "pin:" + key.Substring(4).Trim(); } return "item:" + key; } internal static bool SameKey(string a, string b) { return string.Equals(Normalize(a), Normalize(b), StringComparison.OrdinalIgnoreCase); } private static bool TryVanilla(string normalized, out PinType type) { type = (PinType)3; if (normalized != null && normalized.StartsWith("pin:")) { return Enum.TryParse(normalized.Substring(4), ignoreCase: true, out type); } return false; } internal static int TypeFor(string iconKey) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected I4, but got Unknown string text = Normalize(iconKey); if (text == null) { return 3; } if (text.StartsWith("pin:")) { if (!TryVanilla(text, out var type)) { return 3; } return (int)type; } if (_typeByKey.TryGetValue(text, out var value)) { return value; } value = 100 + _keys.Count; _keys.Add(text); _typeByKey[text] = value; Register(Minimap.instance, text, value); return value; } internal static string KeyForVanilla(int type) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return "pin:" + ((object)(PinType)type/*cast due to .constrained prefix*/).ToString(); } internal static string ItemKey(GameObject itemPrefab) { if (!((Object)(object)itemPrefab == (Object)null)) { return "item:" + Utils.GetPrefabName(itemPrefab); } return null; } internal static string LegacyKey(int type) { switch (type) { case 100: return "item:Raspberry"; case 101: return "item:Mushroom"; case 102: return "item:Thistle"; case 103: return "item:CopperOre"; case 104: return "item:CryptKey"; case 105: return "pin:Memorial"; case 106: return "item:Coins"; case 107: return "pin:Icon0"; default: if (type >= 100) { return "pin:Icon3"; } return KeyForVanilla(type); } } internal static void OnMinimapStart(Minimap map) { for (int i = 0; i < _keys.Count; i++) { Register(map, _keys[i], 100 + i); } EnsureArrays(map); } private static void Register(Minimap map, string key, int type) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_007c: 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) if (!((Object)(object)map == (Object)null)) { Sprite val = Resolve(map, key); if ((Object)(object)val == (Object)null) { TheGreatestMapMod.Log.LogWarning((object)("[TheGreatestMap] No icon for '" + key + "'; using the plain dot.")); val = Resolve(map, "pin:Icon3"); } map.m_icons.RemoveAll((SpriteData x) => (int)x.m_name == type); map.m_icons.Add(new SpriteData { m_name = (PinType)type, m_icon = val }); EnsureArrays(map); } } internal static Sprite Resolve(Minimap map, string key) { //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) //IL_0045: 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_004b: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) key = Normalize(key); if (key == null || (Object)(object)map == (Object)null) { return null; } if (key.StartsWith("pin:")) { if (!TryVanilla(key, out var type)) { return null; } foreach (SpriteData icon in map.m_icons) { if (icon.m_name == type) { return icon.m_icon; } } return null; } try { if ((Object)(object)ObjectDB.instance == (Object)null) { return null; } GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(key.Substring(5)); ItemDrop val = (((Object)(object)itemPrefab != (Object)null) ? itemPrefab.GetComponent() : null); return ((Object)(object)val != (Object)null && val.m_itemData != null) ? val.m_itemData.GetIcon() : null; } catch (Exception ex) { TheGreatestMapMod.Log.LogWarning((object)("[TheGreatestMap] Could not load icon '" + key + "': " + ex.Message)); return null; } } internal static void EnsureArrays(Minimap map) { if ((Object)(object)map == (Object)null) { return; } int num = Math.Max(MaxType + 1, Enum.GetValues(typeof(PinType)).Length); bool[] array = Access.VisibleIconTypes.Invoke(map); if (array == null || array.Length < num) { bool[] array2 = new bool[num]; for (int i = 0; i < array2.Length; i++) { array2[i] = array == null || i >= array.Length || array[i]; } Access.VisibleIconTypes.Invoke(map) = array2; } } } internal static class Keys { internal static bool IsDown(KeyboardShortcut shortcut) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000d: 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) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey == 0) { return false; } if (!ZInput.GetKeyDown(((KeyboardShortcut)(ref shortcut)).MainKey, true)) { return false; } foreach (KeyCode modifier in ((KeyboardShortcut)(ref shortcut)).Modifiers) { if (!ZInput.GetKey(modifier, true)) { return false; } } return true; } internal static bool CanTakeInput() { if (Console.IsVisible() || TextInput.IsVisible() || Menu.IsActive() || InventoryGui.IsVisible() || StoreGui.IsVisible()) { return false; } if ((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus()) { return false; } if ((Object)(object)Minimap.instance != (Object)null && Minimap.InTextInput()) { return false; } return true; } } internal static class LocationIndex { internal sealed class Entry { public LocationProxy Proxy; public string Prefab; public Vector3 Pos; public float Radius; public bool HasInterior; } private static readonly List _entries = new List(); internal static int Count => _entries.Count; internal static void Register(LocationProxy proxy) { //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) if ((Object)(object)proxy == (Object)null) { return; } GameObject val = Access.ProxyInstance.Invoke(proxy); if ((Object)(object)val == (Object)null) { return; } Location component = val.GetComponent(); for (int i = 0; i < _entries.Count; i++) { if ((Object)(object)_entries[i].Proxy == (Object)(object)proxy) { _entries.RemoveAt(i); break; } } _entries.Add(new Entry { Proxy = proxy, Prefab = Utils.GetPrefabName(val), Pos = ((Component)proxy).transform.position, Radius = (((Object)(object)component != (Object)null) ? Mathf.Max(component.m_exteriorRadius, 4f) : 20f), HasInterior = ((Object)(object)component != (Object)null && component.m_hasInterior) }); } internal static bool TryFind(Vector3 point, out Entry best) { //IL_003f: 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) best = null; float num = float.MaxValue; for (int num2 = _entries.Count - 1; num2 >= 0; num2--) { Entry entry = _entries[num2]; if ((Object)(object)entry.Proxy == (Object)null) { _entries.RemoveAt(num2); } else { float num3 = Geo.FlatDistance(point, entry.Pos); if (!(num3 > entry.Radius)) { float num4 = num3 / entry.Radius; if (num4 < num) { num = num4; best = entry; } } } } return best != null; } internal static List Nearest(Vector3 point, int count) { //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) List list = new List(); for (int num = _entries.Count - 1; num >= 0; num--) { if ((Object)(object)_entries[num].Proxy == (Object)null) { _entries.RemoveAt(num); } else { list.Add(_entries[num]); } } list.Sort((Entry a, Entry b) => Geo.FlatDistance(point, a.Pos).CompareTo(Geo.FlatDistance(point, b.Pos))); if (list.Count > count) { list.RemoveRange(count, list.Count - count); } return list; } internal static void Clear() { _entries.Clear(); } } [HarmonyPatch(typeof(LocationProxy), "SpawnLocation")] internal static class LocationProxy_SpawnLocation_Patch { private static void Postfix(LocationProxy __instance, bool __result) { if (__result) { LocationIndex.Register(__instance); } } } internal sealed class Tombstone { public string Id = ""; public long DeletedAt; } internal sealed class MergeResult { public int Added; public int Updated; public int Deleted; public int Suppressed; public readonly List ChangedPins = new List(); public readonly List NewTombstones = new List(); public readonly List NewSuppressions = new List(); public bool Any => Added + Updated + Deleted + Suppressed > 0; public MapStore ToDelta() { MapStore mapStore = new MapStore(); foreach (SharedPin changedPin in ChangedPins) { mapStore.Pins[changedPin.Id] = changedPin.Clone(); } foreach (Tombstone newTombstone in NewTombstones) { mapStore.Tombstones[newTombstone.Id] = newTombstone.DeletedAt; } mapStore.Suppressions.AddRange(NewSuppressions); return mapStore; } public override string ToString() { List list = new List(); if (Added > 0) { list.Add($"+{Added}"); } if (Updated > 0) { list.Add($"{Updated} updated"); } if (Deleted > 0) { list.Add($"{Deleted} erased"); } if (list.Count <= 0) { return "nothing new"; } return string.Join(", ", list); } } internal sealed class MapStore { public const int FormatVersion = 4; public readonly Dictionary Pins = new Dictionary(); public readonly Dictionary Tombstones = new Dictionary(); public readonly List Suppressions = new List(); public static long Now => DateTime.UtcNow.Ticks; public void Upsert(SharedPin pin) { pin.Modified = Now; Pins[pin.Id] = pin; Tombstones.Remove(pin.Id); } public bool Delete(string id, out SharedPin removed) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) removed = null; if (string.IsNullOrEmpty(id) || !Pins.TryGetValue(id, out removed)) { return false; } Pins.Remove(id); Tombstones[id] = Now; if (removed.Auto) { AddSuppression(new Suppression { Type = removed.Type, Icon = removed.Icon, Pos = removed.Pos, Name = removed.Name }); } return true; } public bool AddSuppression(Suppression s) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) foreach (Suppression suppression in Suppressions) { if (IconRegistry.SameKey(suppression.Icon, s.Icon) && Geo.FlatDistance(suppression.Pos, s.Pos) < 1f) { return false; } } Suppressions.Add(s); return true; } public MergeResult Merge(MapStore other) { MergeResult mergeResult = new MergeResult(); if (other == null) { return mergeResult; } foreach (KeyValuePair pin in other.Pins) { SharedPin value = pin.Value; if (string.IsNullOrEmpty(value.Id) || (Tombstones.TryGetValue(value.Id, out var value2) && value2 >= value.Modified)) { continue; } if (Pins.TryGetValue(value.Id, out var value3)) { if (value.Modified <= value3.Modified) { continue; } Pins[value.Id] = value.Clone(); mergeResult.Updated++; } else { Pins[value.Id] = value.Clone(); Tombstones.Remove(value.Id); mergeResult.Added++; } mergeResult.ChangedPins.Add(Pins[value.Id]); } foreach (KeyValuePair tombstone in other.Tombstones) { string key = tombstone.Key; long value4 = tombstone.Value; if (Pins.TryGetValue(key, out var value5) && value5.Modified <= value4) { Pins.Remove(key); mergeResult.Deleted++; mergeResult.NewTombstones.Add(new Tombstone { Id = key, DeletedAt = value4 }); } if (!Tombstones.TryGetValue(key, out var value6) || value4 > value6) { Tombstones[key] = value4; } } foreach (Suppression suppression in other.Suppressions) { if (AddSuppression(suppression)) { mergeResult.Suppressed++; mergeResult.NewSuppressions.Add(suppression); } } return mergeResult; } public void Write(ZPackage pkg) { pkg.Write(4); pkg.Write(Pins.Count); foreach (SharedPin value in Pins.Values) { value.Write(pkg); } pkg.Write(Tombstones.Count); foreach (KeyValuePair tombstone in Tombstones) { pkg.Write(tombstone.Key); pkg.Write(tombstone.Value); } pkg.Write(Suppressions.Count); foreach (Suppression suppression in Suppressions) { suppression.Write(pkg); } } public static MapStore Read(ZPackage pkg) { int num = pkg.ReadInt(); if (num < 1 || num > 4) { throw new InvalidDataException("Unsupported map format " + num); } MapStore mapStore = new MapStore(); int num2 = pkg.ReadInt(); for (int i = 0; i < num2; i++) { SharedPin sharedPin = SharedPin.Read(pkg, num); if (!string.IsNullOrEmpty(sharedPin.Id)) { mapStore.Pins[sharedPin.Id] = sharedPin; } } if (num >= 4) { int num3 = pkg.ReadInt(); for (int j = 0; j < num3; j++) { string text = pkg.ReadString(); long value = pkg.ReadLong(); if (!string.IsNullOrEmpty(text)) { mapStore.Tombstones[text] = value; } } } int num4 = pkg.ReadInt(); for (int k = 0; k < num4; k++) { mapStore.Suppressions.Add(Suppression.Read(pkg, num)); } return mapStore; } public byte[] ToBytes() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ZPackage val = new ZPackage(); Write(val); return val.GetArray(); } public static MapStore FromBytes(byte[] bytes) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown return Read(new ZPackage(bytes)); } } internal static class PersonalMap { private const string KeyPrefix = "TheGreatestMap.Map:"; internal static MapStore Store { get; private set; } = new MapStore(); internal static bool Loaded { get; private set; } internal static bool Dirty { get; private set; } internal static bool IsNew { get; private set; } private static string Key { get { World world = ZNet.World; string text = ((world != null) ? (world.m_name + "_" + world.m_seed) : "world"); return "TheGreatestMap.Map:" + text; } } internal static void Reset() { Store = new MapStore(); Loaded = false; Dirty = false; IsNew = false; } internal static void Touch() { Dirty = true; SyncEngine.OnLocalChange(); } internal static void MarkDirty() { Dirty = true; } internal static void LoadFrom(Player player) { Store = new MapStore(); Loaded = true; Dirty = false; IsNew = false; if ((Object)(object)player == (Object)null || player.m_customData == null) { return; } if (!player.m_customData.TryGetValue(Key, out var value) || string.IsNullOrEmpty(value)) { IsNew = true; return; } try { Store = MapStore.FromBytes(Utils.Decompress(Convert.FromBase64String(value))); TheGreatestMapMod.Log.LogInfo((object)$"[TheGreatestMap] Personal map loaded: {Store.Pins.Count} markers, {Store.Tombstones.Count} erased."); } catch (Exception ex) { TheGreatestMapMod.Log.LogWarning((object)("[TheGreatestMap] Could not read the personal map from the character; starting empty: " + ex.Message)); Store = new MapStore(); } } internal static void SaveTo(Player player) { if (!Loaded || (Object)(object)player == (Object)null || player.m_customData == null) { return; } try { player.m_customData[Key] = Convert.ToBase64String(Utils.Compress(Store.ToBytes())); Dirty = false; } catch (Exception ex) { TheGreatestMapMod.Log.LogWarning((object)("[TheGreatestMap] Could not save the personal map: " + ex.Message)); } } } [HarmonyPatch(typeof(Player), "Save")] internal static class Player_Save_PersonalMap_Patch { private static void Prefix(Player __instance) { if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer) { PersonalMap.SaveTo(__instance); } } } [HarmonyPatch(typeof(Player), "Load")] internal static class Player_Load_PersonalMap_Patch { private static void Postfix(Player __instance) { PersonalMap.LoadFrom(__instance); ClientPins.RebuildPins(); if (TgmConfig.ApplyLabelRulesOnSync.Value && PersonalMap.Store.Pins.Count > 0) { int num = ClientPins.ApplyLabelRules(null); if (num > 0) { TheGreatestMapMod.Log.LogInfo((object)$"[TheGreatestMap] Removed labels from {num} markers on the personal map to match the label rules."); } } } } internal static class PinNetwork { private const string Sync = "TGM_Sync"; private const string SyncRes = "TGM_SyncRes"; private const string Delta = "TGM_Delta"; private const string Exchange = "TGM_Exchange"; private const string Wipe = "TGM_Wipe"; private const string Unsuppress = "TGM_Unsuppress"; private const string BUnsuppress = "TGM_BUnsuppress"; private static bool Ready { get { if (ZRoutedRpc.instance != null) { return (Object)(object)ZNet.instance != (Object)null; } return false; } } internal static void Register() { ZRoutedRpc instance = ZRoutedRpc.instance; if (instance != null) { instance.Register("TGM_Sync", (Action)RPC_Sync); instance.Register("TGM_SyncRes", (Action)RPC_SyncRes); instance.Register("TGM_Delta", (Action)RPC_Delta); instance.Register("TGM_Exchange", (Action)RPC_Exchange); instance.Register("TGM_Wipe", (Action)RPC_Wipe); instance.Register("TGM_Unsuppress", (Action)RPC_Unsuppress); instance.Register("TGM_BUnsuppress", (Action)RPC_BUnsuppress); } } internal static void SendSync(MapStore store) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown if (Ready) { ZPackage val = new ZPackage(); store.Write(val); ZRoutedRpc.instance.InvokeRoutedRPC("TGM_Sync", new object[1] { val }); } } internal static void SendExchange(long peer, MapStore store, bool reply, byte[] exploration) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown if (Ready) { ZPackage val = new ZPackage(); val.Write(((Object)(object)Player.m_localPlayer != (Object)null) ? Player.m_localPlayer.GetPlayerName() : ""); val.Write(reply); store.Write(val); val.Write(exploration != null && exploration.Length != 0); if (exploration != null && exploration.Length != 0) { val.Write(exploration); } ZRoutedRpc.instance.InvokeRoutedRPC(peer, "TGM_Exchange", new object[1] { val }); } } internal static void SendWipe(bool autoOnly) { if (Ready) { ZRoutedRpc.instance.InvokeRoutedRPC("TGM_Wipe", new object[1] { autoOnly ? 1 : 0 }); } } internal static void SendUnsuppress() { if (Ready) { ZRoutedRpc.instance.InvokeRoutedRPC("TGM_Unsuppress", Array.Empty()); } } private static void Broadcast(string method, params object[] args) { ZRoutedRpc.instance.InvokeRoutedRPC(0L, method, args); } private static bool IsAdmin(long sender) { ZNet instance = ZNet.instance; if ((Object)(object)instance == (Object)null) { return false; } if (sender == Access.RoutedId.Invoke(ZRoutedRpc.instance)) { return true; } ZNetPeer peer = instance.GetPeer(sender); if (peer == null || peer.m_socket == null) { return false; } string hostName = peer.m_socket.GetHostName(); if (!string.IsNullOrEmpty(hostName)) { return instance.IsAdmin(hostName); } return false; } private static void RPC_Sync(long sender, ZPackage pkg) { //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown if (PinStore.IsServer && PinStore.Loaded) { MapStore incoming; try { incoming = MapStore.Read(pkg); } catch (Exception ex) { TheGreatestMapMod.Log.LogWarning((object)$"[TheGreatestMap] Bad map from peer {sender}: {ex.Message}"); return; } MergeResult mergeResult = PinStore.Merge(incoming); if (mergeResult.Any && TgmConfig.SharingMode.Value == SharingMode.Instant) { ZPackage val = new ZPackage(); mergeResult.ToDelta().Write(val); Broadcast("TGM_Delta", val); } ZRoutedRpc.instance.InvokeRoutedRPC(sender, "TGM_SyncRes", new object[1] { (object)new ZPackage(PinStore.Snapshot()) }); } } private static void RPC_Wipe(long sender, int autoOnly) { //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown if (PinStore.IsServer && PinStore.Loaded) { if (!IsAdmin(sender)) { TheGreatestMapMod.Log.LogWarning((object)$"[TheGreatestMap] Ignored wipe request from non-admin peer {sender}."); return; } MapStore mapStore = PinStore.Wipe(autoOnly != 0); TheGreatestMapMod.Log.LogInfo((object)$"[TheGreatestMap] Wiped {mapStore.Tombstones.Count} shared markers (autoOnly={autoOnly != 0}) on request of peer {sender}."); ZPackage val = new ZPackage(); mapStore.Write(val); Broadcast("TGM_Delta", val); } } private static void RPC_Unsuppress(long sender) { if (PinStore.IsServer && PinStore.Loaded && IsAdmin(sender)) { PinStore.ClearSuppressions(); Broadcast("TGM_BUnsuppress"); } } private static void RPC_SyncRes(long sender, ZPackage pkg) { if ((Object)(object)Minimap.instance == (Object)null) { return; } try { SyncEngine.OnSharedMap(MapStore.Read(pkg)); } catch (Exception ex) { TheGreatestMapMod.Log.LogWarning((object)("[TheGreatestMap] Bad shared map from the server: " + ex.Message)); } } private static void RPC_Delta(long sender, ZPackage pkg) { if ((Object)(object)Minimap.instance == (Object)null) { return; } try { SyncEngine.OnDelta(MapStore.Read(pkg)); } catch (Exception ex) { TheGreatestMapMod.Log.LogWarning((object)("[TheGreatestMap] Bad update from the server: " + ex.Message)); } } private static void RPC_Exchange(long sender, ZPackage pkg) { if ((Object)(object)Minimap.instance == (Object)null) { return; } string theirName; bool reply; MapStore theirs; try { theirName = pkg.ReadString(); reply = pkg.ReadBool(); theirs = MapStore.Read(pkg); } catch (Exception ex) { TheGreatestMapMod.Log.LogWarning((object)("[TheGreatestMap] Bad map from another player: " + ex.Message)); return; } byte[] exploration = null; try { if (pkg.ReadBool()) { exploration = pkg.ReadByteArray(); } } catch { exploration = null; } SyncEngine.OnExchange(sender, theirName, reply, theirs, exploration); } private static void RPC_BUnsuppress(long sender) { if (!((Object)(object)Minimap.instance == (Object)null)) { ClientPins.ClearSuppressions(); } } } [HarmonyPatch(typeof(Game), "Start")] internal static class Game_Start_Patch { private static void Postfix() { PinNetwork.Register(); ClientPins.Reset(); SyncEngine.Reset(); DiscoveryLedger.Clear(); Recorder.Reset(); LocationIndex.Clear(); Buildings.Clear(); Searched.Clear(); PocketMap.ResetState(); TableSync.Reset(); if (PinStore.IsServer) { PinStore.Load(); } } } [HarmonyPatch(typeof(Player), "OnSpawned")] internal static class Player_OnSpawned_Patch { private static void Postfix(Player __instance) { if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && (SyncEngine.Instant || PersonalMap.IsNew)) { SyncEngine.SyncWithServer(announceNothing: false); } } } [HarmonyPatch(typeof(ZNet), "Shutdown")] internal static class ZNet_Shutdown_Patch { private static void Prefix() { PinStore.Unload(); } } [HarmonyPatch(typeof(ZNet), "SaveWorldAndPlayerProfiles")] internal static class ZNet_SaveWorld_Patch { private static void Postfix() { PinStore.SaveIfDirty(); } } internal static class PinStore { private static MapStore _store = new MapStore(); private static bool _loaded; private static bool _dirty; private static float _saveAt; private static string _path; internal static bool IsServer { get { if ((Object)(object)ZNet.instance != (Object)null) { return ZNet.instance.IsServer(); } return false; } } internal static bool Loaded => _loaded; internal static int Count => _store.Pins.Count; internal static int SuppressionCount => _store.Suppressions.Count; internal static int TombstoneCount => _store.Tombstones.Count; internal static void Load() { _store = new MapStore(); _dirty = false; _path = BuildPath(); _loaded = true; if (_path == null) { TheGreatestMapMod.Log.LogWarning((object)"[TheGreatestMap] No world information; the shared map will not be persisted this session."); return; } try { if (File.Exists(_path)) { _store = MapStore.FromBytes(File.ReadAllBytes(_path)); TheGreatestMapMod.Log.LogInfo((object)$"[TheGreatestMap] Loaded the shared map: {_store.Pins.Count} markers, {_store.Tombstones.Count} erased, {_store.Suppressions.Count} erased spots, from {_path}"); } else { TheGreatestMapMod.Log.LogInfo((object)("[TheGreatestMap] No shared map file yet (" + _path + "); starting empty.")); } } catch (Exception arg) { TheGreatestMapMod.Log.LogError((object)$"[TheGreatestMap] Could not read {_path}: {arg}"); try { File.Copy(_path, _path + ".corrupt-" + DateTime.Now.ToString("yyyyMMdd-HHmmss"), overwrite: true); } catch { } _store = new MapStore(); } } internal static void Unload() { SaveIfDirty(); _loaded = false; _store = new MapStore(); } internal static void Update() { if (_loaded && _dirty && Time.unscaledTime >= _saveAt) { Save(); } } internal static void SaveIfDirty() { if (_loaded && _dirty) { Save(); } } private static void MarkDirty() { _dirty = true; _saveAt = Time.unscaledTime + 3f; } internal static void Save() { if (!_loaded || _path == null) { return; } try { Directory.CreateDirectory(Path.GetDirectoryName(_path)); string text = _path + ".tmp"; File.WriteAllBytes(text, _store.ToBytes()); if (File.Exists(_path)) { File.Replace(text, _path, null); } else { File.Move(text, _path); } _dirty = false; } catch (Exception arg) { TheGreatestMapMod.Log.LogError((object)$"[TheGreatestMap] Could not save {_path}: {arg}"); } } internal static MergeResult Merge(MapStore incoming) { MergeResult mergeResult = _store.Merge(incoming); if (mergeResult.Any) { MarkDirty(); } return mergeResult; } internal static byte[] Snapshot() { return _store.ToBytes(); } internal static MapStore Wipe(bool autoOnly) { MapStore mapStore = new MapStore(); long now = MapStore.Now; List list = new List(); foreach (KeyValuePair pin in _store.Pins) { if (!autoOnly || pin.Value.Auto) { list.Add(pin.Key); } } foreach (string item in list) { _store.Pins.Remove(item); _store.Tombstones[item] = now; mapStore.Tombstones[item] = now; } _store.Suppressions.Clear(); MarkDirty(); return mapStore; } internal static void ClearSuppressions() { _store.Suppressions.Clear(); MarkDirty(); } private static string BuildPath() { World world = ZNet.World; if (world == null) { return null; } return Path.Combine(Paths.ConfigPath, "TheGreatestMap", Sanitize(world.m_name) + "_" + world.m_seed + ".pins.bin"); } private static string Sanitize(string s) { char[] invalidFileNameChars = Path.GetInvalidFileNameChars(); StringBuilder stringBuilder = new StringBuilder(); string text = s ?? ""; foreach (char c in text) { stringBuilder.Append((Array.IndexOf(invalidFileNameChars, c) >= 0) ? '_' : c); } if (stringBuilder.Length != 0) { return stringBuilder.ToString(); } return "world"; } } internal static class PinTypes { internal static bool IsCustom(int type) { return type >= 100; } internal static bool IsPlayerPlaceable(int type) { if (type != 0 && type != 1 && type != 2 && type != 3 && type != 6) { return IsCustom(type); } return true; } } [HarmonyPatch(typeof(Minimap), "Start")] internal static class Minimap_Start_PinTypes_Patch { [HarmonyPriority(0)] private static void Postfix(Minimap __instance) { IconRegistry.OnMinimapStart(__instance); } } [HarmonyPatch(typeof(Minimap), "UpdatePins")] internal static class Minimap_UpdatePins_Guard_Patch { private static void Prefix(Minimap __instance) { IconRegistry.EnsureArrays(__instance); } } internal static class PocketMap { private static bool _busy; private static GameObject[] _localVisuals; private static Material _mapMaterial; private static readonly int MapOutHash = StringExtensionMethods.GetStableHashCode("TGM_MapOut"); private static readonly Dictionary _remoteVisuals = new Dictionary(); private static float _nextRemote; private static float _nextUv; internal static bool IsOut { get; private set; } internal static bool Busy => _busy; internal static void Update() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { if (IsOut) { ResetState(); } return; } if (Keys.IsDown(TgmConfig.TakeOutMapKey.Value) && Keys.CanTakeInput()) { Toggle(localPlayer); } if (IsOut) { if (((Character)localPlayer).IsDead() || ((Character)localPlayer).IsTeleporting() || (((Character)localPlayer).IsSwimming() && !((Character)localPlayer).IsOnGround())) { PutAway(localPlayer); } else if (Time.time >= _nextUv) { _nextUv = Time.time + 0.5f; UpdateMapView(localPlayer); } } if (Time.time >= _nextRemote) { _nextRemote = Time.time + 0.5f; UpdateRemotePlayers(localPlayer); if (IsOut) { OfferMapExchanges(localPlayer); } } } private static void OfferMapExchanges(Player local) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) float value = TgmConfig.ExchangeRadius.Value; foreach (Player allPlayer in Player.GetAllPlayers()) { if (!((Object)(object)allPlayer == (Object)null) && !((Object)(object)allPlayer == (Object)(object)local) && !(Vector3.Distance(((Component)allPlayer).transform.position, ((Component)local).transform.position) > value)) { ZNetView val = Access.NView.Invoke((Character)(object)allPlayer); if (!((Object)(object)val == (Object)null) && val.IsValid() && val.GetZDO().GetInt(MapOutHash, 0) == 1) { SyncEngine.TryExchange(allPlayer); } } } } internal static void Toggle(Player player) { if (IsOut) { PutAway(player); } else { TakeOut(player); } } internal static void TakeOut(Player player) { if (IsOut || (Object)(object)player == (Object)null || ((Character)player).IsDead() || ((Character)player).IsTeleporting() || ((Character)player).InAttack() || ((Character)player).InDodge() || ((Character)player).IsAttached()) { return; } _busy = true; try { ((Humanoid)player).HideHandItems(false, true); IsOut = true; SetFlag(player, 1); if (TgmConfig.ShowMapInHands.Value) { _localVisuals = CreateVisuals((Humanoid)(object)player, out _mapMaterial); } if (TgmConfig.MapPose.Value > 0 && (Object)(object)Access.ZAnim.Invoke((Character)(object)player) != (Object)null) { Access.ZAnim.Invoke((Character)(object)player).SetInt("crafting", TgmConfig.MapPose.Value); } TheGreatestMapMod.Message("You unfold your map."); } finally { _busy = false; } } internal static void PutAway(Player player, bool showHands = true) { if (!IsOut) { return; } _busy = true; try { IsOut = false; if ((Object)(object)player != (Object)null) { SetFlag(player, 0); } DestroyLocalVisuals(); if ((Object)(object)player != (Object)null && TgmConfig.MapPose.Value > 0 && (Object)(object)Access.ZAnim.Invoke((Character)(object)player) != (Object)null) { Access.ZAnim.Invoke((Character)(object)player).SetInt("crafting", 0); } if (showHands && (Object)(object)player != (Object)null && !((Character)player).IsDead()) { Access.ShowHandItems((Humanoid)(object)player); } TheGreatestMapMod.Message("You fold up your map."); } finally { _busy = false; } } internal static void OnVanillaShowHands(Player player) { if (!_busy && IsOut) { PutAway(player, showHands: false); } } internal static void ResetState() { IsOut = false; _busy = false; DestroyLocalVisuals(); foreach (KeyValuePair remoteVisual in _remoteVisuals) { DestroyObjects(remoteVisual.Value); } _remoteVisuals.Clear(); } private static void SetFlag(Player player, int value) { ZNetView val = Access.NView.Invoke((Character)(object)player); if (!((Object)(object)val == (Object)null) && val.IsValid() && val.IsOwner()) { val.GetZDO().Set(MapOutHash, value, false); } } private static GameObject[] CreateVisuals(Humanoid humanoid, out Material mapMaterial) { mapMaterial = null; VisEquipment val = Access.VisEquip.Invoke(humanoid); if ((Object)(object)val == (Object)null) { return null; } List list = new List(); if ((Object)(object)val.m_leftHand != (Object)null) { GameObject val2 = BuildMap(val.m_leftHand, out mapMaterial); if ((Object)(object)val2 != (Object)null) { list.Add(val2); } } if ((Object)(object)val.m_rightHand != (Object)null) { GameObject val3 = BuildPencil(val.m_rightHand); if ((Object)(object)val3 != (Object)null) { list.Add(val3); } } if (list.Count <= 0) { return null; } return list.ToArray(); } private static GameObject BuildMap(Transform parent, out Material material) { //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_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) material = MakeMaterial(); if ((Object)(object)material == (Object)null) { return null; } GameObject result = BuildPrimitive(parent, "TGM_PocketMap", TgmConfig.ParseVector(TgmConfig.MapOffset.Value, new Vector3(0f, 0.08f, 0.02f)), TgmConfig.ParseVector(TgmConfig.MapRotation.Value, new Vector3(0f, 90f, 0f)), TgmConfig.ParseVector(TgmConfig.MapScale.Value, new Vector3(0.28f, 0.2f, 0.004f)), material); if ((Object)(object)Minimap.instance != (Object)null && (Object)(object)Minimap.instance.m_mapTexture != (Object)null) { material.mainTexture = (Texture)(object)Minimap.instance.m_mapTexture; } return result; } private static GameObject BuildPencil(Transform parent) { //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: 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_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0107: 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_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) GameObject val = AttachVanillaVisual(parent, TgmConfig.PencilItem.Value); if ((Object)(object)val == (Object)null) { TheGreatestMapMod.Log.LogWarning((object)("[TheGreatestMap] Could not attach pencil model '" + TgmConfig.PencilItem.Value + "'; using a plain stick instead.")); Material val2 = MakeMaterial(); if ((Object)(object)val2 == (Object)null) { return null; } if (val2.HasProperty("_Color")) { val2.color = new Color(0.55f, 0.38f, 0.2f); } return BuildPrimitive(parent, "TGM_Pencil", new Vector3(0f, 0f, 0.08f), Vector3.zero, new Vector3(0.02f, 0.02f, 0.16f), val2); } ((Object)val).name = "TGM_Pencil"; Transform transform = val.transform; transform.localPosition += TgmConfig.ParseVector(TgmConfig.PencilPositionTweak.Value, Vector3.zero); Transform transform2 = val.transform; transform2.localRotation *= Quaternion.Euler(TgmConfig.ParseVector(TgmConfig.PencilRotationTweak.Value, Vector3.zero)); val.transform.localScale = TgmConfig.ParseVector(TgmConfig.PencilSize.Value, new Vector3(0.25f, 0.25f, 0.25f)); return val; } private static GameObject AttachVanillaVisual(Transform joint, string itemName) { //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(itemName) || (Object)(object)ObjectDB.instance == (Object)null) { return null; } GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(itemName.Trim()); if ((Object)(object)itemPrefab == (Object)null) { return null; } Transform val = null; for (int i = 0; i < itemPrefab.transform.childCount; i++) { Transform child = itemPrefab.transform.GetChild(i); if (((Object)child).name == "attach") { val = child; break; } } if ((Object)(object)val == (Object)null) { return null; } GameObject val2 = Object.Instantiate(((Component)val).gameObject); val2.SetActive(true); Collider[] componentsInChildren = val2.GetComponentsInChildren(true); for (int j = 0; j < componentsInChildren.Length; j++) { componentsInChildren[j].enabled = false; } Light[] componentsInChildren2 = val2.GetComponentsInChildren(true); for (int j = 0; j < componentsInChildren2.Length; j++) { ((Behaviour)componentsInChildren2[j]).enabled = false; } val2.transform.SetParent(joint); val2.transform.localPosition = Vector3.zero; val2.transform.localRotation = Quaternion.identity; Transform val3 = itemPrefab.transform.Find("equipoffset"); if ((Object)(object)val3 != (Object)null) { Transform transform = val2.transform; transform.localPosition += val3.position; Transform transform2 = val2.transform; transform2.localRotation *= val3.rotation; } return val2; } private static GameObject BuildPrimitive(Transform parent, string name, Vector3 pos, Vector3 euler, Vector3 scale, Material material) { //IL_0036: 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_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) GameObject obj = GameObject.CreatePrimitive((PrimitiveType)3); ((Object)obj).name = name; Collider component = obj.GetComponent(); if ((Object)(object)component != (Object)null) { Object.Destroy((Object)(object)component); } obj.transform.SetParent(parent, false); obj.transform.localPosition = pos; obj.transform.localRotation = Quaternion.Euler(euler); obj.transform.localScale = scale; MeshRenderer component2 = obj.GetComponent(); ((Renderer)component2).shadowCastingMode = (ShadowCastingMode)0; ((Renderer)component2).receiveShadows = false; ((Renderer)component2).sharedMaterial = material; obj.layer = ((Component)parent).gameObject.layer; return obj; } private static Material MakeMaterial() { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Expected O, but got Unknown Material val = null; try { GameObject val2 = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab("Wood") : null); Renderer val3 = (((Object)(object)val2 != (Object)null) ? val2.GetComponentInChildren() : null); if ((Object)(object)val3 != (Object)null) { val = val3.sharedMaterial; } } catch { } if ((Object)(object)val != (Object)null) { return new Material(val) { name = "TGM_Material" }; } Shader val4 = Shader.Find("Standard") ?? Shader.Find("Legacy Shaders/Diffuse") ?? Shader.Find("Sprites/Default"); if (!((Object)(object)val4 != (Object)null)) { return null; } return new Material(val4) { name = "TGM_Material" }; } private static void UpdateMapView(Player player) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_mapMaterial == (Object)null) && !((Object)(object)Minimap.instance == (Object)null)) { Access.WorldToMapPoint(Minimap.instance, ((Component)player).transform.position, out var mx, out var my); float num = Mathf.Clamp(TgmConfig.MapViewFraction.Value, 0.02f, 1f); _mapMaterial.mainTextureScale = new Vector2(num, num); _mapMaterial.mainTextureOffset = new Vector2(mx - num * 0.5f, my - num * 0.5f); } } private static void DestroyLocalVisuals() { DestroyObjects(_localVisuals); _localVisuals = null; _mapMaterial = null; } private static void DestroyObjects(GameObject[] objects) { if (objects == null) { return; } foreach (GameObject val in objects) { if ((Object)(object)val != (Object)null) { Object.Destroy((Object)(object)val); } } } private static void UpdateRemotePlayers(Player local) { List allPlayers = Player.GetAllPlayers(); if (_remoteVisuals.Count > 0) { List list = new List(); foreach (KeyValuePair remoteVisual in _remoteVisuals) { if ((Object)(object)remoteVisual.Key == (Object)null || !allPlayers.Contains(remoteVisual.Key)) { list.Add(remoteVisual.Key); } } foreach (Player item in list) { DestroyObjects(_remoteVisuals[item]); _remoteVisuals.Remove(item); } } if (!TgmConfig.ShowMapInHands.Value) { return; } foreach (Player item2 in allPlayers) { if ((Object)(object)item2 == (Object)null || (Object)(object)item2 == (Object)(object)local) { continue; } ZNetView val = Access.NView.Invoke((Character)(object)item2); if ((Object)(object)val == (Object)null || !val.IsValid()) { continue; } bool flag = val.GetZDO().GetInt(MapOutHash, 0) == 1; bool flag2 = _remoteVisuals.ContainsKey(item2); if (flag && !flag2) { Material mapMaterial; GameObject[] array = CreateVisuals((Humanoid)(object)item2, out mapMaterial); if (array != null) { _remoteVisuals[item2] = array; } } else if (!flag && flag2) { DestroyObjects(_remoteVisuals[item2]); _remoteVisuals.Remove(item2); } } } internal static bool IsHandItem(ItemData item) { //IL_000b: 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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Invalid comparison between Unknown and I4 //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected I4, but got Unknown if (item == null) { return false; } ItemType itemType = item.m_shared.m_itemType; if (itemType - 3 > 2) { switch (itemType - 14) { case 0: case 1: case 5: case 6: case 8: break; default: return false; } } return true; } } [HarmonyPatch(typeof(Humanoid), "ShowHandItems")] internal static class Humanoid_ShowHandItems_Patch { private static void Prefix(Humanoid __instance) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown if (PocketMap.IsOut && (Object)(object)__instance == (Object)(object)Player.m_localPlayer) { PocketMap.OnVanillaShowHands((Player)__instance); } } } [HarmonyPatch(typeof(Humanoid), "StartAttack")] internal static class Humanoid_StartAttack_Patch { private static bool Prefix(Humanoid __instance, ref bool __result) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown if (!PocketMap.IsOut || PocketMap.Busy || (Object)(object)__instance != (Object)(object)Player.m_localPlayer) { return true; } PocketMap.PutAway((Player)__instance); __result = false; return false; } } [HarmonyPatch(typeof(Humanoid), "EquipItem")] internal static class Humanoid_EquipItem_Patch { private static void Prefix(Humanoid __instance, ItemData item) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown if (PocketMap.IsOut && !PocketMap.Busy && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && PocketMap.IsHandItem(item)) { PocketMap.PutAway((Player)__instance, showHands: false); } } } [HarmonyPatch(typeof(Player), "OnDamaged")] internal static class Player_OnDamaged_Patch { private static void Postfix(Player __instance, HitData hit) { if (PocketMap.IsOut && !PocketMap.Busy && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && hit != null && hit.GetTotalDamage() > 0f) { PocketMap.PutAway(__instance); } } } [HarmonyPatch(typeof(Player), "OnDeath")] internal static class Player_OnDeath_Patch { private static void Postfix(Player __instance) { if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer) { PocketMap.ResetState(); } } } internal static class Recorder { private static readonly HashSet _announced = new HashSet(); private static float _outSince = -1f; private static float _next; internal static void Reset() { _announced.Clear(); _outSince = -1f; } internal static void Update() { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0187: 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_0235: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; bool flag = PocketMap.IsOut || !TgmConfig.RequireMapOutToRecord.Value; if ((Object)(object)localPlayer == (Object)null || !flag || !TgmConfig.RecordEnabled.Value) { _outSince = -1f; return; } if (_outSince < 0f) { _outSince = Time.time; } if (Time.time - _outSince < TgmConfig.RecordDwell.Value || Time.time < _next) { return; } _next = Time.time + 0.5f; if (((Character)localPlayer).InInterior()) { return; } Vector3 position = ((Component)localPlayer).transform.position; float value = TgmConfig.RecordRadius.Value; foreach (Found item in DiscoveryLedger.Pending()) { if (value > 0f && Geo.FlatDistance(position, item.Pos) > value) { continue; } if (!TgmConfig.CategoryEnabled.TryGetValue(item.Cat, out var value2) || !value2.Value) { DiscoveryLedger.MarkRecorded(item.Key); continue; } ConfigEntry value3; float num = Mathf.Max(TgmConfig.MarkerSpacing.TryGetValue(item.Cat, out value3) ? value3.Value : 1f, item.Radius); Vector3 dedupeCenter = item.DedupeCenter; if (ClientPins.HasPinNear(item.Icon, dedupeCenter, num)) { Announce(item, $"{item.Name}: already marked within {num:0.#} m"); continue; } if (ClientPins.IsSuppressed(item.Icon, dedupeCenter, num)) { Announce(item, item.Name + ": a marker here was erased, not recording"); continue; } ConfigEntry value4; float num2 = (TgmConfig.LabelSpacing.TryGetValue(item.Cat, out value4) ? value4.Value : 0f); float radius = ((num2 > 0f) ? Mathf.Max(num2, item.Radius) : num2); bool num3 = num2 >= 0f && !ClientPins.HasLabeledPinNear(item.Icon, item.Name, dedupeCenter, radius); DiscoveryLedger.MarkRecorded(item.Key); ClientPins.CreateShared(num3 ? item.Name : "", item.Pos, item.Icon, item.Cat.ToString(), auto: true, Searched.WasSearched(item.Key)); TheGreatestMapMod.Message("Recorded: " + item.Name); } } private static void Announce(Found found, string text) { if (_announced.Add(found.Key)) { TheGreatestMapMod.Message(text); } } } internal static class Searched { private const float MatchRadius = 3f; private static readonly HashSet _keys = new HashSet(); internal static bool WasSearched(string key) { if (key != null) { return _keys.Contains(key); } return false; } internal static void Clear() { _keys.Clear(); } internal static void OnSearched(GameObject go) { //IL_005b: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)go == (Object)null || !TgmConfig.CrossOffStructuresOnChest.Value) { return; } Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null) && !((Character)localPlayer).InInterior() && Catalog.TryClassify(go, out var found) && found.Cat == Category.Structure) { _keys.Add(found.Key); if (ClientPins.TryCheckOff(found.Icon, found.DedupeCenter, Mathf.Max(3f, found.Radius))) { TheGreatestMapMod.Message("Searched: " + found.Name); } } } } internal static class ServerSave { private const string TriggerName = "save-now"; private static float _nextCheck; private static float _nextAutosave = -1f; private static string TriggerPath => Path.Combine(Paths.ConfigPath, "TheGreatestMap", "save-now"); internal static void Update() { if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return; } float unscaledTime = Time.unscaledTime; if (unscaledTime < _nextCheck) { return; } _nextCheck = unscaledTime + 2f; try { string triggerPath = TriggerPath; if (File.Exists(triggerPath)) { File.Delete(triggerPath); TheGreatestMapMod.Log.LogInfo((object)"[TheGreatestMap] save-now trigger found: saving the world and player profiles."); ZNet.instance.SaveWorldAndPlayerProfiles(); } } catch (Exception ex) { TheGreatestMapMod.Log.LogWarning((object)("[TheGreatestMap] save-now trigger failed: " + ex.Message)); } float value = TgmConfig.ServerAutosaveMinutes.Value; if (value <= 0f) { _nextAutosave = -1f; } else if (_nextAutosave < 0f) { _nextAutosave = unscaledTime + value * 60f; } else if (unscaledTime >= _nextAutosave) { _nextAutosave = unscaledTime + value * 60f; TheGreatestMapMod.Log.LogInfo((object)$"[TheGreatestMap] Extra autosave ({value:0.#} min interval)."); ZNet.instance.SaveWorldAndPlayerProfiles(); } } } internal sealed class SharedPin { public string Id = ""; public long OwnerId; public string Author = ""; public string Name = ""; public Vector3 Pos; public int Type; public string Icon = ""; public string Kind = ""; public bool Checked; public bool Auto; public long Created; public long Modified; private Category? _kind; private bool _kindParsed; public Category? KindCategory { get { if (!_kindParsed) { _kindParsed = true; if (!string.IsNullOrEmpty(Kind) && Enum.TryParse(Kind, ignoreCase: true, out var result)) { _kind = result; } } return _kind; } } public static string NewId() { return Guid.NewGuid().ToString("N"); } public SharedPin Clone() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) return new SharedPin { Id = Id, OwnerId = OwnerId, Author = Author, Name = Name, Pos = Pos, Type = Type, Icon = Icon, Kind = Kind, Checked = Checked, Auto = Auto, Created = Created, Modified = Modified }; } public void Write(ZPackage pkg) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) pkg.Write(Id ?? ""); pkg.Write(OwnerId); pkg.Write(Author ?? ""); pkg.Write(Name ?? ""); pkg.Write(Pos); pkg.Write(Type); pkg.Write(Icon ?? ""); pkg.Write(Kind ?? ""); pkg.Write(Checked); pkg.Write(Auto); pkg.Write(Created); pkg.Write(Modified); } public static SharedPin Read(ZPackage pkg, int version) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) SharedPin sharedPin = new SharedPin { Id = pkg.ReadString(), OwnerId = pkg.ReadLong(), Author = pkg.ReadString(), Name = pkg.ReadString(), Pos = pkg.ReadVector3(), Type = pkg.ReadInt() }; sharedPin.Icon = ((version >= 2) ? pkg.ReadString() : IconRegistry.LegacyKey(sharedPin.Type)); sharedPin.Kind = ((version >= 3) ? pkg.ReadString() : ""); sharedPin.Checked = pkg.ReadBool(); sharedPin.Auto = pkg.ReadBool(); sharedPin.Created = pkg.ReadLong(); sharedPin.Modified = ((version >= 4) ? pkg.ReadLong() : sharedPin.Created); return sharedPin; } } internal sealed class Suppression { public int Type; public string Icon = ""; public Vector3 Pos; public string Name = ""; public void Write(ZPackage pkg) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) pkg.Write(Type); pkg.Write(Icon ?? ""); pkg.Write(Pos); pkg.Write(Name ?? ""); } public static Suppression Read(ZPackage pkg, int version) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) Suppression suppression = new Suppression { Type = pkg.ReadInt() }; suppression.Icon = ((version >= 2) ? pkg.ReadString() : IconRegistry.LegacyKey(suppression.Type)); suppression.Pos = pkg.ReadVector3(); suppression.Name = pkg.ReadString(); return suppression; } } internal static class Geo { internal static float FlatDistance(Vector3 a, Vector3 b) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) float num = a.x - b.x; float num2 = a.z - b.z; return Mathf.Sqrt(num * num + num2 * num2); } } internal enum SharingMode { Table, Instant } internal static class SyncEngine { private static float _instantDue = -1f; private static bool _announcePending; private static readonly Dictionary _lastExchange = new Dictionary(); private static readonly HashSet _quietOnce = new HashSet(); internal static bool Instant => TgmConfig.SharingMode.Value == SharingMode.Instant; internal static void Reset() { _instantDue = -1f; _announcePending = false; _lastExchange.Clear(); _quietOnce.Clear(); } internal static void OnLocalChange() { if (Instant) { _instantDue = Time.time + 2f; } } internal static void Update() { if (_instantDue > 0f && Time.time >= _instantDue) { _instantDue = -1f; SyncWithServer(announceNothing: false); } } internal static void SyncWithServer(bool announceNothing) { if (PersonalMap.Loaded) { _announcePending = announceNothing; PinNetwork.SendSync(PersonalMap.Store); } } internal static void OnSharedMap(MapStore serverStore) { MergeResult mergeResult = ClientPins.ApplyMerge(serverStore); AfterMerge(mergeResult); if (mergeResult.Any) { TheGreatestMapMod.Message("Shared map: " + mergeResult); } else if (_announcePending) { TheGreatestMapMod.Message("Shared map: nothing new."); } _announcePending = false; } internal static void OnDelta(MapStore delta) { MergeResult mergeResult = ClientPins.ApplyMerge(delta); AfterMerge(mergeResult); if (mergeResult.Deleted > 0 && mergeResult.Added == 0 && mergeResult.Updated == 0 && delta.Tombstones.Count > 5) { TheGreatestMapMod.Message($"Shared map: {mergeResult.Deleted} markers erased by an admin."); } } internal static void AfterMerge(MergeResult result) { if (TgmConfig.ApplyLabelRulesOnSync.Value && result.Added + result.Updated != 0) { int num = ClientPins.ApplyLabelRules(null); if (num > 0) { TheGreatestMapMod.Log.LogInfo((object)$"[TheGreatestMap] Removed labels from {num} markers to match the label rules."); } } } internal static void TryExchange(Player other) { if (!PersonalMap.Loaded || (Object)(object)other == (Object)null) { return; } ZNetView val = Access.NView.Invoke((Character)(object)other); if (!((Object)(object)val == (Object)null) && val.IsValid()) { long owner = val.GetZDO().GetOwner(); if (owner != 0L && (!_lastExchange.TryGetValue(owner, out var value) || !(Time.time - value < TgmConfig.ExchangeCooldown.Value))) { _lastExchange[owner] = Time.time; PinNetwork.SendExchange(owner, PersonalMap.Store, reply: true, MyExploration()); } } } internal static void OnExchange(long sender, string theirName, bool reply, MapStore theirs, byte[] exploration) { MergeResult mergeResult = ClientPins.ApplyMerge(theirs); AfterMerge(mergeResult); bool num = ApplyExploration(exploration); if (reply) { _lastExchange[sender] = Time.time; PinNetwork.SendExchange(sender, PersonalMap.Store, reply: false, MyExploration()); } string text = (mergeResult.Any ? mergeResult.ToString() : ""); if (num) { text = ((text.Length > 0) ? (text + ", new map areas") : "new map areas"); } if (text.Length > 0) { TheGreatestMapMod.Message("Compared maps with " + theirName + ": " + text + "."); } else if (_quietOnce.Add(sender)) { TheGreatestMapMod.Message("Compared maps with " + theirName + ": nothing new."); } } private static byte[] MyExploration() { if (!TgmConfig.ExchangeExploration.Value || (Object)(object)Minimap.instance == (Object)null) { return null; } try { return Utils.Compress(Minimap.instance.GetSharedMapData((byte[])null)); } catch (Exception ex) { TheGreatestMapMod.Log.LogWarning((object)("[TheGreatestMap] Could not pack the explored area for exchange: " + ex.Message)); return null; } } private static bool ApplyExploration(byte[] exploration) { if (exploration == null || exploration.Length == 0 || (Object)(object)Minimap.instance == (Object)null) { return false; } try { return Minimap.instance.AddSharedMapData(Utils.Decompress(exploration)); } catch (Exception ex) { TheGreatestMapMod.Log.LogWarning((object)("[TheGreatestMap] Could not read another player's explored area: " + ex.Message)); return false; } } } internal static class TableSync { private static readonly Dictionary _lastSync = new Dictionary(); private static readonly Collider[] _buffer = (Collider[])(object)new Collider[64]; private static int _pieceMask = -1; private static float _next; private static int PieceMask { get { if (_pieceMask < 0) { _pieceMask = LayerMask.GetMask(new string[2] { "piece", "piece_nonsolid" }); } return _pieceMask; } } internal static void Reset() { _lastSync.Clear(); _next = 0f; } internal static void Update() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } if (Keys.IsDown(TgmConfig.SyncTableKey.Value) && Keys.CanTakeInput()) { SyncNow(localPlayer, announceMissing: true); } else { if (!TgmConfig.AutoSyncTable.Value || Time.time < _next) { return; } _next = Time.time + 1f; MapTable val = FindNearestTable(localPlayer); if (!((Object)(object)val == (Object)null)) { int instanceID = ((Object)val).GetInstanceID(); if (!_lastSync.TryGetValue(instanceID, out var value) || !(Time.time - value < TgmConfig.TableSyncCooldown.Value)) { _lastSync[instanceID] = Time.time; Sync(val, localPlayer, manual: false); } } } } internal static bool SyncNow(Player player, bool announceMissing) { MapTable val = FindNearestTable(player); if ((Object)(object)val == (Object)null) { if (announceMissing) { TheGreatestMapMod.Message("No cartography table within reach."); } return false; } _lastSync[((Object)val).GetInstanceID()] = Time.time; Sync(val, player, manual: true); return true; } private static void Sync(MapTable table, Player player, bool manual) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) Minimap instance = Minimap.instance; if ((Object)(object)instance == (Object)null) { return; } ZNetView val = Access.TableView.Invoke(table); if ((Object)(object)val == (Object)null || !val.IsValid()) { return; } if (!PrivateArea.CheckAccess(((Component)table).transform.position, 0f, manual, false)) { if (manual) { TheGreatestMapMod.Message("No access to this cartography table."); } return; } byte[] array = null; try { byte[] byteArray = val.GetZDO().GetByteArray(ZDOVars.s_data, (byte[])null); if (byteArray != null) { array = Utils.Decompress(byteArray); } } catch (Exception ex) { TheGreatestMapMod.Log.LogWarning((object)("[TheGreatestMap] Could not read the cartography table: " + ex.Message)); } bool num = array != null && instance.AddSharedMapData(array); bool flag = array == null || HasExplorationNotIn(instance, array); if (flag) { Access.TableWrite(table, (Humanoid)(object)player); } if (num) { TheGreatestMapMod.Message(flag ? "Map exchanged with the cartography table." : "New map areas read from the cartography table."); } else if (manual && !flag) { TheGreatestMapMod.Message("Cartography table already up to date."); } SyncEngine.SyncWithServer(manual); } private static bool HasExplorationNotIn(Minimap map, byte[] data) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown try { ZPackage val = new ZPackage(data); int version = val.ReadInt(); List list = Access.ReadExploredArray(map, val, version); if (list == null) { return true; } BitArray bitArray = Access.Explored.Invoke(map); BitArray bitArray2 = Access.ExploredOthers.Invoke(map); int num = Math.Min(list.Count, bitArray.Length); for (int i = 0; i < num; i++) { if (!list[i] && (bitArray[i] || bitArray2[i])) { return true; } } return bitArray.Length > list.Count; } catch (Exception ex) { TheGreatestMapMod.Log.LogWarning((object)("[TheGreatestMap] Could not compare with the cartography table, writing anyway: " + ex.Message)); return true; } } private static MapTable FindNearestTable(Player player) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: 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_0060: 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) Vector3 position = ((Component)player).transform.position; int num = Physics.OverlapSphereNonAlloc(position, TgmConfig.TableSyncRadius.Value, _buffer, PieceMask); MapTable result = null; float num2 = float.MaxValue; for (int i = 0; i < num; i++) { MapTable val = (((Object)(object)_buffer[i] != (Object)null) ? ((Component)_buffer[i]).GetComponentInParent() : null); if (!((Object)(object)val == (Object)null)) { float num3 = Vector3.Distance(position, ((Component)val).transform.position); if (num3 < num2) { num2 = num3; result = val; } } } return result; } } internal static class TgmConfig { internal static ConfigEntry TakeOutMapKey; internal static ConfigEntry SyncTableKey; internal static ConfigEntry ShowMessages; internal static ConfigEntry SharingMode; internal static ConfigEntry AllowErasingMarkers; internal static ConfigEntry RequireMapOutToEdit; internal static ConfigEntry RequireMapOutToRecord; internal static ConfigEntry SharePlacedPins; internal static ConfigEntry TableCarriesPins; internal static ConfigEntry ExchangeRadius; internal static ConfigEntry ExchangeCooldown; internal static ConfigEntry ExchangeExploration; internal static readonly Dictionary> ShowKind = new Dictionary>(); internal static ConfigEntry HiddenIcons; private static HashSet _hiddenIconKeys; internal static ConfigEntry AutoSyncTable; internal static ConfigEntry TableSyncRadius; internal static ConfigEntry TableSyncCooldown; internal static ConfigEntry RecordEnabled; internal static ConfigEntry RecordRadius; internal static ConfigEntry RecordDwell; internal static ConfigEntry FoundMemoryMinutes; internal static ConfigEntry LookDwell; internal static readonly Dictionary> LookDistance = new Dictionary>(); internal static readonly Dictionary> CategoryEnabled = new Dictionary>(); internal static readonly Dictionary> MarkerSpacing = new Dictionary>(); internal static readonly Dictionary> LabelSpacing = new Dictionary>(); internal static readonly Dictionary> MarkerSize = new Dictionary>(); internal static readonly Dictionary> ShowOnMinimap = new Dictionary>(); internal static readonly Dictionary> CategoryPrefabs = new Dictionary>(); internal static readonly Dictionary> CategoryIcon = new Dictionary>(); internal static ConfigEntry StructuresIncludeUnlisted; internal static ConfigEntry StructuresExcludePrefixes; internal static ConfigEntry CrossOffStructuresOnChest; internal static ConfigEntry ApplyLabelRulesOnSync; internal static ConfigEntry ServerAutosaveMinutes; internal static ConfigEntry ShowMapInHands; internal static ConfigEntry MapPose; internal static ConfigEntry MapViewFraction; internal static ConfigEntry MapOffset; internal static ConfigEntry MapRotation; internal static ConfigEntry MapScale; internal static ConfigEntry PencilItem; internal static ConfigEntry PencilSize; internal static ConfigEntry PencilPositionTweak; internal static ConfigEntry PencilRotationTweak; internal static bool IsIconHidden(string icon) { if (_hiddenIconKeys == null) { _hiddenIconKeys = new HashSet(StringComparer.OrdinalIgnoreCase); string[] array = (HiddenIcons.Value ?? "").Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i++) { string text = IconRegistry.Normalize(array[i]); if (text != null) { _hiddenIconKeys.Add(text); } } } string text2 = IconRegistry.Normalize(icon); if (text2 != null) { return _hiddenIconKeys.Contains(text2); } return false; } internal static float LookDistanceFor(Category cat) { if (!LookDistance.TryGetValue(cat, out var value)) { return 30f; } return Mathf.Max(0f, value.Value); } internal static float MaxLookDistance() { float num = 5f; foreach (ConfigEntry value in LookDistance.Values) { if (value.Value > num) { num = value.Value; } } return num; } internal static void Bind(TheGreatestMapMod mod) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) TakeOutMapKey = mod.BindLocal("Keys", "Take Out Map", new KeyboardShortcut((KeyCode)121, Array.Empty()), "Takes the map out of your pocket (both hands: map left, pencil right) or puts it away. Use a key no other mod acts on: a mod that equips something on the same key folds the map straight back up."); SyncTableKey = mod.BindLocal("Keys", "Sync Cartography Table", new KeyboardShortcut((KeyCode)117, Array.Empty()), "Reads and writes the nearest cartography table within reach right now, ignoring the auto-sync cooldown."); ShowMessages = mod.BindLocal("General", "Show Messages", defaultValue: true, "Show small top-left messages when the map is taken out, a marker is recorded, and so on."); SharingMode = mod.BindSynced("Sharing", "Sharing Mode", TheGreatestMap.SharingMode.Table, "Table: markers travel like exploration. What you record or place stays on your own map until you merge it with the shared map at a cartography table, or with another player's map when you both have your maps out standing together. Instant: every change goes to the shared map at once and out to everyone."); AllowErasingMarkers = mod.BindSynced("Sharing", "Allow Erasing Markers", defaultValue: false, "Let players erase this mod's markers (Shift + right-click on the map screen). Off by default so a marker cannot be lost to a stray click; vanilla pins are unaffected. An erasure merges like any other change: it wins over older copies of the marker and is itself replaced if someone records the spot again later."); ExchangeRadius = mod.BindLocal("Sharing", "Exchange Radius", 5f, "Distance in metres within which two players who both have their maps out compare and merge their maps."); ExchangeCooldown = mod.BindLocal("Sharing", "Exchange Cooldown", 60f, "Seconds before the same two players compare maps again."); ExchangeExploration = mod.BindLocal("Sharing", "Exchange Exploration", defaultValue: true, "When comparing maps with another player, also share explored areas (the fog of war), as a cartography table does."); HiddenIcons = mod.BindLocal("Display", "Hidden Icons", "", "Comma-separated marker icons never drawn on your map, as item prefab names or icon keys, e.g. Dandelion,Thistle,pin:Icon1. Hidden markers stay on your map and keep syncing; they are just not shown. Applies at once."); HiddenIcons.SettingChanged += delegate { _hiddenIconKeys = null; }; RequireMapOutToEdit = mod.BindSynced("Sharing", "Require Map Out To Edit", defaultValue: false, "You must have the pocket map out to place a marker, erase one (yours, someone else's or a recorded one) or cross one off on the map screen. Pings are always allowed. Off by default: the map screen edits like vanilla."); RequireMapOutToRecord = mod.BindSynced("Sharing", "Require Map Out To Record", defaultValue: true, "Automatic recording of found things only happens while the pocket map is out. Turn off to record found things whenever you are within the record radius, map or no map."); SharePlacedPins = mod.BindSynced("Sharing", "Share Placed Markers", defaultValue: true, "Markers you place on the map screen are shared instantly with everyone on the server. When false they stay private, as in vanilla."); TableCarriesPins = mod.BindSynced("Sharing", "Table Carries Player Markers", defaultValue: false, "When false (recommended) the cartography table only carries map exploration. Player-placed markers (the five standard icons and this mod's icons) are neither written to nor read from the table, and stale copies previously imported from a table are swept away. Boss, Hildir and memorial pins still share through the table as in vanilla. Set true to restore vanilla table behaviour for markers."); AutoSyncTable = mod.BindLocal("Cartography Table", "Auto Sync", defaultValue: true, "Automatically read and write the cartography table when you are right at it. Silent unless something is actually exchanged: new areas from the table are read, and the table is written (vanilla's 'map saved') only when it lacks areas you have explored."); TableSyncRadius = mod.BindLocal("Cartography Table", "Sync Radius", 1f, "How close to a cartography table you must stand (metres from you to its edge) for auto-sync and the sync key."); TableSyncCooldown = mod.BindLocal("Cartography Table", "Auto Sync Cooldown", 60f, "Seconds between automatic syncs of the same table while you stay in reach. The sync key ignores this."); RecordEnabled = mod.BindLocal("Recording", "Enabled", defaultValue: true, "While the pocket map is out, automatically record things you have found. Nothing is ever recorded that you did not look at or interact with yourself."); RecordRadius = mod.BindLocal("Recording", "Record Range", 0f, "0 (default): taking the map out writes down everything you have found recently, wherever you are now. Otherwise only finds within this many metres of you are written down."); RecordDwell = mod.BindLocal("Recording", "Record Dwell", 3f, "Seconds the map must be out before it starts recording."); FoundMemoryMinutes = mod.BindLocal("Recording", "Found Memory Minutes", 30f, "How long your character remembers something found but not yet written down. Seeing it again restarts the clock. The memory is saved with the character, so a relog inside the window does not lose it. 0 = never forget."); LookDwell = mod.BindLocal("Recording", "Look Dwell", 0.75f, "Seconds you must keep looking at something for it to count as found. Things under the crosshair within interaction range, and anything you interact with, count immediately."); Category[] all = Categories.All; foreach (Category category in all) { string text = Categories.Label(category); CategoryEnabled[category] = mod.BindLocal("Recording", "Record " + text, Categories.DefaultEnabled(category), "Record " + text.ToLowerInvariant() + " you have found." + ((category == Category.Structure) ? " Off by default: useful if you like to track which ruins and abandoned houses you have already searched (click a marker on the map to cross it off)." : "")); MarkerSpacing[category] = mod.BindLocal("Recording", text + " Marker Spacing", Categories.DefaultSpacing(category), "Do not record " + text.ToLowerInvariant() + " if a marker with the same icon already exists within this many metres. Small values give one icon per plant so a clump shows how many there are. The find stays pending and is written once that marker is gone."); LabelSpacing[category] = mod.BindLocal("Recording", text + " Label Spacing", Categories.DefaultLabelSpacing(category), "Text labels on recorded " + text.ToLowerInvariant() + " markers: -1 = never (the icon says it all), 0 = always, or a distance in metres so a clump gets one label (a new marker is icon-only when a marker with the same icon and name that already has a label lies within that distance)."); LookDistance[category] = mod.BindLocal("Recording", text + " Look Distance", Categories.DefaultLookDistance(category), "How far away " + text.ToLowerInvariant() + " can be and still count as seen when you look straight at them with clear line of sight. Interacting, or having them under the crosshair within reach, always counts."); MarkerSize[category] = mod.BindLocalRange("Recording", text + " Marker Size", Categories.DefaultSize(category), 20, 100, "Size of recorded " + text.ToLowerInvariant() + " markers on the map, as a percentage of the normal marker size."); ShowOnMinimap[category] = mod.BindLocal("Recording", text + " On Minimap", defaultValue: true, "Show recorded " + text.ToLowerInvariant() + " markers on the small minimap (when they are shown at all)."); ShowKind[category] = mod.BindLocal("Display", "Show " + text, defaultValue: true, "Draw recorded " + text.ToLowerInvariant() + " markers on your map. Off hides them on both the large map and the minimap; they stay on your map and keep syncing. To hide single icons instead (say only dandelions) use Hidden Icons."); if (Categories.UsesPrefabList(category)) { CategoryPrefabs[category] = mod.BindLocal("Catalog", text, Categories.DefaultPrefabs(category), "Comma-separated prefab names that count as " + text.ToLowerInvariant() + ". Prefab=Display Name overrides the marker text; add |Icon (an item prefab name, or pin:) to override the icon. Without |Icon, plants use the icon of the item they give and deposits the icon of what they drop. " + Categories.CatalogNote(category)); } CategoryIcon[category] = mod.BindLocal("Icons", text, Categories.DefaultIcon(category), "Fallback icon for " + text.ToLowerInvariant() + " markers when the thing's own item icon cannot be worked out: an item prefab name (its inventory icon is used) or pin: such as pin:Icon0, pin:Memorial, pin:Boss."); } StructuresIncludeUnlisted = mod.BindLocal("Catalog", "Structures Include Unlisted", defaultValue: true, "Treat any outdoor location that is not listed under another kind as a structure (the location's prefab name, tidied up, becomes the marker text). Turn off to record only the listed structure prefixes."); StructuresExcludePrefixes = mod.BindLocal("Catalog", "Structures Exclude Prefixes", "Vegvisir_,Runestone_,Meteorite,TarPit,Rock,Hugin,StartTemple,Pickable,Vegetation,Tree,Bush", "Comma-separated prefab name prefixes never recorded as structures."); ApplyLabelRulesOnSync = mod.BindLocal("Recording", "Apply Label Rules To Existing Markers", defaultValue: true, "After each sync, apply the label rules above to recorded markers that already exist: within each kind, the oldest marker of a same-named cluster keeps its label and the others lose theirs, for everyone. Labels are only ever removed, never added back. The console command tgm_relabel does the same on demand."); CrossOffStructuresOnChest = mod.BindLocal("Recording", "Cross Off Structures When Searched", defaultValue: true, "Opening a chest inside a structure crosses its marker off for everyone. If the structure has no marker yet, it is remembered as searched and its marker starts crossed off when it is recorded."); foreach (ConfigEntry value in CategoryPrefabs.Values) { value.SettingChanged += delegate { Catalog.Invalidate(); }; } StructuresExcludePrefixes.SettingChanged += delegate { Catalog.Invalidate(); }; ServerAutosaveMinutes = mod.BindLocal("Server", "Server Autosave Minutes", 0f, "Server only. Extra world save every this many minutes on top of vanilla's own autosave (0 = vanilla only). Worth setting on hosts whose panel stop kills the server without saving. A file named save-now in BepInEx/config/TheGreatestMap/ also makes the server save at once (used by deploy scripts)."); ShowMapInHands = mod.BindLocal("Visuals", "Show Map In Hands", defaultValue: true, "Show a parchment map in the left hand and a pencil in the right while the pocket map is out (visible to other players too)."); MapPose = mod.BindLocal("Visuals", "Map Pose", 0, "Animator 'crafting' state to play while the map is out (0 = none). 1 is the hand-crafting pose; experimental, may look odd while moving."); MapViewFraction = mod.BindLocal("Visuals", "Map View Fraction", 0.12f, "How much of the world map the parchment shows around you (fraction of the full map per side)."); MapOffset = mod.BindLocal("Visuals", "Map Offset", "0,0.08,0.02", "Local position (x,y,z) of the parchment relative to the left hand bone."); MapRotation = mod.BindLocal("Visuals", "Map Rotation", "0,90,0", "Local rotation (euler x,y,z) of the parchment relative to the left hand bone."); MapScale = mod.BindLocal("Visuals", "Map Scale", "0.28,0.2,0.004", "Local scale (x,y,z) of the parchment."); PencilItem = mod.BindLocal("Visuals", "Pencil Item", "Club", "Vanilla item whose held model is shown, scaled down, as the pencil in the right hand. It is placed exactly the way the game places that item when held, so it sits in the grip correctly. Any held item prefab works, e.g. Club, KnifeFlint, Torch."); PencilSize = mod.BindLocal("Visuals", "Pencil Size", "0.25,0.25,0.25", "Scale (x,y,z) applied to the pencil model."); PencilPositionTweak = mod.BindLocal("Visuals", "Pencil Position Tweak", "0,0,0", "Extra local offset (x,y,z) for the pencil on top of the vanilla hand placement."); PencilRotationTweak = mod.BindLocal("Visuals", "Pencil Rotation Tweak", "0,0,0", "Extra local rotation (euler x,y,z) for the pencil on top of the vanilla hand placement."); } internal static Vector3 ParseVector(string s, Vector3 fallback) { //IL_0008: 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_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(s)) { return fallback; } string[] array = s.Split(new char[1] { ',' }); if (array.Length != 3) { return fallback; } if (float.TryParse(array[0].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result) && float.TryParse(array[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result2) && float.TryParse(array[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result3)) { return new Vector3(result, result2, result3); } return fallback; } } [BepInPlugin("DeathMonger.TheGreatestMap", "The Greatest Map", "0.2.1")] public class TheGreatestMapMod : BaseUnityPlugin { public const string ModGuid = "DeathMonger.TheGreatestMap"; public const string ModName = "The Greatest Map"; public const string ModVersion = "0.2.1"; public const string MinCompatibleVersion = "0.2.0"; internal static ConfigEntry ModEnabled; private readonly Harmony _harmony = new Harmony("DeathMonger.TheGreatestMap"); private static ConfigSync _configSync; internal static TheGreatestMapMod Instance { get; private set; } internal static ManualLogSource Log { get; private set; } private void Awake() { Instance = this; Log = ((BaseUnityPlugin)this).Logger; ModEnabled = ((BaseUnityPlugin)this).Config.Bind("General", "Mod Enabled", true, "Master toggle for the entire mod. Set to false to disable every patch, the pocket map, pin sharing, auto-recording and the console commands without removing the DLL. Not server-synced. Requires a game restart to take effect."); if (!ModEnabled.Value) { Log.LogInfo((object)"[TheGreatestMap] Mod Enabled = false in config; skipping patches and commands."); return; } _configSync = new ConfigSync("DeathMonger.TheGreatestMap") { DisplayName = "The Greatest Map", CurrentVersion = "0.2.1", MinimumRequiredVersion = "0.2.0" }; TgmConfig.Bind(this); Commands.Register(); _harmony.PatchAll(); Log.LogInfo((object)"[TheGreatestMap] 0.2.1 loaded."); } private void Update() { if (ModEnabled.Value) { PinStore.Update(); ServerSave.Update(); if (!((Object)(object)Player.m_localPlayer == (Object)null)) { PocketMap.Update(); DiscoveryLedger.Update(); Recorder.Update(); TableSync.Update(); SyncEngine.Update(); } } } private void OnDestroy() { _harmony.UnpatchSelf(); } internal ConfigEntry BindSynced(string section, string key, T defaultValue, string description) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown ConfigEntry val = ((BaseUnityPlugin)this).Config.Bind(section, key, defaultValue, new ConfigDescription(description + " [Synced with Server]", (AcceptableValueBase)null, Array.Empty())); _configSync.AddConfigEntry(val).SynchronizedConfig = true; return val; } internal ConfigEntry BindLocal(string section, string key, T defaultValue, string description) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown return ((BaseUnityPlugin)this).Config.Bind(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty())); } internal ConfigEntry BindLocalRange(string section, string key, int defaultValue, int min, int max, string description) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown return ((BaseUnityPlugin)this).Config.Bind(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange(min, max), Array.Empty())); } internal static void Message(string text) { if (TgmConfig.ShowMessages != null && TgmConfig.ShowMessages.Value && !((Object)(object)MessageHud.instance == (Object)null)) { MessageHud.instance.ShowMessage((MessageType)1, text, 0, (Sprite)null, false, true); } } } }