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.Security; using System.Security.Permissions; using System.Text; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; using WingsoftheValkyrie.VFX; [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("WingsoftheValkyrie")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Valheim Wings of the Valkyrie Mod")] [assembly: AssemblyFileVersion("2.2.2.0")] [assembly: AssemblyInformationalVersion("2.2.2+b00be47ed25ba9a6d38606bc33109cde738e1213")] [assembly: AssemblyProduct("WingsoftheValkyrie")] [assembly: AssemblyTitle("WingsoftheValkyrie")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.2.2.0")] [module: UnverifiableCode] [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 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_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01e3: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3) { return; } bool flag = false; VersionCheck[] failedClient = GetFailedClient(); if (failedClient.Length != 0) { string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error())); TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + text; flag = true; } foreach (KeyValuePair item in notProcessedNames.OrderBy((KeyValuePair kv) => kv.Key)) { if (!__instance.m_connectionFailedError.text.Contains(item.Key)) { TMP_Text connectionFailedError2 = __instance.m_connectionFailedError; connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed."; flag = true; } } if (flag) { RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; __instance.m_connectionFailedError.ForceMeshUpdate(false, false); float num = __instance.m_connectionFailedError.renderedHeight + 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 WingsoftheValkyrie { internal static class AzuEpiCompat { public const string Guid = "Azumatt.AzuExtendedPlayerInventory"; private const string TrinketSlotName = "$azu_epi_trinket"; private const string BackSlotName = "$azu_epi_shoulder"; private static MethodInfo _tryGetSlotIndexByName; private static MethodInfo _tryGetSlotIndexAtGridPos; public static bool Active { get; private set; } public static void Init(Harmony harmony) { //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Expected O, but got Unknown //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_01e3: Expected O, but got Unknown //IL_01e3: Expected O, but got Unknown if (harmony == null || !Chainloader.PluginInfos.ContainsKey("Azumatt.AzuExtendedPlayerInventory")) { return; } try { Type type = AccessTools.TypeByName("AzuEPI.API"); MethodInfo methodInfo = ((type == null) ? null : AccessTools.Method(type, "SlotValidates", new Type[2] { typeof(int), typeof(ItemData) }, (Type[])null)); _tryGetSlotIndexByName = ((type == null) ? null : AccessTools.Method(type, "TryGetSlotIndexByName", new Type[3] { typeof(string), typeof(int).MakeByRefType(), typeof(bool) }, (Type[])null)); _tryGetSlotIndexAtGridPos = ((type == null) ? null : AccessTools.Method(type, "TryGetSlotIndexAtGridPos", new Type[3] { typeof(Inventory), typeof(Vector2i), typeof(int).MakeByRefType() }, (Type[])null)); if (methodInfo == null || _tryGetSlotIndexByName == null) { Log.LogWarning("AzuExtendedPlayerInventory is loaded but its slot API is not the one this build knows (2.5.x), so the wings' trinket-slot compatibility is off. Its layout repair may move wings worn as a trinket out of its trinket cell."); return; } harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(AzuEpiCompat), "SlotValidatesPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); MethodInfo methodInfo2 = AccessTools.Method(typeof(InventoryGrid), "DropItem", new Type[4] { typeof(Inventory), typeof(ItemData), typeof(int), typeof(Vector2i) }, (Type[])null); if (_tryGetSlotIndexAtGridPos != null && methodInfo2 != null) { harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(AzuEpiCompat), "DropItemPrefix", (Type[])null) { priority = 200 }, new HarmonyMethod(typeof(AzuEpiCompat), "DropItemPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } Active = true; Log.LogInfo("AzuExtendedPlayerInventory found: its trinket cell takes the wings whenever WingsSlot allows it, and a drag onto its trinket or back cell chooses the slot."); } catch (Exception ex) { Log.LogWarning("Could not bind to AzuExtendedPlayerInventory (" + ex.Message + "); the wings' trinket-slot compatibility is off."); } } private static int SlotIndex(string originalName) { if (_tryGetSlotIndexByName == null) { return -1; } try { object[] array = new object[3] { originalName, -1, true }; return ((bool)_tryGetSlotIndexByName.Invoke(null, array)) ? ((int)array[1]) : (-1); } catch { return -1; } } private static int SlotIndexAt(Inventory inventory, Vector2i pos) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) if (_tryGetSlotIndexAtGridPos == null || inventory == null) { return -1; } try { object[] array = new object[3] { inventory, pos, -1 }; return ((bool)_tryGetSlotIndexAtGridPos.Invoke(null, array)) ? ((int)array[2]) : (-1); } catch { return -1; } } private static void SlotValidatesPostfix(int slotIndex, ItemData item, ref bool __result) { if (!__result && slotIndex >= 0 && WingsItem.IsWings(item) && slotIndex == SlotIndex("$azu_epi_trinket")) { __result = WingsSlot.MayUseTrinketSlot(item); } } private static void DropItemPrefix(InventoryGrid __instance, ItemData item, Vector2i pos, bool __runOriginal) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (!__runOriginal || !WingsItem.IsWings(item) || (Object)(object)Player.m_localPlayer == (Object)null) { return; } Inventory inventory = ((Humanoid)Player.m_localPlayer).GetInventory(); if (inventory == null || __instance.GetInventory() != inventory) { return; } int num = SlotIndexAt(inventory, pos); if (num >= 0) { if (num == SlotIndex("$azu_epi_trinket")) { WingsSlot.NoteDragTarget(item, WingsSlotChoice.Trinket); } else if (num == SlotIndex("$azu_epi_shoulder")) { WingsSlot.NoteDragTarget(item, WingsSlotChoice.Back); } } } private static void DropItemPostfix(ItemData item, bool __result) { if (!__result && WingsItem.IsWings(item)) { WingsSlot.ForgetDragTarget(item); } } } [HarmonyPatch] public static class CapeVisualPatch { private static readonly FieldRef> ShoulderInstancesRef = ReflectionUtil.TryFieldRef>("m_shoulderItemInstances"); private static readonly FieldRef> TrinketInstancesRef = ReflectionUtil.TryFieldRef>("m_trinketItemInstances"); [HarmonyPatch(typeof(VisEquipment), "AttachArmor")] [HarmonyPrefix] public static bool AttachArmorPrefix(int itemHash, ref List __result) { if (!WingsItem.IsWingsHash(itemHash)) { return true; } __result = new List(); return false; } [HarmonyPatch(typeof(VisEquipment), "SetShoulderEquipped")] [HarmonyPostfix] [HarmonyPriority(0)] public static void SetShoulderEquippedPostfix(VisEquipment __instance, int hash) { HideInstances(ShoulderInstancesRef, __instance, hash); } [HarmonyPatch(typeof(VisEquipment), "SetTrinketEquipped")] [HarmonyPostfix] [HarmonyPriority(0)] public static void SetTrinketEquippedPostfix(VisEquipment __instance, int hash) { HideInstances(TrinketInstancesRef, __instance, hash); } private static void HideInstances(FieldRef> instancesRef, VisEquipment visEq, int hash) { if (instancesRef == null || !WingsItem.IsWingsHash(hash)) { return; } List list = instancesRef.Invoke(visEq); if (list == null) { return; } for (int i = 0; i < list.Count; i++) { if ((Object)(object)list[i] != (Object)null) { list[i].SetActive(false); } } } } public static class ConfigMigration { public sealed class Rebase { public string Section; public string Key; public string[] OldDefaults; } public const int CurrentConfigVersion = 3; private static readonly Dictionary Rebases = new Dictionary { { 1, new Rebase[9] { new Rebase { Section = "2. Crude Wings", Key = "MinStationLevel", OldDefaults = new string[1] { "1" } }, new Rebase { Section = "2. Crude Wings", Key = "CraftingRequirements", OldDefaults = new string[1] { "Feathers:10,LeatherScraps:10" } }, new Rebase { Section = "3. Troll Wings", Key = "MinStationLevel", OldDefaults = new string[1] { "2" } }, new Rebase { Section = "3. Troll Wings", Key = "CraftingRequirements", OldDefaults = new string[1] { "TrollHide:5,Feathers:15" } }, new Rebase { Section = "4. Lox Wings", Key = "MinStationLevel", OldDefaults = new string[1] { "1" } }, new Rebase { Section = "4. Lox Wings", Key = "CraftingRequirements", OldDefaults = new string[1] { "LoxPelt:5,Silver:5" } }, new Rebase { Section = "5. Dragon Wings", Key = "CraftingRequirements", OldDefaults = new string[1] { "Feathers:20,Eitr:5" } }, new Rebase { Section = "6. Valkyrie Flight Skill", Key = "XpPerFlap", OldDefaults = new string[1] { "0.5" } }, new Rebase { Section = "6. Valkyrie Flight Skill", Key = "XpPerGlideSecond", OldDefaults = new string[1] { "0.25" } } } }, { 2, new Rebase[20] { new Rebase { Section = "2. Crude Wings", Key = "FlightCeiling", OldDefaults = new string[1] { "120" } }, new Rebase { Section = "2. Crude Wings", Key = "GlideSpeed", OldDefaults = new string[1] { "10" } }, new Rebase { Section = "2. Crude Wings", Key = "FlapForce", OldDefaults = new string[1] { "15" } }, new Rebase { Section = "2. Crude Wings", Key = "FlapStaminaCost", OldDefaults = new string[1] { "10" } }, new Rebase { Section = "3. Troll Wings", Key = "FlightCeiling", OldDefaults = new string[1] { "135" } }, new Rebase { Section = "3. Troll Wings", Key = "GlideSpeed", OldDefaults = new string[1] { "15" } }, new Rebase { Section = "3. Troll Wings", Key = "FlapForce", OldDefaults = new string[1] { "18" } }, new Rebase { Section = "3. Troll Wings", Key = "FlapStaminaCost", OldDefaults = new string[1] { "8" } }, new Rebase { Section = "4. Lox Wings", Key = "FlightCeiling", OldDefaults = new string[1] { "160" } }, new Rebase { Section = "4. Lox Wings", Key = "GlideSpeed", OldDefaults = new string[1] { "20" } }, new Rebase { Section = "4. Lox Wings", Key = "FlapForce", OldDefaults = new string[1] { "22" } }, new Rebase { Section = "4. Lox Wings", Key = "FlapStaminaCost", OldDefaults = new string[1] { "6" } }, new Rebase { Section = "5. Dragon Wings", Key = "FlightCeiling", OldDefaults = new string[1] { "1100" } }, new Rebase { Section = "5. Dragon Wings", Key = "GlideSpeed", OldDefaults = new string[1] { "30" } }, new Rebase { Section = "5. Dragon Wings", Key = "FlapForce", OldDefaults = new string[1] { "28" } }, new Rebase { Section = "5. Dragon Wings", Key = "FlapStaminaCost", OldDefaults = new string[1] { "4" } }, new Rebase { Section = "6. Valkyrie Flight Skill", Key = "StaminaReductionAtMax", OldDefaults = new string[1] { "0.5" } }, new Rebase { Section = "6. Valkyrie Flight Skill", Key = "FlapPowerBonusAtMax", OldDefaults = new string[1] { "0.3" } }, new Rebase { Section = "6. Valkyrie Flight Skill", Key = "GlideSinkReductionAtMax", OldDefaults = new string[1] { "0.5" } }, new Rebase { Section = "6. Valkyrie Flight Skill", Key = "GlideSpeedBonusAtMax", OldDefaults = new string[1] { "0.15" } } } }, { 3, new Rebase[2] { new Rebase { Section = "2. Crude Wings", Key = "MinStationLevel", OldDefaults = new string[1] { "3" } }, new Rebase { Section = "3. Troll Wings", Key = "MinStationLevel", OldDefaults = new string[1] { "3" } } } } }; private static readonly Dictionary Snapshot = new Dictionary(StringComparer.OrdinalIgnoreCase); private static readonly List Pending = new List(); private static int _fileVersion; private static string Slot(string section, string key) { return section + "::" + key; } public static void Begin(ConfigFile config) { Snapshot.Clear(); Pending.Clear(); _fileVersion = 3; try { string configFilePath = config.ConfigFilePath; if (File.Exists(configFilePath)) { ReadRaw(configFilePath, Snapshot); _fileVersion = ReadStampedVersion(Snapshot); if (_fileVersion < 3) { Backup(configFilePath, _fileVersion); Log.LogWarning($"Migrating {Path.GetFileName(configFilePath)} from config version {_fileVersion} to {3}. Values you changed are kept; values still at their old defaults move to the new ones. The previous file is backed up beside it."); PlanRebases(); } } } catch (Exception arg) { Log.LogError($"Config migration could not start, settings will be read as-is. Reason: {arg}"); } } private static void PlanRebases() { //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Expected O, but got Unknown for (int i = _fileVersion + 1; i <= 3; i++) { if (!Rebases.TryGetValue(i, out var value)) { continue; } Rebase[] array = value; foreach (Rebase rebase in array) { if (!Snapshot.TryGetValue(Slot(rebase.Section, rebase.Key), out var value2)) { continue; } bool flag = false; string[] oldDefaults = rebase.OldDefaults; foreach (string b in oldDefaults) { if (string.Equals(value2.Trim(), b, StringComparison.Ordinal)) { flag = true; break; } } if (flag) { Pending.Add(new ConfigDefinition(rebase.Section, rebase.Key)); Log.LogInfo("[" + rebase.Section + "] " + rebase.Key + " was still the old default; moving it to the new default."); } else { Log.LogInfo("[" + rebase.Section + "] " + rebase.Key + " was customised ('" + value2 + "'); keeping your value."); } } } } public static void Finish(ConfigFile config, ConfigEntry versionEntry) { try { foreach (ConfigDefinition item in Pending) { if (config.ContainsKey(item)) { ConfigEntryBase obj = config[item]; obj.BoxedValue = obj.DefaultValue; } } if (versionEntry != null) { versionEntry.Value = 3; } config.Save(); } catch (Exception arg) { Log.LogError($"Config migration could not finish - check the backup beside your config file. Reason: {arg}"); } finally { Snapshot.Clear(); Pending.Clear(); } } private static void Backup(string path, int fromVersion) { try { File.Copy(path, path + $".v{fromVersion}.bak", overwrite: true); } catch (Exception ex) { Log.LogError("Could not back up the config before migrating (" + ex.Message + "). Migrating anyway."); } } private static int ReadStampedVersion(Dictionary snapshot) { if (snapshot.TryGetValue(Slot("0. Meta", "ConfigVersion"), out var value) && int.TryParse(value, out var result)) { return result; } return 0; } private static void ReadRaw(string path, Dictionary into) { string section = ""; string[] array = File.ReadAllLines(path); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.Length == 0 || text[0] == '#') { continue; } if (text[0] == '[' && text[text.Length - 1] == ']') { section = text.Substring(1, text.Length - 2).Trim(); continue; } int num = text.IndexOf('='); if (num > 0) { string text2 = text.Substring(0, num).Trim(); string value = text.Substring(num + 1).Trim(); if (text2.Length != 0) { into[Slot(section, text2)] = value; } } } } } [HarmonyPatch(typeof(Player))] public static class FlightController { private static readonly int ZdoGliding = StringExtensionMethods.GetStableHashCode("wotv_gliding"); private static readonly int ZdoFlapCount = StringExtensionMethods.GetStableHashCode("wotv_flapcount"); private static readonly int ZdoWings = StringExtensionMethods.GetStableHashCode("wotv_wings"); [HarmonyPatch("Update")] [HarmonyPostfix] public static void UpdatePostfix(Player __instance) { //IL_0070: Unknown result type (might be due to invalid IL or missing references) if (!ModConfig.EnableMod.Value) { return; } try { RuneWingVFX runeWingVFX = ((Component)__instance).GetComponent(); if ((Object)(object)runeWingVFX == (Object)null) { runeWingVFX = ((Component)__instance).gameObject.AddComponent(); } bool flag = (Object)(object)__instance == (Object)(object)Player.m_localPlayer; if (flag) { WingsSlot.Tick(__instance); } string text = (flag ? WingsItem.GetEquippedWingsName(__instance) : ReadRemoteWings(__instance, runeWingVFX)); if (text == null) { runeWingVFX.IsGlidingLocal = false; if (flag) { FlightLog.Tick(__instance, gliding: false, null, Time.deltaTime); } } else { runeWingVFX.SetTierColor(GetTierColor(text)); if (flag) { UpdateLocalGlide(__instance, runeWingVFX, text); FlyingSkill.AccumulateGlideXP(__instance, runeWingVFX.IsGlidingLocal, Time.deltaTime); FlightLog.Tick(__instance, runeWingVFX.IsGlidingLocal, text, Time.deltaTime); } else { ReadRemoteState(__instance, runeWingVFX); } } if (flag) { PublishState(runeWingVFX, text); } runeWingVFX.SetGlidingState(runeWingVFX.IsGlidingLocal); } catch (Exception ex) { Log.LogWarning("Error in UpdatePostfix for " + ((__instance != null) ? __instance.GetPlayerName() : null) + ": " + ex.Message); } } private static Color GetTierColor(string wingsName) { //IL_0029: 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) //IL_0053: 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) return (Color)(wingsName switch { "WingsOf_Troll" => Color.cyan, "WingsOf_Lox" => new Color(0.8f, 0.8f, 1f), "WingsOf_Dragon" => new Color(0.8f, 0.1f, 1f), _ => Color.green, }); } private static void UpdateLocalGlide(Player player, RuneWingVFX vfx, string wingsName) { //IL_0154: 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) if (((Character)player).IsOnGround() || ((Character)player).IsSwimming() || ((Character)player).InWater() || (Object)(object)((Character)player).GetStandingOnShip() != (Object)null || ((Character)player).IsAttachedToShip()) { vfx.IsGlidingLocal = false; return; } if (ValkyrieInput.JumpPressed(player)) { WingStats stats = ModConfig.GetStats(wingsName, WingsItem.GetEquippedWingsQuality(player)); if (FlyingSkill.IsAvailable && FlyingSkill.Level(player) < stats.MinSkillToFlap) { vfx.IsGlidingLocal = true; FlightLog.NoteSkillDenied(); ((Character)player).Message((MessageType)2, $"These wings will not beat for you yet - Valkyrie Flight {Mathf.RoundToInt(stats.MinSkillToFlap)} required. Glide to learn.", 0, (Sprite)null, false); } else { float num = stats.FlapStaminaCost * (1f - ModConfig.SkillStaminaReduction.Value * FlyingSkill.Factor(player)); if (((Character)player).HaveStamina(num)) { ((Character)player).UseStamina(num); FlyingSkill.AddFlapXP(player); FlightLog.NoteFlap(); vfx.TriggerFlap(); vfx.WantsToFlap = true; vfx.FlapCount++; } else { FlightLog.NoteStaminaDenied(); ((Character)player).Message((MessageType)2, "Not enough stamina to flap!", 0, (Sprite)null, false); } } } if (!vfx.IsGlidingLocal) { bool flag = ((Character)player).InNumShipVolumes > 0; if (vfx.WantsToFlap || (!flag && ((Character)player).GetVelocity().y < -5f)) { vfx.IsGlidingLocal = true; } } if (vfx.IsGlidingLocal) { Traverse.Create((object)player).Field("m_maxAirAltitude").SetValue((object)((Component)player).transform.position.y); } } private static void PublishState(RuneWingVFX vfx, string wingsName) { ZNetView nView = vfx.NView; if ((Object)(object)nView == (Object)null || !nView.IsValid() || !nView.IsOwner()) { return; } ZDO zDO = nView.GetZDO(); if (zDO != null) { if (zDO.GetBool(ZdoGliding, false) != vfx.IsGlidingLocal) { zDO.Set(ZdoGliding, vfx.IsGlidingLocal); } if (zDO.GetInt(ZdoFlapCount, 0) != vfx.FlapCount) { zDO.Set(ZdoFlapCount, vfx.FlapCount, false); } int hashFromWingsName = WingsItem.GetHashFromWingsName(wingsName); int num = default(int); if (!zDO.GetInt(ZdoWings, ref num) || num != hashFromWingsName) { zDO.Set(ZdoWings, hashFromWingsName, false); } } } private static string ReadRemoteWings(Player player, RuneWingVFX vfx) { ZNetView nView = vfx.NView; ZDO val = (((Object)(object)nView != (Object)null && nView.IsValid()) ? nView.GetZDO() : null); int hash = default(int); if (val != null && val.GetInt(ZdoWings, ref hash)) { return WingsItem.GetWingsNameFromHash(hash); } return WingsItem.GetVisualWingsName(player); } private static void ReadRemoteState(Player player, RuneWingVFX vfx) { //IL_006b: Unknown result type (might be due to invalid IL or missing references) ZNetView nView = vfx.NView; ZDO val = (((Object)(object)nView != (Object)null && nView.IsValid()) ? nView.GetZDO() : null); bool isGlidingLocal = default(bool); if (val == null || !val.GetBool(ZdoGliding, ref isGlidingLocal)) { isGlidingLocal = !((Character)player).IsOnGround() && !((Character)player).IsSwimming() && !((Character)player).InWater() && (Object)(object)((Character)player).GetStandingOnShip() == (Object)null && !((Character)player).IsAttachedToShip() && ((Character)player).InNumShipVolumes == 0 && Mathf.Abs(((Character)player).GetVelocity().y) > 2f; vfx.IsGlidingLocal = isGlidingLocal; return; } vfx.IsGlidingLocal = isGlidingLocal; int num = val.GetInt(ZdoFlapCount, 0); if (vfx.LastSeenFlapCount == int.MinValue) { vfx.LastSeenFlapCount = num; } else if (num != vfx.LastSeenFlapCount) { vfx.LastSeenFlapCount = num; vfx.TriggerFlap(); } } [HarmonyPatch("FixedUpdate")] [HarmonyPostfix] public static void FixedUpdatePostfix(Player __instance) { //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: 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_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_021c: 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_0232: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_0244: 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_0278: Unknown result type (might be due to invalid IL or missing references) //IL_028a: Unknown result type (might be due to invalid IL or missing references) //IL_029d: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || !ModConfig.EnableMod.Value) { return; } try { RuneWingVFX component = ((Component)__instance).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsGlidingLocal || ((Character)__instance).IsOnGround() || ((Character)__instance).IsSwimming() || ((Character)__instance).InWater() || !((Object)(object)((Character)__instance).GetStandingOnShip() == (Object)null) || ((Character)__instance).IsAttachedToShip()) { return; } Rigidbody component2 = ((Component)__instance).GetComponent(); if (!((Object)(object)component2 != (Object)null)) { return; } ItemData equippedWings = WingsItem.GetEquippedWings(__instance); WingStats stats = ModConfig.GetStats((equippedWings != null) ? WingsItem.GetWingsNameFromHash(StringExtensionMethods.GetStableHashCode(((Object)equippedWings.m_dropPrefab).name)) : null, equippedWings?.m_quality ?? 1); float num = FlyingSkill.Factor(__instance); float num2 = stats.GlideSpeed * (1f + ModConfig.SkillGlideSpeedBonus.Value * num); float num3 = stats.FlapForce * (1f + ModConfig.SkillFlapPowerBonus.Value * num); float num4 = (FlyingSkill.IsAvailable ? (stats.FlightCeiling * Mathf.Lerp(ModConfig.CeilingAtNovice.Value, 1f, num)) : stats.FlightCeiling); if (component.WantsToFlap) { component2.linearVelocity = new Vector3(component2.linearVelocity.x, num3, component2.linearVelocity.z); component.WantsToFlap = false; } else { Vector3 lookDir = ((Character)__instance).GetLookDir(); float num5 = (0f - ModConfig.BaseGlideSinkRate.Value) * (1f - ModConfig.SkillGlideSinkReduction.Value * num); float num6 = num5; if (lookDir.y < 0f) { num6 = Mathf.Lerp(num5, 0f - ModConfig.MaxDiveSpeed.Value, 0f - lookDir.y); } if (component2.linearVelocity.y < num6) { component2.linearVelocity = new Vector3(component2.linearVelocity.x, num6, component2.linearVelocity.z); } } Vector3 value = Traverse.Create((object)__instance).Field("m_moveDir").GetValue(); if (((Vector3)(ref value)).magnitude > 0.1f) { Vector3 val = value * num2; val.y = component2.linearVelocity.y; component2.linearVelocity = Vector3.Lerp(component2.linearVelocity, val, 3f * Time.fixedDeltaTime); } if ((Object)(object)ZoneSystem.instance != (Object)null) { float groundHeight = ZoneSystem.instance.GetGroundHeight(((Component)__instance).transform.position); if (((Component)__instance).transform.position.y - groundHeight > num4 && component2.linearVelocity.y > 0f) { component2.linearVelocity = new Vector3(component2.linearVelocity.x, 0f, component2.linearVelocity.z); } } } catch (Exception ex) { Log.LogWarning("Error in FixedUpdatePostfix for " + ((__instance != null) ? __instance.GetPlayerName() : null) + ": " + ex.Message); } } } public static class FlightLog { private const string CustomDataKey = "wubarrk.wotv.flightlog"; private const float MinTrackedSpeed = 0.1f; private const float ImplausibleSpeed = 200f; private const float AltitudeSampleInterval = 0.25f; private const float InFlightFlushInterval = 10f; private static FlightSaga _saga = new FlightSaga(); private static string _loadedFor; private static Player _boundPlayer; private static bool _airborne; private static float _currentFlightSeconds; private static float _currentFlightMeters; private static Vector3 _lastPosition; private static bool _hasLastPosition; private static float _altitudeSampleTimer; private static float _flushTimer; public static bool HasFlown => _saga.HasFlown; public static FlightSaga Saga => _saga; public static string OwnerName => _loadedFor; public static void LoadFrom(Player player) { Bind(player, force: true); } public static void EnsureLoaded(Player player) { Bind(player, force: false); } private static void Bind(Player player, bool force) { if ((Object)(object)player == (Object)null || (!force && _boundPlayer == player)) { return; } string playerName = player.GetPlayerName(); if (!force && _loadedFor == playerName) { _boundPlayer = player; return; } _saga = new FlightSaga(); _loadedFor = playerName; _boundPlayer = player; ResetFlightState(); _airborne = false; try { Dictionary customData = player.m_customData; if (customData != null && customData.TryGetValue("wubarrk.wotv.flightlog", out var value) && !string.IsNullOrEmpty(value)) { _saga = FlightSaga.Deserialize(value); } } catch (Exception ex) { _saga = new FlightSaga(); Log.LogWarning("Could not read the flight logbook for " + playerName + ", starting a fresh one. Reason: " + ex.Message); } } public static void Flush(Player player, bool force) { if ((Object)(object)player == (Object)null || !ModConfig.EnableFlightLog.Value || _loadedFor == null || _loadedFor != player.GetPlayerName()) { return; } _saga.SkillLevel = FlyingSkill.Level(player); try { Dictionary dictionary = player.m_customData; if (dictionary == null) { dictionary = (player.m_customData = new Dictionary()); } dictionary["wubarrk.wotv.flightlog"] = _saga.Serialize(); } catch (Exception ex) { Log.LogWarning("Could not store the flight logbook on your character. Reason: " + ex.Message); } FlightReport.ReportToServer(player, _saga, force); } public static void NoteFlap() { if (ModConfig.EnableFlightLog.Value) { _saga.Flaps++; } } public static void NoteStaminaDenied() { if (ModConfig.EnableFlightLog.Value) { _saga.StaminaDenials++; } } public static void NoteSkillDenied() { if (ModConfig.EnableFlightLog.Value) { _saga.SkillDenials++; } } public static void Tick(Player player, bool gliding, string wingsName, float deltaTime) { if (!((Object)(object)player == (Object)null) && ModConfig.EnableFlightLog.Value) { EnsureLoaded(player); if (gliding && !_airborne) { BeginFlight(player); } else if (!gliding && _airborne) { EndFlight(player); } if (!gliding) { _hasLastPosition = false; } else { Accumulate(player, wingsName, deltaTime); } } } private static void BeginFlight(Player player) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) _airborne = true; _currentFlightSeconds = 0f; _currentFlightMeters = 0f; _altitudeSampleTimer = 0f; _flushTimer = 0f; _lastPosition = ((Component)player).transform.position; _hasLastPosition = true; _saga.Flights++; long num = FlightSaga.UnixNow(); if (_saga.FirstFlightUnix == 0L) { _saga.FirstFlightUnix = num; } _saga.LastFlightUnix = num; } private static void EndFlight(Player player) { _airborne = false; if (_currentFlightSeconds > _saga.BestFlightSeconds) { _saga.BestFlightSeconds = _currentFlightSeconds; } if (_currentFlightMeters > _saga.BestFlightMeters) { _saga.BestFlightMeters = _currentFlightMeters; } _saga.LastFlightUnix = FlightSaga.UnixNow(); if (((Character)player).IsSwimming() || ((Character)player).InWater()) { _saga.LandingsWater++; } else if ((Object)(object)((Character)player).GetStandingOnShip() != (Object)null) { _saga.LandingsShip++; } else { _saga.LandingsGround++; } ResetFlightState(); Flush(player, force: false); } private static void Accumulate(Player player, string wingsName, float deltaTime) { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: 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_008b: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) if (deltaTime <= 0f) { return; } _currentFlightSeconds += deltaTime; _saga.TimeFlownSeconds += deltaTime; _saga.AddTierTime(wingsName, deltaTime); _flushTimer += deltaTime; if (_flushTimer >= 10f) { _flushTimer = 0f; Flush(player, force: false); } if (EnvMan.IsNight()) { _saga.NightSeconds += deltaTime; } Vector3 position = ((Component)player).transform.position; if (_hasLastPosition) { Vector3 val = position - _lastPosition; val.y = 0f; float magnitude = ((Vector3)(ref val)).magnitude; float num = magnitude / deltaTime; if (num >= 0.1f && num < 200f) { _saga.DistanceMeters += magnitude; _currentFlightMeters += magnitude; if (num > _saga.BestSpeed) { _saga.BestSpeed = num; } } } _lastPosition = position; _hasLastPosition = true; float num2 = 0f - ((Character)player).GetVelocity().y; if (num2 > _saga.BestDiveSpeed && num2 < 200f) { _saga.BestDiveSpeed = num2; } _altitudeSampleTimer += deltaTime; if (_altitudeSampleTimer >= 0.25f) { _altitudeSampleTimer = 0f; SampleAltitudeAndBiome(player, position); } } private static void SampleAltitudeAndBiome(Player player, Vector3 position) { //IL_0039: 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) //IL_003f: 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_0018: Unknown result type (might be due to invalid IL or missing references) //IL_004d: 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_0054: Expected I4, but got Unknown if ((Object)(object)ZoneSystem.instance != (Object)null) { float num = position.y - ZoneSystem.instance.GetGroundHeight(position); if (num > _saga.BestAltitude) { _saga.BestAltitude = num; } } Biome currentBiome = player.GetCurrentBiome(); if ((int)currentBiome != 0) { FlightSaga saga = _saga; saga.BiomeMask |= currentBiome; } } private static void ResetFlightState() { _currentFlightSeconds = 0f; _currentFlightMeters = 0f; _hasLastPosition = false; _altitudeSampleTimer = 0f; _flushTimer = 0f; } private static string Num(double value, int decimals) { return value.ToString("N" + decimals, CultureInfo.InvariantCulture); } public static List Report(Player player, bool includeOddities) { List list = new List(); if (!ModConfig.EnableFlightLog.Value) { list.Add("The flight logbook is switched off (see EnableFlightLog in the config)."); return list; } if (!HasFlown) { list.Add("Your logbook is empty. The sky is still waiting."); return list; } list.Add("=== The Flight Saga of " + (_loadedFor ?? "a nameless Viking") + " ==="); list.Add("Valkyrie Flight level : " + Num(FlyingSkill.Level(player), 1)); list.Add("Time flown : " + FlightSaga.Duration(_saga.TimeFlownSeconds)); list.Add("Distance flown : " + Num(_saga.DistanceMeters, 0) + " m"); list.Add("Flights : " + _saga.Flights.ToString(CultureInfo.InvariantCulture)); list.Add("Wingbeats : " + _saga.Flaps.ToString(CultureInfo.InvariantCulture)); list.Add("-- Records --"); list.Add("Highest above ground : " + Num(_saga.BestAltitude, 1) + " m"); list.Add("Longest single flight : " + FlightSaga.Duration(_saga.BestFlightSeconds) + " / " + Num(_saga.BestFlightMeters, 0) + " m"); list.Add("Fastest on the wing : " + Num(_saga.BestSpeed, 1) + " m/s"); list.Add("Steepest stoop : " + Num(_saga.BestDiveSpeed, 1) + " m/s straight down"); if (!includeOddities) { return list; } list.Add("-- Oddities --"); list.Add("Flown by night : " + FlightSaga.Duration(_saga.NightSeconds)); list.Add("Out of stamina midair : " + _saga.StaminaDenials.ToString(CultureInfo.InvariantCulture) + " times"); list.Add("Wings refused you : " + _saga.SkillDenials.ToString(CultureInfo.InvariantCulture) + " times (not skilled enough to flap)"); list.Add("Landed on solid ground: " + _saga.LandingsGround.ToString(CultureInfo.InvariantCulture)); list.Add("Landed in the drink : " + _saga.LandingsWater.ToString(CultureInfo.InvariantCulture)); list.Add("Landed on a ship : " + _saga.LandingsShip.ToString(CultureInfo.InvariantCulture)); List list2 = _saga.BiomesFlownOver(); list.Add("Biomes crossed : " + list2.Count + "/" + FlightSaga.BiomeCount + ((list2.Count > 0) ? (" (" + string.Join(", ", list2.ToArray()) + ")") : "")); list.Add("-- Time per tier --"); list.Add("Crude : " + FlightSaga.Duration(_saga.CrudeSeconds)); list.Add("Troll : " + FlightSaga.Duration(_saga.TrollSeconds)); list.Add("Lox : " + FlightSaga.Duration(_saga.LoxSeconds)); list.Add("Dragon : " + FlightSaga.Duration(_saga.DragonSeconds)); return list; } } public static class FlightLogCommand { [CompilerGenerated] private static class <>O { public static ConsoleEvent <0>__Run; } [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static ConsoleOptionsFetcher <>9__3_0; internal List b__3_0() { return Options; } } private const string Name = "wov"; private const string Help = "Wings of the Valkyrie. 'wov log' for your flight saga, 'wov oddities' for the strange corners of it, 'wov export' to write the logbook out as JSON, 'wov where' for that file's path, 'wov slot [back|trinket]' to see or choose which slot your wings go in."; private static readonly List Options = new List { "log", "oddities", "export", "where", "slot" }; public static void Register() { //IL_001a: 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_0025: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown object obj = <>O.<0>__Run; if (obj == null) { ConsoleEvent val = Run; <>O.<0>__Run = val; obj = (object)val; } object obj2 = <>c.<>9__3_0; if (obj2 == null) { ConsoleOptionsFetcher val2 = () => Options; <>c.<>9__3_0 = val2; obj2 = (object)val2; } new ConsoleCommand("wov", "Wings of the Valkyrie. 'wov log' for your flight saga, 'wov oddities' for the strange corners of it, 'wov export' to write the logbook out as JSON, 'wov where' for that file's path, 'wov slot [back|trinket]' to see or choose which slot your wings go in.", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)obj2, false, false, false); } private static void Run(ConsoleEventArgs args) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { Print(args, "No Viking to speak of - load a character first."); return; } FlightLog.EnsureLoaded(localPlayer); string text = ((args != null && args.Length > 1) ? args[1].ToLowerInvariant() : "log"); switch (text) { case "log": case "oddities": { foreach (string item in FlightLog.Report(localPlayer, text == "oddities")) { Print(args, item); } break; } case "export": { FlightLog.Flush(localPlayer, force: true); if (!ModConfig.PublishFlightStats.Value) { Print(args, "Flight statistics are switched off here - set PublishFlightStats to true in the config."); break; } if ((Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer()) { Print(args, "Sent your flight saga to the server. The server owns the statistics file - ask its admin, or run this on the server itself."); break; } string text2 = FlightReport.WriteExport(); Print(args, (text2 != null) ? ("Flight statistics written to " + text2) : "Could not write the flight statistics - see the log for why."); break; } case "where": Print(args, "Flight statistics file: " + FlightReport.ExportPath()); Print(args, "Your own saga lives on your character, not in that file."); break; case "slot": { string argument = ((args.Length > 2) ? args[2].ToLowerInvariant() : null); { foreach (string item2 in WingsSlot.Command(localPlayer, argument)) { Print(args, item2); } break; } } default: Print(args, "Unknown option '" + text + "'. Try: log, oddities, export, where, slot."); break; } } private static void Print(ConsoleEventArgs args, string line) { Terminal val = args?.Context; if ((Object)(object)val != (Object)null) { val.AddString(line); } else if ((Object)(object)Console.instance != (Object)null) { ((Terminal)Console.instance).AddString(line); } } } [HarmonyPatch(typeof(Player))] public static class FlightLogPatches { [HarmonyPatch("Load")] [HarmonyPostfix] public static void LoadPostfix(Player __instance) { if (ModConfig.EnableFlightLog.Value) { FlightLog.LoadFrom(__instance); } } [HarmonyPatch("OnSpawned")] [HarmonyPostfix] public static void OnSpawnedPostfix(Player __instance) { if (ModConfig.EnableFlightLog.Value && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer)) { FlightLog.EnsureLoaded(__instance); } } [HarmonyPatch("Save")] [HarmonyPrefix] public static void SavePrefix(Player __instance) { if (ModConfig.EnableFlightLog.Value) { FlightLog.Flush(__instance, force: true); } } } public static class FlightReport { private sealed class Row { public long PlayerId; public string Name; public FlightSaga Saga; } private sealed class Field { public string Name; public Func Value; public bool Integral; } private sealed class Subject { public string FileName; public string Holds; public Field[] Fields; public Action AppendExtra; } private sealed class Leader { public string Name; public double Value; } private const string RpcName = "WOTV_FlightSaga"; private const string ExportFolder = "WingsOfTheValkyrie"; private const string ExportFileName = "barrkbot_flight.json"; private const string RegistryFileName = "flight_registry.dat"; private static readonly Dictionary Rows = new Dictionary(); private static ZRoutedRpc _registeredOn; private static bool _registryLoaded; private static float _writeTimer; private static float _lastReportTime = float.NegativeInfinity; private const int RowBudgetChars = 2400; public static void Register() { ZRoutedRpc instance = ZRoutedRpc.instance; if (instance == null || _registeredOn == instance) { return; } try { instance.Register("WOTV_FlightSaga", (Action)OnSagaReceived); _registeredOn = instance; Rows.Clear(); _registryLoaded = false; _writeTimer = 0f; _lastReportTime = float.NegativeInfinity; } catch (Exception ex) { Log.LogWarning("Could not register the flight report RPC; flight stats will not reach the server. Reason: " + ex.Message); } } public static void ReportToServer(Player player, FlightSaga saga, bool force) { if ((Object)(object)player == (Object)null || saga == null || !ModConfig.PublishFlightStats.Value || !saga.HasFlown) { return; } Register(); float num = Mathf.Max(1f, ModConfig.FlightStatsReportInterval.Value); if (!force && Time.realtimeSinceStartup - _lastReportTime < num) { return; } _lastReportTime = Time.realtimeSinceStartup; try { long playerID = player.GetPlayerID(); string playerName = player.GetPlayerName(); string text = saga.Serialize(); if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer()) { Accept(playerID, playerName, text); return; } ZRoutedRpc instance = ZRoutedRpc.instance; if (instance != null) { ZNetPeer serverPeer = ZNet.instance.GetServerPeer(); if (serverPeer != null) { instance.InvokeRoutedRPC(serverPeer.m_uid, "WOTV_FlightSaga", new object[3] { playerID, playerName, text }); } } } catch (Exception ex) { Log.LogWarning("Could not send your flight stats to the server. Reason: " + ex.Message); } } private static void OnSagaReceived(long sender, long playerId, string name, string payload) { if (!((Object)(object)ZNet.instance != (Object)null) || ZNet.instance.IsServer()) { Accept(playerId, name, payload); } } private static void Accept(long playerId, string name, string payload) { try { if (playerId != 0L && !string.IsNullOrEmpty(payload)) { FlightSaga flightSaga = FlightSaga.Deserialize(payload); if (flightSaga.HasFlown) { EnsureRegistryLoaded(); Rows[playerId] = new Row { PlayerId = playerId, Name = (string.IsNullOrEmpty(name) ? "Unknown" : name), Saga = flightSaga }; } } } catch (Exception ex) { Log.LogWarning("Could not read a flight report. Reason: " + ex.Message); } } public static void Tick(float deltaTime) { if (ModConfig.PublishFlightStats.Value && !((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer()) { Register(); EnsureRegistryLoaded(); _writeTimer += deltaTime; if (!(_writeTimer < Mathf.Max(5f, ModConfig.FlightStatsWriteInterval.Value))) { _writeTimer = 0f; WriteExport(); } } } public static string ExportDirectory() { string value = ModConfig.FlightStatsExportFolder.Value; if (!string.IsNullOrEmpty(value)) { return value.Trim(); } return Path.Combine(Paths.ConfigPath, "WingsOfTheValkyrie"); } public static string ExportPath() { return Path.Combine(ExportDirectory(), "barrkbot_flight.json"); } private static string RegistryPath() { return Path.Combine(ExportDirectory(), "flight_registry.dat"); } internal static void EnsureSnapshot() { EnsureRegistryLoaded(); } private static void EnsureRegistryLoaded() { if (_registryLoaded) { return; } _registryLoaded = true; try { string path = RegistryPath(); if (!File.Exists(path)) { return; } string[] array = File.ReadAllLines(path); foreach (string text in array) { if (!string.IsNullOrEmpty(text)) { int num = text.IndexOf('|'); int num2 = text.LastIndexOf('|'); if (num > 0 && num2 > num && long.TryParse(text.Substring(0, num), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { Rows[result] = new Row { PlayerId = result, Name = text.Substring(num + 1, num2 - num - 1), Saga = FlightSaga.Deserialize(text.Substring(num2 + 1)) }; } } } } catch (Exception ex) { Log.LogWarning("Could not read the flight registry; it will rebuild as players fly. Reason: " + ex.Message); } FlyingSkillRestore.CaptureSnapshot(Rows.Count, VisitRows); } private static void VisitRows(Action visit) { foreach (Row value in Rows.Values) { if (value != null && value.Saga != null) { visit(value.PlayerId, value.Name, value.Saga.SkillLevel); } } } private static void SaveRegistry() { StringBuilder stringBuilder = new StringBuilder(Rows.Count * 320); foreach (Row value in Rows.Values) { stringBuilder.Append(value.PlayerId.ToString(CultureInfo.InvariantCulture)).Append('|').Append((value.Name ?? "").Replace("\n", " ").Replace("\r", " ")) .Append('|') .Append(value.Saga.Serialize()) .Append('\n'); } WriteAtomic(RegistryPath(), stringBuilder.ToString()); } public static string WriteExport() { string text = ExportDirectory(); try { EnsureRegistryLoaded(); List list = new List(); foreach (Row value in Rows.Values) { if (value?.Saga != null) { list.Add(value); } } HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase); Subject[] array = Subjects(); foreach (Subject subject in array) { List> list2 = Partition(subject, list); for (int j = 0; j < list2.Count; j++) { string text2 = PartFileName(subject.FileName, j + 1); hashSet.Add(text2); WriteAtomic(Path.Combine(text, text2), BuildJson(subject, list2[j], list, j + 1, list2.Count)); } } SweepStaleExports(text, hashSet); SaveRegistry(); return ExportPath(); } catch (Exception ex) { Log.LogWarning("Could not write the flight export to '" + text + "'. Reason: " + ex.Message); return null; } } private static string PartFileName(string fileName, int part) { if (part <= 1) { return fileName; } return fileName.Substring(0, fileName.Length - ".json".Length) + "_" + part.ToString(CultureInfo.InvariantCulture) + ".json"; } private static void SweepStaleExports(string directory, HashSet written) { try { if (!Directory.Exists(directory)) { return; } string[] files = Directory.GetFiles(directory, "barrkbot_flight*.json"); foreach (string path in files) { string fileName = Path.GetFileName(path); if (!written.Contains(fileName)) { File.Delete(path); Log.LogInfo("Removed a flight export this version no longer writes, so the reader stops ranking it: " + fileName); } } } catch (Exception ex) { Log.LogWarning("Could not tidy old flight exports; an out-of-date file may still be read. Reason: " + ex.Message); } } private static void WriteAtomic(string path, string contents) { string directoryName = Path.GetDirectoryName(path); if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } string text = path + ".tmp"; File.WriteAllText(text, contents, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); if (File.Exists(path)) { File.Replace(text, path, null); } else { File.Move(text, path); } } private static Subject[] Subjects() { return new Subject[4] { new Subject { FileName = "barrkbot_flight.json", Holds = "Career totals per pilot: Valkyrie Flight skill level, total time aloft, total distance, number of flights, and time flown at night.", Fields = new Field[5] { new Field { Name = "valkyrie_flight_level", Value = (FlightSaga s) => Math.Round(s.SkillLevel, 1) }, new Field { Name = "flight_time_seconds", Value = (FlightSaga s) => Math.Round(s.TimeFlownSeconds, 1) }, new Field { Name = "distance_flown_meters", Value = (FlightSaga s) => Math.Round(s.DistanceMeters, 1) }, new Field { Name = "flights", Value = (FlightSaga s) => s.Flights, Integral = true }, new Field { Name = "night_flight_seconds", Value = (FlightSaga s) => Math.Round(s.NightSeconds, 1) } } }, new Subject { FileName = "barrkbot_flight_records.json", Holds = "Personal bests per pilot: longest single flight by time and by distance, highest altitude, top speed and steepest dive.", Fields = new Field[5] { new Field { Name = "longest_flight_seconds", Value = (FlightSaga s) => Math.Round(s.BestFlightSeconds, 1) }, new Field { Name = "longest_flight_meters", Value = (FlightSaga s) => Math.Round(s.BestFlightMeters, 1) }, new Field { Name = "max_altitude_meters", Value = (FlightSaga s) => Math.Round(s.BestAltitude, 1) }, new Field { Name = "top_speed_meters_per_second", Value = (FlightSaga s) => Math.Round(s.BestSpeed, 1) }, new Field { Name = "steepest_dive_meters_per_second", Value = (FlightSaga s) => Math.Round(s.BestDiveSpeed, 1) } } }, new Subject { FileName = "barrkbot_flight_counters.json", Holds = "Event tallies per pilot: wingbeats, landings on ground, water and ship, and flights refused for want of stamina or skill.", Fields = new Field[6] { new Field { Name = "wingbeats", Value = (FlightSaga s) => s.Flaps, Integral = true }, new Field { Name = "landings_ground", Value = (FlightSaga s) => s.LandingsGround, Integral = true }, new Field { Name = "landings_water", Value = (FlightSaga s) => s.LandingsWater, Integral = true }, new Field { Name = "landings_ship", Value = (FlightSaga s) => s.LandingsShip, Integral = true }, new Field { Name = "stamina_denials", Value = (FlightSaga s) => s.StaminaDenials, Integral = true }, new Field { Name = "skill_denials", Value = (FlightSaga s) => s.SkillDenials, Integral = true } } }, new Subject { FileName = "barrkbot_flight_tiers.json", Holds = "Time flown on each grade of wings per pilot -- crude, troll, lox and dragon -- and which biomes they have crossed.", Fields = new Field[5] { new Field { Name = "tier_time_crude_seconds", Value = (FlightSaga s) => Math.Round(s.CrudeSeconds, 1) }, new Field { Name = "tier_time_troll_seconds", Value = (FlightSaga s) => Math.Round(s.TrollSeconds, 1) }, new Field { Name = "tier_time_lox_seconds", Value = (FlightSaga s) => Math.Round(s.LoxSeconds, 1) }, new Field { Name = "tier_time_dragon_seconds", Value = (FlightSaga s) => Math.Round(s.DragonSeconds, 1) }, new Field { Name = "distinct_biomes_flown", Value = (FlightSaga s) => s.BiomesFlownOver().Count, Integral = true } }, AppendExtra = AppendBiomes } }; } private static void AppendBiomes(StringBuilder sb, FlightSaga saga) { sb.Append(" \"biomes_flown_over\": ["); List list = saga.BiomesFlownOver(); for (int i = 0; i < list.Count; i++) { if (i > 0) { sb.Append(", "); } sb.Append('"').Append(Escape(list[i])).Append('"'); } sb.Append("],\n"); } private static List> Partition(Subject subject, List rows) { List> list = new List>(); List list2 = new List(); int num = 0; foreach (Row row in rows) { int num2 = CompactRowWidth(subject, row); if (list2.Count > 0 && num + num2 > 2400) { list.Add(list2); list2 = new List(); num = 0; } list2.Add(row); num += num2; } list.Add(list2); return list; } private static int CompactRowWidth(Subject subject, Row row) { StringBuilder stringBuilder = new StringBuilder(320); AppendRowObject(stringBuilder, row, subject); return CompactLength(stringBuilder.ToString()); } private static int CompactLength(string json) { int num = 0; bool flag = false; bool flag2 = false; foreach (char c in json) { if (flag) { num++; if (flag2) { flag2 = false; continue; } switch (c) { case '\\': flag2 = true; break; case '"': flag = false; break; } } else { switch (c) { case '"': flag = true; num++; break; default: num++; break; case '\t': case '\n': case '\r': case ' ': break; } } } return num; } private static void AppendLeaders(StringBuilder sb, Subject subject, List allRows) { Dictionary dictionary = new Dictionary(); foreach (Row allRow in allRows) { string key = allRow.Name ?? "Unknown"; dictionary.TryGetValue(key, out var value); dictionary[key] = value + 1; } sb.Append(" \"players_leaders\": {\n"); bool flag = true; Field[] fields = subject.Fields; foreach (Field field in fields) { List list = new List(); foreach (Row allRow2 in allRows) { if (allRow2?.Saga == null) { continue; } double num = field.Value(allRow2.Saga); if (!double.IsNaN(num) && !double.IsInfinity(num) && !(num <= 0.0)) { string text = allRow2.Name ?? "Unknown"; if (dictionary[text] > 1) { text = text + " (id " + allRow2.PlayerId.ToString(CultureInfo.InvariantCulture) + ")"; } list.Add(new Leader { Name = text, Value = num }); } } if (list.Count == 0) { continue; } list.Sort((Leader a, Leader b) => b.Value.CompareTo(a.Value)); if (!flag) { sb.Append(",\n"); } flag = false; Indent(sb, 2).Append('"').Append(field.Name).Append("\": ["); int num2 = Math.Min(3, list.Count); for (int num3 = 0; num3 < num2; num3++) { if (num3 > 0) { sb.Append(", "); } sb.Append("{\"name\": \"").Append(Escape(list[num3].Name)).Append("\", \"value\": ") .Append(Number(list[num3].Value, field.Integral)) .Append('}'); } sb.Append(']'); } sb.Append(flag ? "},\n" : "\n },\n"); } private static string BuildJson(Subject subject, List partRows, List allRows, int part, int partOf) { StringBuilder stringBuilder = new StringBuilder(1024 + partRows.Count * 320); stringBuilder.Append("{\n"); Str(stringBuilder, 1, "generated_at", FlightSaga.IsoNow()).Append(",\n"); Str(stringBuilder, 1, "source", "Wings of the Valkyrie 2.2.2").Append(",\n"); Raw(stringBuilder, 1, "schema_version", 4.ToString(CultureInfo.InvariantCulture)).Append(",\n"); Str(stringBuilder, 1, "holds", subject.Holds).Append(",\n"); if (partOf > 1) { Raw(stringBuilder, 1, "part", part.ToString(CultureInfo.InvariantCulture)).Append(",\n"); Raw(stringBuilder, 1, "part_of", partOf.ToString(CultureInfo.InvariantCulture)).Append(",\n"); AppendLeaders(stringBuilder, subject, allRows); } stringBuilder.Append(" \"intervals\": {\n"); Raw(stringBuilder, 2, "write_seconds", ((int)ModConfig.FlightStatsWriteInterval.Value).ToString(CultureInfo.InvariantCulture)).Append(",\n"); Raw(stringBuilder, 2, "client_report_seconds", ((int)ModConfig.FlightStatsReportInterval.Value).ToString(CultureInfo.InvariantCulture)).Append("\n"); stringBuilder.Append(" },\n"); AppendNotes(stringBuilder, partOf); stringBuilder.Append(" \"players\": {"); bool flag = true; foreach (Row partRow in partRows) { if (partRow?.Saga != null) { stringBuilder.Append(flag ? "\n" : ",\n"); flag = false; stringBuilder.Append(" \"").Append(Escape(partRow.PlayerId.ToString(CultureInfo.InvariantCulture))).Append("\": "); AppendRowObject(stringBuilder, partRow, subject); } } stringBuilder.Append(flag ? "}\n" : "\n }\n"); stringBuilder.Append("}\n"); return stringBuilder.ToString(); } private static void AppendRowObject(StringBuilder sb, Row row, Subject subject) { FlightSaga saga = row.Saga; sb.Append("{\n"); Str(sb, 3, "name", row.Name).Append(",\n"); Field[] fields = subject.Fields; foreach (Field field in fields) { Num(sb, 3, field.Name, field.Value(saga)).Append(",\n"); } if (subject.AppendExtra != null) { subject.AppendExtra(sb, saga); } Str(sb, 3, "first_flight_at", FlightSaga.Iso(saga.FirstFlightUnix)).Append(",\n"); Str(sb, 3, "last_flight_at", FlightSaga.Iso(saga.LastFlightUnix)).Append("\n"); sb.Append(" }"); } private static void AppendNotes(StringBuilder sb, int partOf) { Str(sb, 1, "flight_time_seconds_notes", "Time with wings deployed and gliding. This is not playtime and not session length - a player with hundreds of hours may have very little flight time. Never present it as time played.").Append(",\n"); Str(sb, 1, "distance_flown_meters_notes", "Horizontal distance covered under this mod's wings only. It shares no base with any sailing, riding or walking distance counter from another mod on this server: never sum, rank or compare them together.").Append(",\n"); Str(sb, 1, "counters_notes", "flights, wingbeats, stamina_denials and skill_denials all count different events inside the same flight and must never be added together into one total. A single flight raises several of them at once.").Append(",\n"); Str(sb, 1, "players_notes", "Rows are created the first time a character actually flies, never pre-seeded. An empty players map means no flight has been recorded yet - it never means nobody flies, and it is not a zero. A missing player is a player who has not flown since this server last saw them, not a player who has flown zero metres.").Append(",\n"); Str(sb, 1, "max_altitude_meters_notes", "Height above the ground directly below, not above sea level, and capped in play by the flight ceiling of the wings worn and the pilot's Valkyrie Flight level.").Append(",\n"); Str(sb, 1, "tier_time_notes", "tier_time_crude_seconds, tier_time_troll_seconds, tier_time_lox_seconds and tier_time_dragon_seconds divide the same flight time between the grades of wings worn, so together they total flight_time_seconds and must never be added to it.").Append(",\n"); Str(sb, 1, "distinct_biomes_flown_notes", "How many of the nine biomes this pilot has crossed under wing, not how many they have visited on foot. Ranking it ranks exploration by air only.").Append(",\n"); Str(sb, 1, "subject_split_notes", "This mod publishes four files that each hold every pilot, divided by subject rather than by player: barrkbot_flight.json (totals), _records (personal bests), _counters (event tallies), _tiers (wing grades and biomes). Each ranks over the complete roster, so a superlative from any one of them is correct and they never need combining to be trusted.").Append(",\n"); if (partOf > 1) { Str(sb, 1, "part_notes", "This subject has outgrown one file and continues into numbered parts. The rows below are this part's only, but players_leaders above is ranked over every pilot on the server, so any superlative should be answered from it and never from these rows.").Append(",\n"); } } private static StringBuilder Indent(StringBuilder sb, int depth) { return sb.Append(' ', depth * 2); } private static StringBuilder Str(StringBuilder sb, int depth, string key, string value) { return Indent(sb, depth).Append('"').Append(key).Append("\": \"") .Append(Escape(value)) .Append('"'); } private static StringBuilder Raw(StringBuilder sb, int depth, string key, string value) { return Indent(sb, depth).Append('"').Append(key).Append("\": ") .Append(value); } private static string Number(double value, bool integral) { if (!integral) { return value.ToString("0.####", CultureInfo.InvariantCulture); } return ((long)Math.Round(value)).ToString(CultureInfo.InvariantCulture); } private static StringBuilder Num(StringBuilder sb, int depth, string key, double value) { return Indent(sb, depth).Append('"').Append(key).Append("\": ") .Append(value.ToString("0.####", CultureInfo.InvariantCulture)); } private static StringBuilder Num(StringBuilder sb, int depth, string key, long value) { return Indent(sb, depth).Append('"').Append(key).Append("\": ") .Append(value.ToString(CultureInfo.InvariantCulture)); } private static string Escape(string value) { if (string.IsNullOrEmpty(value)) { return ""; } StringBuilder stringBuilder = new StringBuilder(value.Length + 8); foreach (char c in value) { switch (c) { case '"': stringBuilder.Append("\\\""); continue; case '\\': stringBuilder.Append("\\\\"); continue; case '\n': stringBuilder.Append("\\n"); continue; case '\r': stringBuilder.Append("\\r"); continue; case '\t': stringBuilder.Append("\\t"); continue; } if (c < ' ') { StringBuilder stringBuilder2 = stringBuilder.Append("\\u"); int num = c; stringBuilder2.Append(num.ToString("x4", CultureInfo.InvariantCulture)); } else { stringBuilder.Append(c); } } return stringBuilder.ToString(); } } public sealed class FlightSaga { public const int SchemaVersion = 1; public const int ExportSchemaVersion = 4; public long Flights; public double TimeFlownSeconds; public double DistanceMeters; public long Flaps; public long LandingsGround; public long LandingsWater; public long LandingsShip; public float BestAltitude; public float BestFlightSeconds; public float BestFlightMeters; public float BestSpeed; public float BestDiveSpeed; public long StaminaDenials; public long SkillDenials; public double NightSeconds; public int BiomeMask; public double CrudeSeconds; public double TrollSeconds; public double LoxSeconds; public double DragonSeconds; public long FirstFlightUnix; public long LastFlightUnix; public float SkillLevel; private static readonly KeyValuePair[] BiomeNames = new KeyValuePair[9] { new KeyValuePair((Biome)1, "Meadows"), new KeyValuePair((Biome)8, "Black Forest"), new KeyValuePair((Biome)2, "Swamp"), new KeyValuePair((Biome)4, "Mountain"), new KeyValuePair((Biome)16, "Plains"), new KeyValuePair((Biome)512, "Mistlands"), new KeyValuePair((Biome)32, "Ashlands"), new KeyValuePair((Biome)64, "Deep North"), new KeyValuePair((Biome)256, "Ocean") }; private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public bool HasFlown => Flights > 0; public static int BiomeCount => BiomeNames.Length; public void AddTierTime(string wingsName, double seconds) { switch (wingsName) { case "WingsOf_Troll": TrollSeconds += seconds; break; case "WingsOf_Lox": LoxSeconds += seconds; break; case "WingsOf_Dragon": DragonSeconds += seconds; break; default: CrudeSeconds += seconds; break; } } public string Serialize() { StringBuilder stringBuilder = new StringBuilder(360); Put(stringBuilder, "v", 1L); Put(stringBuilder, "flights", Flights); Put(stringBuilder, "time", TimeFlownSeconds); Put(stringBuilder, "dist", DistanceMeters); Put(stringBuilder, "flaps", Flaps); Put(stringBuilder, "landGround", LandingsGround); Put(stringBuilder, "landWater", LandingsWater); Put(stringBuilder, "landShip", LandingsShip); Put(stringBuilder, "bestAlt", BestAltitude); Put(stringBuilder, "bestTime", BestFlightSeconds); Put(stringBuilder, "bestDist", BestFlightMeters); Put(stringBuilder, "bestSpeed", BestSpeed); Put(stringBuilder, "bestDive", BestDiveSpeed); Put(stringBuilder, "noStam", StaminaDenials); Put(stringBuilder, "noSkill", SkillDenials); Put(stringBuilder, "night", NightSeconds); Put(stringBuilder, "biomes", BiomeMask); Put(stringBuilder, "tCrude", CrudeSeconds); Put(stringBuilder, "tTroll", TrollSeconds); Put(stringBuilder, "tLox", LoxSeconds); Put(stringBuilder, "tDragon", DragonSeconds); Put(stringBuilder, "first", FirstFlightUnix); Put(stringBuilder, "last", LastFlightUnix); Put(stringBuilder, "skill", SkillLevel); return stringBuilder.ToString(); } public static FlightSaga Deserialize(string stored) { FlightSaga flightSaga = new FlightSaga(); if (string.IsNullOrEmpty(stored)) { return flightSaga; } string[] array = stored.Split(new char[1] { ';' }); foreach (string text in array) { int num = text.IndexOf('='); if (num > 0) { string text2 = text.Substring(0, num); string raw = text.Substring(num + 1); switch (text2) { case "flights": flightSaga.Flights = Long(raw); break; case "time": flightSaga.TimeFlownSeconds = Double(raw); break; case "dist": flightSaga.DistanceMeters = Double(raw); break; case "flaps": flightSaga.Flaps = Long(raw); break; case "landGround": flightSaga.LandingsGround = Long(raw); break; case "landWater": flightSaga.LandingsWater = Long(raw); break; case "landShip": flightSaga.LandingsShip = Long(raw); break; case "bestAlt": flightSaga.BestAltitude = (float)Double(raw); break; case "bestTime": flightSaga.BestFlightSeconds = (float)Double(raw); break; case "bestDist": flightSaga.BestFlightMeters = (float)Double(raw); break; case "bestSpeed": flightSaga.BestSpeed = (float)Double(raw); break; case "bestDive": flightSaga.BestDiveSpeed = (float)Double(raw); break; case "noStam": flightSaga.StaminaDenials = Long(raw); break; case "noSkill": flightSaga.SkillDenials = Long(raw); break; case "night": flightSaga.NightSeconds = Double(raw); break; case "biomes": flightSaga.BiomeMask = (int)Long(raw); break; case "tCrude": flightSaga.CrudeSeconds = Double(raw); break; case "tTroll": flightSaga.TrollSeconds = Double(raw); break; case "tLox": flightSaga.LoxSeconds = Double(raw); break; case "tDragon": flightSaga.DragonSeconds = Double(raw); break; case "first": flightSaga.FirstFlightUnix = Long(raw); break; case "last": flightSaga.LastFlightUnix = Long(raw); break; case "skill": flightSaga.SkillLevel = (float)Double(raw); break; } } } return flightSaga; } private static void Put(StringBuilder sb, string key, double value) { if (sb.Length > 0) { sb.Append(';'); } sb.Append(key).Append('=').Append(value.ToString("R", CultureInfo.InvariantCulture)); } private static void Put(StringBuilder sb, string key, long value) { if (sb.Length > 0) { sb.Append(';'); } sb.Append(key).Append('=').Append(value.ToString(CultureInfo.InvariantCulture)); } private static long Long(string raw) { if (!long.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return 0L; } return result; } private static double Double(string raw) { if (!double.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { return 0.0; } return result; } public List BiomesFlownOver() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) List list = new List(); KeyValuePair[] biomeNames = BiomeNames; for (int i = 0; i < biomeNames.Length; i++) { KeyValuePair keyValuePair = biomeNames[i]; if ((BiomeMask & keyValuePair.Key) != 0) { list.Add(keyValuePair.Value); } } return list; } public static string Duration(double seconds) { if (seconds < 1.0) { return "no time at all"; } TimeSpan timeSpan = TimeSpan.FromSeconds(seconds); if (timeSpan.TotalHours >= 1.0) { return string.Format(CultureInfo.InvariantCulture, "{0}h {1}m {2}s", (int)timeSpan.TotalHours, timeSpan.Minutes, timeSpan.Seconds); } if (timeSpan.TotalMinutes >= 1.0) { return string.Format(CultureInfo.InvariantCulture, "{0}m {1}s", (int)timeSpan.TotalMinutes, timeSpan.Seconds); } return string.Format(CultureInfo.InvariantCulture, "{0}s", timeSpan.Seconds); } public static long UnixNow() { return (long)(DateTime.UtcNow - Epoch).TotalSeconds; } public static string Iso(long unixSeconds) { DateTime epoch = Epoch; return epoch.AddSeconds(unixSeconds).ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); } public static string IsoNow() { return DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); } } [HarmonyPatch] public static class FlyingSkill { private const string Identifier = "wubarrk.wingsofthevalkyrie.flying"; private const string SkillName = "Valkyrie Flight"; private const string SkillDescription = "Mastery of the Valkyrie's wings. Cheaper, stronger wingbeats and longer glides."; private static string LocalizationKey; private static SkillDef _definition; private static readonly MethodInfo AddWordMethod = AccessTools.Method(typeof(Localization), "AddWord", new Type[2] { typeof(string), typeof(string) }, (Type[])null); private static readonly FieldInfo LocalizationInstanceField = AccessTools.Field(typeof(Localization), "m_instance"); private static float _glideSeconds; private static readonly MethodInfo GetSkillMethod = AccessTools.Method(typeof(Skills), "GetSkill", new Type[1] { typeof(SkillType) }, (Type[])null); public static SkillType SkillType { get; private set; } = (SkillType)0; public static bool IsAvailable => (int)SkillType > 0; public static bool PersistenceGuaranteed { get; private set; } private static bool XpWillStick { get { if (!PersistenceGuaranteed) { return FlyingSkillMirror.CanMirror; } return true; } } public static void Register() { //IL_004e: 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) //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_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected O, but got Unknown try { int num = Math.Abs(StringExtensionMethods.GetStableHashCode("wubarrk.wingsofthevalkyrie.flying")); if (num <= 999) { Log.LogError($"The Valkyrie Flight skill identifier hashes to {num}, which collides with vanilla's skill range. The skill will not be registered."); return; } SkillType = (SkillType)num; LocalizationKey = "skill_" + num; _definition = new SkillDef { m_skill = SkillType, m_description = "Mastery of the Valkyrie's wings. Cheaper, stronger wingbeats and longer glides.", m_increseStep = 1f, m_icon = IconLoader.Load("skill_valkyrie_flight.png") }; AddLocalizationWord(); Log.LogInfo($"Valkyrie Flight registered as skill {num}."); } catch (Exception arg) { SkillType = (SkillType)0; Log.LogError($"Could not register the Valkyrie Flight skill; flight will work but will not level. Reason: {arg}"); } } private static void AddLocalizationWord() { if (!(AddWordMethod == null) && LocalizationKey != null && !(LocalizationInstanceField == null)) { object? value = LocalizationInstanceField.GetValue(null); Localization val = (Localization)((value is Localization) ? value : null); if (val != null) { AddWordMethod.Invoke(val, new object[2] { LocalizationKey, "Valkyrie Flight" }); } } } [HarmonyPatch(typeof(Localization), "SetupLanguage")] [HarmonyPostfix] private static void SetupLanguagePostfix() { AddLocalizationWord(); } [HarmonyPatch(typeof(Skills), "IsSkillValid")] [HarmonyPostfix] private static void IsSkillValidPostfix(SkillType type, ref bool __result) { //IL_0004: 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_000d: Unknown result type (might be due to invalid IL or missing references) if (!__result && (int)SkillType != 0 && type == SkillType) { __result = true; } } [HarmonyPatch(typeof(Skills), "Awake")] [HarmonyPostfix] private static void SkillsAwakePostfix(Skills __instance) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) if (_definition == null || (Object)(object)__instance == (Object)null || __instance.m_skills == null) { return; } AddLocalizationWord(); foreach (SkillDef skill in __instance.m_skills) { if (skill != null && skill.m_skill == SkillType) { return; } } __instance.m_skills.Add(_definition); } public static float Factor(Player player) { //IL_0009: 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) if ((Object)(object)player == (Object)null || (int)SkillType == 0) { return 0f; } Skills skills = ((Character)player).GetSkills(); if (!((Object)(object)skills != (Object)null)) { return 0f; } return skills.GetSkillFactor(SkillType); } public static float Level(Player player) { //IL_0009: 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) if ((Object)(object)player == (Object)null || (int)SkillType == 0) { return 0f; } Skills skills = ((Character)player).GetSkills(); if (!((Object)(object)skills != (Object)null)) { return 0f; } return skills.GetSkillLevel(SkillType); } public static void VerifyPersistencePatch() { PersistenceGuaranteed = false; MethodInfo methodInfo = AccessTools.Method(typeof(Skills), "IsSkillValid", (Type[])null, (Type[])null); if (methodInfo != null) { Patches patchInfo = Harmony.GetPatchInfo((MethodBase)methodInfo); if (patchInfo != null && patchInfo.Postfixes != null) { foreach (Patch postfix in patchInfo.Postfixes) { if (postfix.owner == "wubarrk.wingsofthevalkyrie") { PersistenceGuaranteed = true; break; } } } } if (!PersistenceGuaranteed) { Log.LogError("Skills.IsSkillValid is NOT patched, so Valheim will discard the Valkyrie Flight level every time a character loads. This is the 2.1.0-2.1.2 bug returning, most likely because a Valheim update changed that method or another mod replaced it. Please report this."); } } internal static Skill FindEntry(Player player) { //IL_0009: 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) //IL_0057: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null || (int)SkillType == 0) { return null; } Skills skills = ((Character)player).GetSkills(); if ((Object)(object)skills == (Object)null) { return null; } List skillList = skills.GetSkillList(); if (skillList == null) { return null; } foreach (Skill item in skillList) { if (item != null && item.m_info != null && item.m_info.m_skill == SkillType) { return item; } } return null; } internal static Skill GetEntry(Skills skills) { //IL_0016: 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) if (GetSkillMethod == null || (Object)(object)skills == (Object)null || (int)SkillType == 0) { return null; } try { object? obj = GetSkillMethod.Invoke(skills, new object[1] { SkillType }); return (Skill)((obj is Skill) ? obj : null); } catch (Exception ex) { Log.LogWarning("Could not reach the Valkyrie Flight skill entry: " + ex.Message); return null; } } internal static bool HasEntry(Player player) { return FindEntry(player) != null; } internal static bool SetLevel(Player player, float level, float accumulator) { if ((Object)(object)player == (Object)null) { return false; } Skill entry = GetEntry(((Character)player).GetSkills()); if (entry == null) { return false; } entry.m_level = Mathf.Clamp(level, 0f, 100f); entry.m_accumulator = Mathf.Max(accumulator, 0f); return true; } public static void AddFlapXP(Player player) { //IL_0009: 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 (!((Object)(object)player == (Object)null) && (int)SkillType != 0 && XpWillStick) { float value = ModConfig.SkillXpPerFlap.Value; if (value > 0f) { ((Character)player).RaiseSkill(SkillType, value); } } } public static void AccumulateGlideXP(Player player, bool gliding, float deltaTime) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) if (!gliding || (Object)(object)player == (Object)null || (int)SkillType == 0 || !XpWillStick) { return; } _glideSeconds += deltaTime; if (!(_glideSeconds < 1f)) { _glideSeconds -= 1f; float value = ModConfig.SkillXpPerGlideSecond.Value; if (value > 0f) { ((Character)player).RaiseSkill(SkillType, value); } } } } [HarmonyPatch] public static class FlyingSkillCommands { public const string ConsoleName = "ValkyrieFlight"; private static readonly string[] AcceptedNames = new string[3] { "ValkyrieFlight", "valkyrie_flight", "wubarrk.wingsofthevalkyrie.flying" }; private static readonly FieldInfo CommandsField = AccessTools.Field(typeof(Terminal), "commands"); private static readonly FieldInfo TabOptionsFetcherField = AccessTools.Field(typeof(ConsoleCommand), "m_tabOptionsFetcher"); private static bool _tabOptionsAdded; private static bool IsOurs(string name) { if (string.IsNullOrEmpty(name) || !FlyingSkill.IsAvailable) { return false; } string[] acceptedNames = AcceptedNames; foreach (string b in acceptedNames) { if (string.Equals(name, b, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } [HarmonyPatch(typeof(Skills), "CheatRaiseSkill")] [HarmonyPrefix] private static bool CheatRaiseSkillPrefix(Skills __instance, string name, float value, bool showMessage) { if (!IsOurs(name)) { return true; } Skill entry = FlyingSkill.GetEntry(__instance); if (entry == null) { Print("Could not reach the Valkyrie Flight skill - see the log."); return false; } entry.m_level = Mathf.Clamp(entry.m_level + value, 0f, 100f); Player component = ((Component)__instance).GetComponent(); if (showMessage && (Object)(object)component != (Object)null) { ((Character)component).Message((MessageType)1, $"Skill increased Valkyrie Flight: {(int)entry.m_level}", 0, (entry.m_info != null) ? entry.m_info.m_icon : null, false); } Print($"Skill Valkyrie Flight = {entry.m_level}"); return false; } [HarmonyPatch(typeof(Skills), "CheatResetSkill")] [HarmonyPrefix] private static bool CheatResetSkillPrefix(Skills __instance, string name) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) if (!IsOurs(name)) { return true; } __instance.ResetSkill(FlyingSkill.SkillType); Print("Skill Valkyrie Flight reset"); return false; } [HarmonyPatch(typeof(Terminal), "InitTerminal")] [HarmonyPostfix] private static void InitTerminalPostfix() { if (!_tabOptionsAdded && FlyingSkill.IsAvailable && !(CommandsField == null) && !(TabOptionsFetcherField == null) && CommandsField.GetValue(null) is Dictionary commands) { _tabOptionsAdded = true; AddTabOption(commands, "raiseskill"); AddTabOption(commands, "resetskill"); } } private static void AddTabOption(Dictionary commands, string commandName) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown if (!commands.TryGetValue(commandName, out var value) || value == null) { Log.LogWarning("No '" + commandName + "' console command to add Valkyrie Flight to; its tab completion will not list the skill."); return; } try { ConsoleOptionsFetcher inner = default(ConsoleOptionsFetcher); ref ConsoleOptionsFetcher reference = ref inner; object? value2 = TabOptionsFetcherField.GetValue(value); reference = (ConsoleOptionsFetcher)((value2 is ConsoleOptionsFetcher) ? value2 : null); TabOptionsFetcherField.SetValue(value, (object?)(ConsoleOptionsFetcher)delegate { List list = ((inner != null) ? inner.Invoke() : null); if (list == null) { list = new List(); } if (!list.Contains("ValkyrieFlight")) { list.Add("ValkyrieFlight"); } return list; }); } catch (Exception ex) { Log.LogWarning("Could not extend '" + commandName + "' tab completion (" + ex.Message + "). The command still works; the skill just will not be offered."); } } private static void Print(string line) { if ((Object)(object)Console.instance != (Object)null) { Console.instance.Print(line); } } } [HarmonyPatch(typeof(Player))] public static class FlyingSkillMirror { private const string CustomDataKey = "wubarrk.wotv.flyingskill"; public static bool CanMirror { get; private set; } = true; [HarmonyPatch("Save")] [HarmonyPrefix] public static void SavePrefix(Player __instance) { if ((Object)(object)__instance == (Object)null || !FlyingSkill.IsAvailable) { return; } try { Skill val = FlyingSkill.FindEntry(__instance); if (val != null) { Dictionary customData = __instance.m_customData; if (customData == null) { CanMirror = false; return; } customData["wubarrk.wotv.flyingskill"] = val.m_level.ToString("R", CultureInfo.InvariantCulture) + ";" + val.m_accumulator.ToString("R", CultureInfo.InvariantCulture); CanMirror = true; } } catch (Exception ex) { CanMirror = false; Log.LogWarning("Could not mirror the Valkyrie Flight level onto the character: " + ex.Message); } } [HarmonyPatch("Load")] [HarmonyPostfix] public static void LoadPostfix(Player __instance) { if ((Object)(object)__instance == (Object)null || !FlyingSkill.IsAvailable || FlyingSkill.HasEntry(__instance)) { return; } try { Dictionary customData = __instance.m_customData; if (customData != null && customData.TryGetValue("wubarrk.wotv.flyingskill", out var value) && !string.IsNullOrEmpty(value) && TryParse(value, out var level, out var accumulator) && !(level <= 0f) && FlyingSkill.SetLevel(__instance, level, accumulator)) { Log.LogWarning($"Valheim discarded the Valkyrie Flight skill on load; restored it to level {(int)level} " + "from the copy kept on the character. Flight itself is unaffected, but this should not happen -- please report it."); } } catch (Exception ex) { Log.LogWarning("Could not read the mirrored Valkyrie Flight level: " + ex.Message); } } private static bool TryParse(string stored, out float level, out float accumulator) { level = 0f; accumulator = 0f; string[] array = stored.Split(new char[1] { ';' }); if (array.Length < 1) { return false; } if (!float.TryParse(array[0], NumberStyles.Float, CultureInfo.InvariantCulture, out level)) { return false; } if (array.Length > 1) { float.TryParse(array[1], NumberStyles.Float, CultureInfo.InvariantCulture, out accumulator); } return true; } } [HarmonyPatch] public static class FlyingSkillRestore { private const string SnapshotFileName = "flight_skill_restore.dat"; private const string CustomDataKey = "wubarrk.wotv.skillrestore"; private const string StampPrefix = "v2:"; private const float RetrySeconds = 2f; private const int MaxAttempts = 10; private const string AskRpc = "WotV_SkillRestoreAsk"; private const string TellRpc = "WotV_SkillRestoreTell"; private static readonly Dictionary Snapshot = new Dictionary(); private static ZRoutedRpc _registeredOn; private static long _pendingId; private static float _pendingTimer; private static int _attempts; public static void Register() { ZRoutedRpc instance = ZRoutedRpc.instance; if (instance == null || _registeredOn == instance) { return; } try { instance.Register("WotV_SkillRestoreAsk", (Action)OnAsked); instance.Register("WotV_SkillRestoreTell", (Action)OnTold); _registeredOn = instance; } catch (Exception ex) { Log.LogWarning("Could not register the skill restore RPC; lost Valkyrie Flight levels will have to be handed back by hand. Reason: " + ex.Message); } } internal static void CaptureSnapshot(int rowCount, Action> visitRows) { Snapshot.Clear(); try { string text = Path.Combine(FlightReport.ExportDirectory(), "flight_skill_restore.dat"); if (File.Exists(text)) { string[] array = File.ReadAllLines(text); foreach (string text2 in array) { if (!string.IsNullOrEmpty(text2)) { int num = text2.LastIndexOf('|'); int num2 = text2.IndexOf('|'); if (num2 > 0 && num > num2 && long.TryParse(text2.Substring(0, num2), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) && float.TryParse(text2.Substring(num + 1), NumberStyles.Float, CultureInfo.InvariantCulture, out var result2)) { Snapshot[result] = result2; } } } Log.LogInfo($"Valkyrie Flight restore snapshot loaded: {Snapshot.Count} pilot(s) on file."); } else { if (rowCount <= 0 || visitRows == null) { return; } List lines = new List(); visitRows(delegate(long id, string name, float level) { if (id != 0L && !(level <= 0f)) { Snapshot[id] = level; lines.Add(id.ToString(CultureInfo.InvariantCulture) + "|" + (name ?? "Unknown") + "|" + level.ToString("R", CultureInfo.InvariantCulture)); } }); if (lines.Count != 0) { File.WriteAllLines(text, lines.ToArray()); Log.LogInfo($"Wrote the Valkyrie Flight restore snapshot for {lines.Count} pilot(s) to {text}. " + "Each of them will have their level handed back once, the first time they load in. This file is written once and never rewritten -- keep a copy."); } } } catch (Exception ex) { Log.LogWarning("Could not prepare the Valkyrie Flight restore snapshot: " + ex.Message); } } private static void OnAsked(long sender, long playerId) { if ((Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer()) { return; } float num = Lookup(playerId); try { ZRoutedRpc instance = ZRoutedRpc.instance; if (instance != null) { Log.LogInfo((num > 0f) ? $"Skill restore: pilot {playerId} asked; answering with Valkyrie Flight {num}." : $"Skill restore: pilot {playerId} asked; nothing on record for them."); instance.InvokeRoutedRPC(sender, "WotV_SkillRestoreTell", new object[1] { num.ToString("R", CultureInfo.InvariantCulture) }); } } catch (Exception ex) { Log.LogWarning("Could not answer a skill restore request: " + ex.Message); } } private static float Lookup(long playerId) { FlightReport.EnsureSnapshot(); if (!Snapshot.TryGetValue(playerId, out var value)) { return 0f; } return value; } [HarmonyPatch(typeof(Player), "Load")] [HarmonyPostfix] private static void LoadPostfix(Player __instance) { if (!((Object)(object)__instance == (Object)null) && FlyingSkill.IsAvailable && !IsStamped(__instance)) { long playerID = __instance.GetPlayerID(); if (playerID != 0L) { _pendingId = playerID; _pendingTimer = 0f; _attempts = 0; } } } public static void Tick(float deltaTime) { Register(); if (_pendingId == 0L) { return; } if (!ModConfig.RestoreLostSkillLevels.Value) { _pendingId = 0L; return; } _pendingTimer += deltaTime; if (_pendingTimer < 2f) { return; } _pendingTimer = 0f; try { if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer()) { Apply(Lookup(_pendingId)); return; } ZRoutedRpc instance = ZRoutedRpc.instance; ZNetPeer serverPeer = ZNet.instance.GetServerPeer(); if (instance != null && serverPeer != null) { instance.InvokeRoutedRPC(serverPeer.m_uid, "WotV_SkillRestoreAsk", new object[1] { _pendingId }); } if (++_attempts >= 10) { Log.LogWarning("The server never answered about this character's Valkyrie Flight level. If a level went missing it has not been restored; an admin can hand it back with 'resetskill ValkyrieFlight' then 'raiseskill ValkyrieFlight '."); _pendingId = 0L; } } catch (Exception ex) { Log.LogWarning("Could not ask the server about your Valkyrie Flight level: " + ex.Message); _pendingId = 0L; } } private static void OnTold(long sender, string payload) { if (!string.IsNullOrEmpty(payload) && float.TryParse(payload, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { Apply(result); } } private static void Apply(float recorded) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || !FlyingSkill.IsAvailable) { return; } _pendingId = 0L; if (!IsStamped(localPlayer) && !(recorded <= 0f)) { float num = FlyingSkill.Level(localPlayer); if (recorded > num && FlyingSkill.SetLevel(localPlayer, recorded, 0f)) { Log.LogInfo($"Restored Valkyrie Flight from {num} to {recorded} for {localPlayer.GetPlayerName()}."); ((Character)localPlayer).Message((MessageType)2, $"The Valkyries remember your wings: Valkyrie Flight restored to {(int)recorded}", 0, (Sprite)null, false); } Stamp(localPlayer, recorded); } } private static bool IsStamped(Player player) { Dictionary customData = player.m_customData; if (customData != null && customData.TryGetValue("wubarrk.wotv.skillrestore", out var value) && value != null) { return value.StartsWith("v2:", StringComparison.Ordinal); } return false; } private static void Stamp(Player player, float recorded) { try { Dictionary dictionary = player.m_customData; if (dictionary == null) { dictionary = (player.m_customData = new Dictionary()); } dictionary["wubarrk.wotv.skillrestore"] = "v2:" + recorded.ToString("R", CultureInfo.InvariantCulture); } catch (Exception ex) { Log.LogWarning("Could not mark the Valkyrie Flight restore as done: " + ex.Message); } } } internal static class IconLoader { private static readonly Dictionary Cache = new Dictionary(); private static readonly MethodInfo LoadImageMethod = typeof(ImageConversion).GetMethod("LoadImage", new Type[3] { typeof(Texture2D), typeof(byte[]), typeof(bool) }) ?? typeof(ImageConversion).GetMethod("LoadImage", new Type[2] { typeof(Texture2D), typeof(byte[]) }); private static bool LoadPng(Texture2D tex, byte[] bytes) { if (LoadImageMethod == null) { return false; } object[] parameters = ((LoadImageMethod.GetParameters().Length != 3) ? new object[2] { tex, bytes } : new object[3] { tex, bytes, false }); return (bool)LoadImageMethod.Invoke(null, parameters); } public static Sprite Load(string fileName) { //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown //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) if (Cache.TryGetValue(fileName, out var value)) { return value; } Sprite val = null; try { Assembly executingAssembly = Assembly.GetExecutingAssembly(); string text = executingAssembly.GetManifestResourceNames().FirstOrDefault((string n) => n.EndsWith(fileName, StringComparison.OrdinalIgnoreCase)); if (text == null) { Log.LogWarning("Embedded icon '" + fileName + "' not found; keeping the fallback icon."); } else { byte[] bytes; using (Stream stream = executingAssembly.GetManifestResourceStream(text)) { using MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); bytes = memoryStream.ToArray(); } Texture2D val2 = new Texture2D(2, 2, (TextureFormat)4, false) { name = "wotv_icon_" + fileName }; if (LoadPng(val2, bytes)) { val = Sprite.Create(val2, new Rect(0f, 0f, (float)((Texture)val2).width, (float)((Texture)val2).height), new Vector2(0.5f, 0.5f)); ((Object)val).name = ((Object)val2).name; } else { Log.LogWarning("Embedded icon '" + fileName + "' is not a decodable PNG."); } } } catch (Exception ex) { Log.LogWarning("Failed loading embedded icon '" + fileName + "': " + ex.Message); } Cache[fileName] = val; return val; } } internal static class Log { private static ManualLogSource _source; public static void Init(ManualLogSource source) { _source = source; } public static void LogInfo(object message) { if (_source != null) { _source.LogInfo(message); } else { Debug.Log(message); } } public static void LogWarning(object message) { if (_source != null) { _source.LogWarning(message); } else { Debug.LogWarning(message); } } public static void LogError(object message) { if (_source != null) { _source.LogError(message); } else { Debug.LogError(message); } } } public readonly struct WingStats { public readonly float FlightCeiling; public readonly float GlideSpeed; public readonly float FlapForce; public readonly float FlapStaminaCost; public readonly float MinSkillToFlap; public WingStats(float flightCeiling, float glideSpeed, float flapForce, float flapStaminaCost, float minSkillToFlap) { FlightCeiling = flightCeiling; GlideSpeed = glideSpeed; FlapForce = flapForce; FlapStaminaCost = flapStaminaCost; MinSkillToFlap = minSkillToFlap; } } public static class ModConfig { public sealed class TierConfig { public SyncedConfigEntry FlightCeiling; public SyncedConfigEntry GlideSpeed; public SyncedConfigEntry FlapForce; public SyncedConfigEntry FlapStaminaCost; public SyncedConfigEntry MinSkillToFlap; public SyncedConfigEntry CraftingStation; public SyncedConfigEntry MinStationLevel; public SyncedConfigEntry CraftingRequirements; public SyncedConfigEntry UpgradeRequirements; public SyncedConfigEntry Armor; public SyncedConfigEntry ArmorPerLevel; public SyncedConfigEntry Weight; public SyncedConfigEntry MaxDurability; public SyncedConfigEntry DamageModifiers; public SyncedConfigEntry JumpStaminaModifier; public SyncedConfigEntry RunStaminaModifier; public SyncedConfigEntry SneakStaminaModifier; public SyncedConfigEntry EitrRegenModifier; } public const string MetaSection = "0. Meta"; public const string ConfigVersionKey = "ConfigVersion"; private static readonly ConfigSync Sync = new ConfigSync("wubarrk.wingsofthevalkyrie") { DisplayName = "Wings of the Valkyrie", CurrentVersion = "2.2.2", MinimumRequiredVersion = "2.1.4", ModRequired = true }; private static ConfigFile _file; public static ConfigEntry ConfigVersion { get; private set; } public static SyncedConfigEntry LockConfiguration { get; private set; } public static SyncedConfigEntry EnableMod { get; private set; } public static SyncedConfigEntry GlobalWingSpan { get; private set; } public static SyncedConfigEntry BaseGlideSinkRate { get; private set; } public static SyncedConfigEntry MaxDiveSpeed { get; private set; } public static SyncedConfigEntry SkillXpPerFlap { get; private set; } public static SyncedConfigEntry SkillXpPerGlideSecond { get; private set; } public static SyncedConfigEntry SkillStaminaReduction { get; private set; } public static SyncedConfigEntry SkillFlapPowerBonus { get; private set; } public static SyncedConfigEntry SkillGlideSinkReduction { get; private set; } public static SyncedConfigEntry SkillGlideSpeedBonus { get; private set; } public static SyncedConfigEntry CeilingAtNovice { get; private set; } public static SyncedConfigEntry RestoreLostSkillLevels { get; private set; } public static SyncedConfigEntry EnableFlightLog { get; private set; } public static SyncedConfigEntry PublishFlightStats { get; private set; } public static SyncedConfigEntry FlightStatsExportFolder { get; private set; } public static SyncedConfigEntry FlightStatsWriteInterval { get; private set; } public static SyncedConfigEntry FlightStatsReportInterval { get; private set; } public static SyncedConfigEntry MaxQuality { get; private set; } public static SyncedConfigEntry CeilingBonusPerLevel { get; private set; } public static SyncedConfigEntry GlideSpeedBonusPerLevel { get; private set; } public static SyncedConfigEntry FlapForceBonusPerLevel { get; private set; } public static SyncedConfigEntry FlapStaminaReductionPerLevel { get; private set; } public static SyncedConfigEntry SlotPolicy { get; private set; } public static SyncedConfigEntry PreferredWingsSlot { get; private set; } public static SyncedConfigEntry AlternateSlotKey { get; private set; } public static TierConfig Crude { get; private set; } public static TierConfig Troll { get; private set; } public static TierConfig Lox { get; private set; } public static TierConfig Dragon { get; private set; } public static ConfigFile File => _file; private static SyncedConfigEntry Bind(string section, string key, T value, ConfigDescription description, bool synced = true) { ConfigEntry configEntry = _file.Bind(section, key, value, description); SyncedConfigEntry syncedConfigEntry = Sync.AddConfigEntry(configEntry); syncedConfigEntry.SynchronizedConfig = synced; return syncedConfigEntry; } private static SyncedConfigEntry Bind(string section, string key, T value, string description, bool synced = true) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown return Bind(section, key, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty()), synced); } public static void Init(ConfigFile config) { //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Expected O, but got Unknown //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Expected O, but got Unknown //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Expected O, but got Unknown //IL_037a: Unknown result type (might be due to invalid IL or missing references) //IL_0385: Expected O, but got Unknown //IL_03a5: Unknown result type (might be due to invalid IL or missing references) //IL_03b0: Expected O, but got Unknown //IL_03cb: Unknown result type (might be due to invalid IL or missing references) //IL_03d6: Expected O, but got Unknown //IL_03f6: Unknown result type (might be due to invalid IL or missing references) //IL_0401: Expected O, but got Unknown //IL_0421: Unknown result type (might be due to invalid IL or missing references) //IL_042c: Expected O, but got Unknown //IL_044c: Unknown result type (might be due to invalid IL or missing references) //IL_0457: Expected O, but got Unknown //IL_0477: Unknown result type (might be due to invalid IL or missing references) //IL_0482: Expected O, but got Unknown //IL_04a2: Unknown result type (might be due to invalid IL or missing references) //IL_04ad: Expected O, but got Unknown //IL_052f: Unknown result type (might be due to invalid IL or missing references) //IL_053a: Expected O, but got Unknown //IL_0567: Unknown result type (might be due to invalid IL or missing references) //IL_0572: Expected O, but got Unknown //IL_0593: Unknown result type (might be due to invalid IL or missing references) //IL_059e: Expected O, but got Unknown //IL_05be: Unknown result type (might be due to invalid IL or missing references) //IL_05c9: Expected O, but got Unknown //IL_05e9: Unknown result type (might be due to invalid IL or missing references) //IL_05f4: Expected O, but got Unknown //IL_0614: Unknown result type (might be due to invalid IL or missing references) //IL_061f: Expected O, but got Unknown //IL_063f: Unknown result type (might be due to invalid IL or missing references) //IL_064a: Expected O, but got Unknown //IL_0665: Unknown result type (might be due to invalid IL or missing references) //IL_0670: Expected O, but got Unknown //IL_06a4: Unknown result type (might be due to invalid IL or missing references) _file = config; AcceptableValueRange item = new AcceptableValueRange(10f, 5000f); AcceptableValueRange item2 = new AcceptableValueRange(1f, 100f); AcceptableValueRange item3 = new AcceptableValueRange(1f, 100f); AcceptableValueRange item4 = new AcceptableValueRange(0f, 100f); AcceptableValueRange item5 = new AcceptableValueRange(1, 10); AcceptableValueRange item6 = new AcceptableValueRange(0f, 100f); AcceptableValueRange val = new AcceptableValueRange(0f, 5f); AcceptableValueRange val2 = new AcceptableValueRange(0f, 1f); ConfigMigration.Begin(config); ConfigVersion = config.Bind("0. Meta", "ConfigVersion", 3, "Internal bookkeeping - the layout version of this file, used to carry your settings across mod updates. Do not edit."); LockConfiguration = Bind("1. General", "LockConfiguration", value: true, "If on, this file is served by the server and only its admins can change the synced settings. Replaces the admin-only lock Jotunn used to provide."); Sync.AddLockingConfigEntry(LockConfiguration.SourceConfig); EnableMod = Bind("1. General", "EnableMod", value: true, "Enable or disable the Valkyrie Wings mod."); GlobalWingSpan = Bind("1. General", "GlobalWingSpan", 1f, new ConfigDescription("Multiplier for the overall size of the wings.", (AcceptableValueBase)(object)new AcceptableValueRange(0.1f, 5f), Array.Empty())); BaseGlideSinkRate = Bind("1. General", "BaseGlideSinkRate", 2.5f, new ConfigDescription("How fast a level 0 flier sinks while gliding level, in metres per second. Skill flattens this (see GlideSinkReductionAtMax).", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 20f), Array.Empty())); MaxDiveSpeed = Bind("1. General", "MaxDiveSpeed", 20f, new ConfigDescription("Descent speed at a full straight-down dive, in metres per second. Never scaled by skill - diving is intent, not practice.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 100f), Array.Empty())); Crude = BindTier("2. Crude Wings", 130f, 8f, 11f, 16f, 0f, "piece_workbench", 2, "BronzeNails:10,DeerHide:10,LeatherScraps:20,TrollHide:5,Feathers:20", "Feathers:25,LeatherScraps:15,BronzeNails:8,TrollHide:6", 2f, 1f, 4f, 400f, "", -0.1f, 0f, 0f, 0f, (ceiling: item, speed: item2, force: item3, stamina: item4, skill: item6, level: item5)); Troll = BindTier("3. Troll Wings", 150f, 12f, 13f, 13f, 15f, "piece_workbench", 2, "TrollHide:15,IronNails:10,Feathers:30", "Feathers:35,TrollHide:12,IronNails:10,Silver:5", 4f, 2f, 4f, 500f, "Blunt:SlightlyResistant", -0.15f, -0.05f, -0.15f, 0f, (ceiling: item, speed: item2, force: item3, stamina: item4, skill: item6, level: item5)); Lox = BindTier("4. Lox Wings", 190f, 16f, 16f, 10f, 30f, "forge", 3, "LoxPelt:10,Silver:20,LinenThread:10,Feathers:30", "Feathers:40,LoxPelt:8,Silver:25,LinenThread:12", 7f, 3f, 5f, 1200f, "Frost:Resistant", -0.2f, -0.1f, 0f, 0f, (ceiling: item, speed: item2, force: item3, stamina: item4, skill: item6, level: item5)); Dragon = BindTier("5. Dragon Wings", 1300f, 24f, 20f, 7f, 50f, "piece_magetable", 1, "Feathers:40,Eitr:20,ScaleHide:10,DragonTear:2", "Feathers:50,Eitr:25,ScaleHide:12,DragonTear:1", 10f, 4f, 3f, 1200f, "Fire:VeryResistant,Frost:Resistant", -0.25f, -0.15f, -0.1f, 0.1f, (ceiling: item, speed: item2, force: item3, stamina: item4, skill: item6, level: item5)); SkillXpPerFlap = Bind("6. Valkyrie Flight Skill", "XpPerFlap", 0.4f, new ConfigDescription("Skill XP awarded per wing flap.", (AcceptableValueBase)(object)val, Array.Empty())); SkillXpPerGlideSecond = Bind("6. Valkyrie Flight Skill", "XpPerGlideSecond", 0.2f, new ConfigDescription("Skill XP awarded per second spent gliding. This is the only way a flier below a tier's MinSkillToFlap can earn levels, so keep it above 0.", (AcceptableValueBase)(object)val, Array.Empty())); RestoreLostSkillLevels = Bind("6. Valkyrie Flight Skill", "RestoreLostSkillLevels", value: true, new ConfigDescription("Hands each pilot their Valkyrie Flight level back once, the first time they load in, from the snapshot the server takes of its flight registry. This repairs the levels 2.1.0 to 2.1.2 destroyed. It only ever raises a level, never lowers one, and runs at most once per character. Safe to leave on; turn it off if you would rather hand levels back yourself with raiseskill.", (AcceptableValueBase)null, Array.Empty())); SkillStaminaReduction = Bind("6. Valkyrie Flight Skill", "StaminaReductionAtMax", 0.55f, new ConfigDescription("Fraction of the flap stamina cost removed at skill level 100.", (AcceptableValueBase)(object)val2, Array.Empty())); SkillFlapPowerBonus = Bind("6. Valkyrie Flight Skill", "FlapPowerBonusAtMax", 0.5f, new ConfigDescription("Extra flap lift at skill level 100, as a fraction of the tier's base force.", (AcceptableValueBase)(object)val2, Array.Empty())); SkillGlideSinkReduction = Bind("6. Valkyrie Flight Skill", "GlideSinkReductionAtMax", 0.6f, new ConfigDescription("How much slower you sink while gliding at skill level 100 (longer glides).", (AcceptableValueBase)(object)val2, Array.Empty())); SkillGlideSpeedBonus = Bind("6. Valkyrie Flight Skill", "GlideSpeedBonusAtMax", 0.35f, new ConfigDescription("Extra horizontal glide speed at skill level 100, as a fraction.", (AcceptableValueBase)(object)val2, Array.Empty())); CeilingAtNovice = Bind("6. Valkyrie Flight Skill", "CeilingAtNovice", 0.35f, new ConfigDescription("Fraction of a tier's flight ceiling available at skill level 0, rising to the full ceiling at 100. 1 = altitude is not gated by skill at all.", (AcceptableValueBase)(object)val2, Array.Empty())); EnableFlightLog = Bind("7. Flight Logbook", "EnableFlightLog", value: true, "Track your flight saga - time flown, distance, records and oddities - and store it on your character. Read it in-game with the 'wov' console command.", synced: false); PublishFlightStats = Bind("7. Flight Logbook", "PublishFlightStats", value: true, "Take part in the server's flight statistics. On a client this sends your totals to the server you are playing on; on a server it publishes everyone's totals to a JSON file that tools such as BarrkBOT read. Set it to false on a client to keep your own logbook but stay out of the server's.", synced: false); FlightStatsExportFolder = Bind("7. Flight Logbook", "FlightStatsExportFolder", "", "Server only. Folder to write the flight statistics into. Leave empty for 'WingsOfTheValkyrie' beside this config file, which is where the export sweep looks - change it only if you know the reader is looking somewhere else.", synced: false); FlightStatsWriteInterval = Bind("7. Flight Logbook", "FlightStatsWriteIntervalSeconds", 60f, new ConfigDescription("Server only. How often the flight statistics file is rewritten, in seconds.", (AcceptableValueBase)(object)new AcceptableValueRange(5f, 3600f), Array.Empty()), synced: false); FlightStatsReportInterval = Bind("7. Flight Logbook", "FlightStatsReportIntervalSeconds", 60f, new ConfigDescription("Client only. How often your totals are sent to the server while you play, in seconds.", (AcceptableValueBase)(object)new AcceptableValueRange(5f, 3600f), Array.Empty()), synced: false); MaxQuality = Bind("8. Wing Upgrades", "MaxQuality", 4, new ConfigDescription("How many quality levels each pair of wings can be upgraded to. 1 disables upgrading entirely. Lowering this below a pair of wings someone already upgraded does not take their levels away, it only stops further upgrades.", (AcceptableValueBase)(object)new AcceptableValueRange(1, 4), Array.Empty())); CeilingBonusPerLevel = Bind("8. Wing Upgrades", "CeilingBonusPerLevel", 0.08f, new ConfigDescription("Extra flight ceiling per quality level above 1, as a fraction of the tier's ceiling.", (AcceptableValueBase)(object)val2, Array.Empty())); GlideSpeedBonusPerLevel = Bind("8. Wing Upgrades", "GlideSpeedBonusPerLevel", 0.05f, new ConfigDescription("Extra glide speed per quality level above 1, as a fraction of the tier's glide speed.", (AcceptableValueBase)(object)val2, Array.Empty())); FlapForceBonusPerLevel = Bind("8. Wing Upgrades", "FlapForceBonusPerLevel", 0.05f, new ConfigDescription("Extra flap lift per quality level above 1, as a fraction of the tier's flap force.", (AcceptableValueBase)(object)val2, Array.Empty())); FlapStaminaReductionPerLevel = Bind("8. Wing Upgrades", "FlapStaminaReductionPerLevel", 0.06f, new ConfigDescription("Flap stamina removed per quality level above 1, as a fraction of the tier's cost.", (AcceptableValueBase)(object)val2, Array.Empty())); SlotPolicy = Bind("9. Wing Slot", "WingsSlot", WingsSlotPolicy.Auto, new ConfigDescription("Which equipment slot the wings occupy. Auto: your back, unless a cape is already there and the trinket slot is free. Either: each player chooses (PreferredWingsSlot, the AlternateSlotKey, or 'wov slot' in the console). TrinketOnly / BackOnly: that slot, no choice. The wings keep their full armour, resistances and stat modifiers in either slot; what the trinket slot buys is a real cape worn alongside them. Applies immediately: wings sitting in a slot the new rule forbids are moved the next time their wearer is on the ground.", (AcceptableValueBase)null, Array.Empty())); PreferredWingsSlot = Bind("9. Wing Slot", "PreferredWingsSlot", WingsSlotChoice.Back, "Client only, and only while the server's WingsSlot is Either: the slot your wings go to when you equip them. Change it in-game with 'wov slot back' or 'wov slot trinket'.", synced: false); AlternateSlotKey = Bind("9. Wing Slot", "AlternateSlotKey", new KeyboardShortcut((KeyCode)304, Array.Empty()), "Client only, and only while the server's WingsSlot is Either: hold this while equipping wings to send that one pair to the slot you did NOT prefer.", synced: false); ConfigMigration.Finish(config, ConfigVersion); } private static TierConfig BindTier(string section, float ceiling, float glide, float flap, float stamina, float minSkill, string station, int stationLevel, string craft, string upgrade, float armor, float armorPerLevel, float weight, float durability, string damageModifiers, float jump, float run, float sneak, float eitr, (AcceptableValueRange ceiling, AcceptableValueRange speed, AcceptableValueRange force, AcceptableValueRange stamina, AcceptableValueRange skill, AcceptableValueRange level) ranges) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Expected O, but got Unknown //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Expected O, but got Unknown //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Expected O, but got Unknown //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Expected O, but got Unknown //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Expected O, but got Unknown //IL_01df: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Expected O, but got Unknown //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Expected O, but got Unknown //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Expected O, but got Unknown //IL_0272: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Expected O, but got Unknown //IL_0296: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Expected O, but got Unknown //IL_02ba: Unknown result type (might be due to invalid IL or missing references) //IL_02c5: Expected O, but got Unknown AcceptableValueRange val = new AcceptableValueRange(-1f, 1f); return new TierConfig { FlightCeiling = Bind(section, "FlightCeiling", ceiling, new ConfigDescription("Flight ceiling above ground at Valkyrie Flight 100. Lower levels reach only a fraction of it (see CeilingAtNovice).", (AcceptableValueBase)(object)ranges.ceiling, Array.Empty())), GlideSpeed = Bind(section, "GlideSpeed", glide, new ConfigDescription("Horizontal glide speed before skill and quality bonuses.", (AcceptableValueBase)(object)ranges.speed, Array.Empty())), FlapForce = Bind(section, "FlapForce", flap, new ConfigDescription("Upward lift force when flapping, before skill and quality bonuses.", (AcceptableValueBase)(object)ranges.force, Array.Empty())), FlapStaminaCost = Bind(section, "FlapStaminaCost", stamina, new ConfigDescription("Stamina consumed per flap before skill and quality reductions.", (AcceptableValueBase)(object)ranges.stamina, Array.Empty())), MinSkillToFlap = Bind(section, "MinSkillToFlap", minSkill, new ConfigDescription("Valkyrie Flight level needed to flap these wings. Below it they still unfurl and glide, so the skill can always be earned. 0 = no requirement.", (AcceptableValueBase)(object)ranges.skill, Array.Empty())), CraftingStation = Bind(section, "CraftingStation", station, "Prefab name of the crafting station."), MinStationLevel = Bind(section, "MinStationLevel", stationLevel, new ConfigDescription("Minimum station level required to craft. Upgrading to quality q needs this + (q - 1), so raising it can put the top quality levels out of reach: a workbench stops at level 5, a forge at 7 and a Galdr table at 4.", (AcceptableValueBase)(object)ranges.level, Array.Empty())), CraftingRequirements = Bind(section, "CraftingRequirements", craft, "Items consumed to craft these wings at quality 1. Format: ItemName:Amount,ItemName:Amount"), UpgradeRequirements = Bind(section, "UpgradeRequirements", upgrade, "Items consumed PER QUALITY LEVEL when upgrading. Valheim charges (quality - 1) times these amounts, so 'Feathers:25' costs 25 feathers for quality 2, 50 for quality 3 and 75 for quality 4. Format: ItemName:AmountPerLevel"), Armor = Bind(section, "Armor", armor, new ConfigDescription("Armour these wings give at quality 1.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 100f), Array.Empty())), ArmorPerLevel = Bind(section, "ArmorPerLevel", armorPerLevel, new ConfigDescription("Extra armour per quality level above 1.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 50f), Array.Empty())), Weight = Bind(section, "Weight", weight, new ConfigDescription("Carry weight of the wings.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 100f), Array.Empty())), MaxDurability = Bind(section, "MaxDurability", durability, new ConfigDescription("Durability at quality 1. Each quality level adds 50 on top, as vanilla armour does.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 10000f), Array.Empty())), DamageModifiers = Bind(section, "DamageModifiers", damageModifiers, "Damage resistances the wings grant. Format: Type:Modifier,Type:Modifier. Types: Blunt, Slash, Pierce, Chop, Pickaxe, Fire, Frost, Lightning, Poison, Spirit. Modifiers: Normal, Resistant, VeryResistant, SlightlyResistant, Weak, VeryWeak, SlightlyWeak, Immune, Ignore. Empty for none."), JumpStaminaModifier = Bind(section, "JumpStaminaModifier", jump, new ConfigDescription("Change to jump stamina cost while worn. Negative is cheaper - wings should make leaving the ground easy.", (AcceptableValueBase)(object)val, Array.Empty())), RunStaminaModifier = Bind(section, "RunStaminaModifier", run, new ConfigDescription("Change to run stamina cost while worn. Negative is cheaper.", (AcceptableValueBase)(object)val, Array.Empty())), SneakStaminaModifier = Bind(section, "SneakStaminaModifier", sneak, new ConfigDescription("Change to sneak stamina cost while worn. Negative is cheaper.", (AcceptableValueBase)(object)val, Array.Empty())), EitrRegenModifier = Bind(section, "EitrRegenModifier", eitr, new ConfigDescription("Change to eitr regeneration while worn. Positive is faster.", (AcceptableValueBase)(object)val, Array.Empty())) }; } public static TierConfig GetTier(string wingsName) { return wingsName switch { "WingsOf_Troll" => Troll, "WingsOf_Lox" => Lox, "WingsOf_Dragon" => Dragon, _ => Crude, }; } public static WingStats GetStats(string wingsName) { return GetStats(wingsName, 1); } public static WingStats GetStats(string wingsName, int quality) { TierConfig tier = GetTier(wingsName); int num = Mathf.Clamp(quality, 1, Mathf.Max(1, MaxQuality.Value)) - 1; float num2 = 1f + CeilingBonusPerLevel.Value * (float)num; float num3 = 1f + GlideSpeedBonusPerLevel.Value * (float)num; float num4 = 1f + FlapForceBonusPerLevel.Value * (float)num; float num5 = Mathf.Max(0f, 1f - FlapStaminaReductionPerLevel.Value * (float)num); return new WingStats(tier.FlightCeiling.Value * num2, tier.GlideSpeed.Value * num3, tier.FlapForce.Value * num4, tier.FlapStaminaCost.Value * num5, tier.MinSkillToFlap.Value); } } internal static class ReflectionUtil { public static FieldRef TryFieldRef(string fieldName) { try { return AccessTools.FieldRefAccess(fieldName); } catch (Exception ex) { Log.LogWarning("Could not bind " + typeof(T).Name + "." + fieldName + " (" + ex.Message + "). The feature depending on it will be skipped."); return null; } } } internal static class ValkyrieInput { public static bool JumpPressed(Player player) { if (!AcceptsInput(player)) { return false; } if (ZInput.GetButtonDown("Jump")) { return true; } if (ZInput.GetButtonDown("JoyJump") && !Hud.InRadial()) { return !Hud.IsPieceSelectionVisible(); } return false; } private static bool AcceptsInput(Player player) { if ((Object)(object)player == (Object)null) { return false; } if (((Character)player).IsDead() || ((Character)player).InCutscene() || ((Character)player).IsTeleporting()) { return false; } if (Console.IsVisible()) { return false; } if ((Object)(object)Chat.instance != (Object)null && Chat.instance.HasFocus()) { return false; } if (TextInput.IsVisible()) { return false; } if (Menu.IsVisible()) { return false; } if (InventoryGui.IsVisible()) { return false; } if (StoreGui.IsVisible()) { return false; } if (Minimap.IsOpen()) { return false; } return true; } } [HarmonyPatch] public static class WingsFactory { private const string HolderName = "WingsoftheValkyrie_PrefabContainer"; private static GameObject _holder; private static readonly Dictionary Prefabs = new Dictionary(); private static readonly Dictionary Recipes = new Dictionary(); private static readonly Dictionary StationState = new Dictionary(); private static readonly MethodInfo UpdateRegistersMethod = AccessTools.Method(typeof(ObjectDB), "UpdateRegisters", (Type[])null, (Type[])null); private static readonly FieldInfo NamedPrefabsField = AccessTools.Field(typeof(ZNetScene), "m_namedPrefabs"); public static void Init() { EnsureHolder(); if (ModConfig.File != null) { ModConfig.File.SettingChanged += OnConfigChanged; } } private static void OnConfigChanged(object sender, EventArgs args) { if (Prefabs.Count == 0) { return; } try { WingsTier[] tiers = WingsItem.Tiers; foreach (WingsTier wingsTier in tiers) { if (Prefabs.TryGetValue(wingsTier.PrefabName, out var value)) { ApplyStats(wingsTier, value); } } EnsureRecipes(); } catch (Exception ex) { Log.LogWarning("Could not re-apply the wing stats after a config change; the previous values stay in force. Reason: " + ex.Message); } } private static void EnsureHolder() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown if (!((Object)(object)_holder != (Object)null)) { _holder = new GameObject("WingsoftheValkyrie_PrefabContainer"); _holder.SetActive(false); Object.DontDestroyOnLoad((Object)(object)_holder); } } internal static void EnsureItems() { ObjectDB instance = ObjectDB.instance; if ((Object)(object)instance == (Object)null || instance.m_items == null || instance.m_items.Count == 0 || (Object)(object)instance.GetItemPrefab("Wood") == (Object)null) { return; } EnsureHolder(); bool flag = false; WingsTier[] tiers = WingsItem.Tiers; foreach (WingsTier wingsTier in tiers) { try { GameObject val = BuildOrGet(instance, wingsTier); if (!((Object)(object)val == (Object)null)) { ApplyStats(wingsTier, val); if (!instance.m_items.Contains(val)) { instance.m_items.Add(val); flag = true; } } } catch (Exception arg) { Log.LogError($"Could not build {wingsTier.PrefabName}; that tier will not exist this session. Reason: {arg}"); } } if (flag) { RebuildRegisters(instance); } } private static GameObject BuildOrGet(ObjectDB db, WingsTier tier) { if (Prefabs.TryGetValue(tier.PrefabName, out var value) && (Object)(object)value != (Object)null) { return value; } GameObject itemPrefab = db.GetItemPrefab(tier.DonorPrefab); if ((Object)(object)itemPrefab == (Object)null) { Log.LogError("Donor prefab '" + tier.DonorPrefab + "' is missing from the ObjectDB, so " + tier.PrefabName + " cannot be built."); return null; } if ((Object)(object)db.GetItemPrefab(tier.Hash) != (Object)null) { Log.LogError("Something else already owns the item name '" + tier.PrefabName + "'. Refusing to replace it."); return null; } GameObject val = Object.Instantiate(itemPrefab, _holder.transform, false); ((Object)val).name = tier.PrefabName; Prefabs[tier.PrefabName] = val; Log.LogInfo("Forged " + tier.PrefabName + " from " + tier.DonorPrefab + "."); return val; } private static void RebuildRegisters(ObjectDB db) { if (UpdateRegistersMethod == null) { Log.LogError("ObjectDB.UpdateRegisters could not be found, so the wings cannot be indexed. They will not be craftable this session."); } else { UpdateRegistersMethod.Invoke(db, null); } } internal static void EnsurePrefabs() { ZNetScene instance = ZNetScene.instance; if ((Object)(object)instance == (Object)null || Prefabs.Count == 0) { return; } if (NamedPrefabsField == null) { Log.LogError("ZNetScene.m_namedPrefabs could not be found. Dropped wings would be destroyed by the server, so they are not being registered for spawning."); } else { if (!(NamedPrefabsField.GetValue(instance) is Dictionary dictionary)) { return; } WingsTier[] tiers = WingsItem.Tiers; foreach (WingsTier wingsTier in tiers) { if (Prefabs.TryGetValue(wingsTier.PrefabName, out var value) && !((Object)(object)value == (Object)null)) { if (!instance.m_prefabs.Contains(value)) { instance.m_prefabs.Add(value); } if (!dictionary.ContainsKey(wingsTier.Hash)) { dictionary[wingsTier.Hash] = value; } } } } } internal static void EnsureRecipes() { ObjectDB instance = ObjectDB.instance; if ((Object)(object)instance == (Object)null || Prefabs.Count == 0) { return; } WingsTier[] tiers = WingsItem.Tiers; foreach (WingsTier tier in tiers) { try { if (!Prefabs.TryGetValue(tier.PrefabName, out var value) || (Object)(object)value == (Object)null) { continue; } ItemDrop component = value.GetComponent(); if ((Object)(object)component == (Object)null) { continue; } if (!Recipes.TryGetValue(tier.PrefabName, out var recipe) || (Object)(object)recipe == (Object)null) { recipe = ScriptableObject.CreateInstance(); ((Object)recipe).name = "Recipe_" + tier.PrefabName; ((Object)recipe).hideFlags = (HideFlags)61; Recipes[tier.PrefabName] = recipe; } ModConfig.TierConfig config = tier.Config; string stationName = config.CraftingStation.Value; CraftingStation val = null; if (string.IsNullOrEmpty(stationName)) { goto IL_0198; } if (!((Object)(object)ZNetScene.instance == (Object)null)) { val = FindStation(stationName); if (!((Object)(object)val == (Object)null)) { goto IL_0198; } LogStation(tier, "missing:" + stationName, delegate { Log.LogError("Crafting station '" + stationName + "' does not exist, so " + tier.DisplayName + " cannot be crafted. Fix CraftingStation in the config (or clear it to make them craftable with no station)."); }); recipe.m_enabled = false; instance.m_recipes.Remove(recipe); } goto end_IL_0038; IL_0198: recipe.m_item = component; recipe.m_amount = 1; recipe.m_enabled = true; recipe.m_minStationLevel = Mathf.Max(1, config.MinStationLevel.Value); recipe.m_craftingStation = val; recipe.m_repairStation = val; recipe.m_resources = BuildRequirements(instance, tier, config); if (!instance.m_recipes.Contains(recipe)) { instance.m_recipes.Add(recipe); } LogStation(tier, $"ok:{stationName}:{recipe.m_minStationLevel}", delegate { Log.LogInfo(string.IsNullOrEmpty(stationName) ? (tier.PrefabName + " is craftable with no station.") : $"{tier.PrefabName} bound to station '{stationName}' at level {recipe.m_minStationLevel}."); }); end_IL_0038:; } catch (Exception arg) { Log.LogError($"Could not build the recipe for {tier.PrefabName}. Reason: {arg}"); } } } private static CraftingStation FindStation(string stationPrefabName) { if (string.IsNullOrEmpty(stationPrefabName)) { return null; } if ((Object)(object)ZNetScene.instance == (Object)null) { return null; } GameObject prefab = ZNetScene.instance.GetPrefab(stationPrefabName); if (!((Object)(object)prefab != (Object)null)) { return null; } return prefab.GetComponent(); } private static void LogStation(WingsTier tier, string state, Action write) { if (!StationState.TryGetValue(tier.PrefabName, out var value) || !(value == state)) { StationState[tier.PrefabName] = state; write(); } } private static void ApplyStats(WingsTier tier, GameObject prefab) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) ItemDrop component = prefab.GetComponent(); if (!((Object)(object)component == (Object)null) && component.m_itemData != null && component.m_itemData.m_shared != null) { SharedData shared = component.m_itemData.m_shared; ModConfig.TierConfig config = tier.Config; shared.m_name = tier.DisplayName; shared.m_description = tier.Description; shared.m_itemType = (ItemType)17; shared.m_maxStackSize = 1; shared.m_maxQuality = Mathf.Clamp(ModConfig.MaxQuality.Value, 1, 4); shared.m_weight = config.Weight.Value; shared.m_teleportable = true; shared.m_armor = config.Armor.Value; shared.m_armorPerLevel = config.ArmorPerLevel.Value; shared.m_damageModifiers = ParseDamageModifiers(config.DamageModifiers.Value, tier.PrefabName); shared.m_useDurability = true; shared.m_destroyBroken = false; shared.m_canBeReparied = true; shared.m_maxDurability = config.MaxDurability.Value; shared.m_durabilityPerLevel = 50f; shared.m_jumpStaminaModifier = config.JumpStaminaModifier.Value; shared.m_runStaminaModifier = config.RunStaminaModifier.Value; shared.m_sneakStaminaModifier = config.SneakStaminaModifier.Value; shared.m_eitrRegenModifier = config.EitrRegenModifier.Value; shared.m_setName = ""; shared.m_setSize = 0; shared.m_setStatusEffect = null; shared.m_equipStatusEffect = null; ApplyIcon(tier, shared); DisableCloth(prefab); } } private static void ApplyIcon(WingsTier tier, SharedData shared) { Sprite val = IconLoader.Load(tier.IconFile); if (!((Object)(object)val == (Object)null) && (shared.m_icons == null || shared.m_icons.Length != 1 || !((Object)(object)shared.m_icons[0] == (Object)(object)val))) { shared.m_icons = (Sprite[])(object)new Sprite[1] { val }; } } private static void DisableCloth(GameObject prefab) { Component[] componentsInChildren = prefab.GetComponentsInChildren(true); foreach (Component val in componentsInChildren) { if (!((Object)(object)val == (Object)null) && !(((object)val).GetType().Name != "Cloth")) { PropertyInfo property = ((object)val).GetType().GetProperty("enabled"); if (property != null) { property.SetValue(val, false, null); } } } } private static Requirement[] BuildRequirements(ObjectDB db, WingsTier tier, ModConfig.TierConfig cfg) { //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Expected O, but got Unknown Dictionary dictionary = ParseAmounts(cfg.CraftingRequirements.Value, tier.PrefabName, "CraftingRequirements"); Dictionary dictionary2 = ParseAmounts(cfg.UpgradeRequirements.Value, tier.PrefabName, "UpgradeRequirements"); List list = new List(dictionary.Keys); foreach (string key in dictionary2.Keys) { if (!dictionary.ContainsKey(key)) { list.Add(key); } } List list2 = new List(list.Count); foreach (string item in list) { GameObject itemPrefab = db.GetItemPrefab(item); ItemDrop val = (((Object)(object)itemPrefab != (Object)null) ? itemPrefab.GetComponent() : null); if ((Object)(object)val == (Object)null) { Log.LogWarning(tier.PrefabName + ": ingredient '" + item + "' is not a known item, so it is being left out of the recipe."); continue; } list2.Add(new Requirement { m_resItem = val, m_amount = (dictionary.TryGetValue(item, out var value) ? value : 0), m_amountPerLevel = (dictionary2.TryGetValue(item, out var value2) ? value2 : 0), m_recover = true }); } return list2.ToArray(); } private static Dictionary ParseAmounts(string value, string tierName, string key) { Dictionary dictionary = new Dictionary(); if (string.IsNullOrEmpty(value)) { return dictionary; } string[] array = value.Split(new char[1] { ',' }); foreach (string text in array) { if (!string.IsNullOrEmpty(text.Trim())) { string[] array2 = text.Split(new char[1] { ':' }); if (array2.Length != 2 || !int.TryParse(array2[1].Trim(), out var result) || result < 0) { Log.LogWarning(tierName + ": could not read '" + text.Trim() + "' in " + key + ". Expected ItemName:Amount."); } else { dictionary[array2[0].Trim()] = result; } } } return dictionary; } private static List ParseDamageModifiers(string value, string tierName) { //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Invalid comparison between Unknown and I4 //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) List list = new List(); if (string.IsNullOrEmpty(value)) { return list; } string[] array = value.Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.Length == 0) { continue; } string[] array2 = text.Split(new char[1] { ':' }); if (array2.Length != 2) { Log.LogWarning(tierName + ": could not read '" + text + "' in DamageModifiers. Expected Type:Modifier."); continue; } string text2 = array2[0].Trim(); string text3 = array2[1].Trim(); if (!TryParseEnum(text2, out DamageType parsed) || (int)parsed == 31 || (int)parsed == 224) { Log.LogWarning(tierName + ": '" + text2 + "' is not a damage type that can carry a resistance."); continue; } if (!TryParseEnum(text3, out DamageModifier parsed2)) { Log.LogWarning(tierName + ": '" + text3 + "' is not a damage modifier."); continue; } list.Add(new DamageModPair { m_type = parsed, m_modifier = parsed2 }); } return list; } private static bool TryParseEnum(string name, out T parsed) where T : struct { string[] names = Enum.GetNames(typeof(T)); foreach (string text in names) { if (string.Equals(text, name, StringComparison.OrdinalIgnoreCase)) { parsed = (T)Enum.Parse(typeof(T), text); return true; } } parsed = default(T); return false; } [HarmonyPatch(typeof(ObjectDB), "Awake")] [HarmonyPostfix] private static void ObjectDBAwakePostfix() { EnsureItems(); EnsurePrefabs(); EnsureRecipes(); } [HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")] [HarmonyPostfix] private static void ObjectDBCopyOtherDBPostfix() { EnsureItems(); EnsurePrefabs(); EnsureRecipes(); } [HarmonyPatch(typeof(ZNetScene), "Awake")] [HarmonyPostfix] private static void ZNetSceneAwakePostfix() { EnsureItems(); EnsurePrefabs(); EnsureRecipes(); } } public sealed class WingsTier { public readonly string PrefabName; public readonly string DonorPrefab; public readonly string DisplayName; public readonly string Description; public readonly string IconFile; public readonly int Hash; public ModConfig.TierConfig Config => ModConfig.GetTier(PrefabName); public WingsTier(string prefabName, string donorPrefab, string displayName, string description, string iconFile) { PrefabName = prefabName; DonorPrefab = donorPrefab; DisplayName = displayName; Description = description; IconFile = iconFile; Hash = StringExtensionMethods.GetStableHashCode(prefabName); } } public static class WingsItem { public const string CrudeName = "WingsOf_Crude"; public const string TrollName = "WingsOf_Troll"; public const string LoxName = "WingsOf_Lox"; public const string DragonName = "WingsOf_Dragon"; public static readonly WingsTier[] Tiers = new WingsTier[4] { new WingsTier("WingsOf_Crude", "CapeDeerHide", "Wings of the Valkyrie (Crude)", "Basic crafted wings. Low flight ceiling.", "wings_crude.png"), new WingsTier("WingsOf_Troll", "CapeTrollHide", "Wings of the Valkyrie (Troll)", "Improved glide and lift.", "wings_troll.png"), new WingsTier("WingsOf_Lox", "CapeLox", "Wings of the Valkyrie (Lox)", "High glide speed, strong lift.", "wings_lox.png"), new WingsTier("WingsOf_Dragon", "CapeFeather", "Wings of the Valkyrie (Dragon)", "Unlimited sky ceiling and excellent speed.", "wings_dragon.png") }; private static readonly int CrudeHash = StringExtensionMethods.GetStableHashCode("WingsOf_Crude"); private static readonly int TrollHash = StringExtensionMethods.GetStableHashCode("WingsOf_Troll"); private static readonly int LoxHash = StringExtensionMethods.GetStableHashCode("WingsOf_Lox"); private static readonly int DragonHash = StringExtensionMethods.GetStableHashCode("WingsOf_Dragon"); private static readonly FieldRef ShoulderItemRef = ReflectionUtil.TryFieldRef("m_shoulderItem"); private static readonly FieldRef TrinketItemRef = ReflectionUtil.TryFieldRef("m_trinketItem"); private static readonly FieldRef CurrentShoulderHashRef = ReflectionUtil.TryFieldRef("m_currentShoulderItemHash"); public static bool TrinketSlotAvailable => TrinketItemRef != null; public static void Init() { WingsFactory.Init(); } public static string GetWingsNameFromHash(int hash) { if (hash == CrudeHash) { return "WingsOf_Crude"; } if (hash == TrollHash) { return "WingsOf_Troll"; } if (hash == LoxHash) { return "WingsOf_Lox"; } if (hash == DragonHash) { return "WingsOf_Dragon"; } return null; } public static bool IsWingsHash(int hash) { return GetWingsNameFromHash(hash) != null; } public static int GetHashFromWingsName(string wingsName) { return wingsName switch { "WingsOf_Crude" => CrudeHash, "WingsOf_Troll" => TrollHash, "WingsOf_Lox" => LoxHash, "WingsOf_Dragon" => DragonHash, _ => 0, }; } public static bool IsWings(ItemData item) { if (item != null && (Object)(object)item.m_dropPrefab != (Object)null) { return IsWingsHash(StringExtensionMethods.GetStableHashCode(((Object)item.m_dropPrefab).name)); } return false; } internal static ItemData GetShoulderItem(Humanoid humanoid) { if (!((Object)(object)humanoid != (Object)null) || ShoulderItemRef == null) { return null; } return ShoulderItemRef.Invoke(humanoid); } internal static ItemData GetTrinketItem(Humanoid humanoid) { if (!((Object)(object)humanoid != (Object)null) || TrinketItemRef == null) { return null; } return TrinketItemRef.Invoke(humanoid); } public static ItemData GetEquippedWings(Player player) { if ((Object)(object)player == (Object)null) { return null; } ItemData shoulderItem = GetShoulderItem((Humanoid)(object)player); if (IsWings(shoulderItem)) { return shoulderItem; } ItemData trinketItem = GetTrinketItem((Humanoid)(object)player); if (!IsWings(trinketItem)) { return null; } return trinketItem; } public static string GetEquippedWingsName(Player player) { if ((Object)(object)player == (Object)null) { return null; } if (ShoulderItemRef == null && TrinketItemRef == null) { return GetVisualWingsName(player); } ItemData equippedWings = GetEquippedWings(player); if (equippedWings == null) { return null; } return GetWingsNameFromHash(StringExtensionMethods.GetStableHashCode(((Object)equippedWings.m_dropPrefab).name)); } public static int GetEquippedWingsQuality(Player player) { return GetEquippedWings(player)?.m_quality ?? 1; } public static string GetVisualWingsName(Player player) { if ((Object)(object)player == (Object)null || CurrentShoulderHashRef == null) { return null; } VisEquipment component = ((Component)player).GetComponent(); if (!((Object)(object)component != (Object)null)) { return null; } return GetWingsNameFromHash(CurrentShoulderHashRef.Invoke(component)); } public static bool IsWingsEquipped(Player player) { return GetEquippedWingsName(player) != null; } } [BepInPlugin("wubarrk.wingsofthevalkyrie", "Wings of the Valkyrie", "2.2.2")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class WingsoftheValkyriePlugin : BaseUnityPlugin { public const string PluginGUID = "wubarrk.wingsofthevalkyrie"; public const string PluginName = "Wings of the Valkyrie"; public const string PluginVersion = "2.2.2"; public const string SyncFloor = "2.1.4"; private readonly Harmony harmony = new Harmony("wubarrk.wingsofthevalkyrie"); private void Awake() { Log.Init(((BaseUnityPlugin)this).Logger); Log.LogInfo("Wings of the Valkyrie initializing..."); ModConfig.Init(((BaseUnityPlugin)this).Config); FlyingSkill.Register(); WingsItem.Init(); WingsSlot.Init(); FlightLogCommand.Register(); harmony.PatchAll(); FlyingSkill.VerifyPersistencePatch(); AzuEpiCompat.Init(harmony); Log.LogInfo("Wings of the Valkyrie has loaded!"); } private void Update() { if (ModConfig.EnableMod.Value) { FlightReport.Tick(Time.deltaTime); FlyingSkillRestore.Tick(Time.deltaTime); } } } public enum WingsSlotPolicy { Auto, Either, TrinketOnly, BackOnly } public enum WingsSlotChoice { Back, Trinket } [HarmonyPatch] public static class WingsSlot { private sealed class UpgradeMemory { public string PrefabName; public Vector2i GridPos; public WingsSlotChoice Slot; } private const string SlotKey = "wotv.slot"; private const string TrinketValue = "trinket"; private const string BackValue = "back"; private static readonly Dictionary Pending = new Dictionary(); private static bool _reseatWanted; private static float _reseatRetryAt; private static int _reseatAttempts; private const int ReseatMaxAttempts = 5; private const float ReseatRetrySeconds = 2f; private static bool _moving; private static bool _warnedNoTrinketSlot; private static readonly FieldRef ChestItemRef = ReflectionUtil.TryFieldRef("m_chestItem"); private static readonly FieldRef LegItemRef = ReflectionUtil.TryFieldRef("m_legItem"); private static readonly FieldRef HelmetItemRef = ReflectionUtil.TryFieldRef("m_helmetItem"); private static readonly FieldRef CraftUpgradeItemRef = ReflectionUtil.TryFieldRef("m_craftUpgradeItem"); public static void Init() { if (ModConfig.File != null) { ModConfig.File.SettingChanged += OnSettingChanged; } } internal static WingsSlotChoice Choose(Player player, ItemData wings, bool playerInitiated) { if (!TrinketSlotUsable(wings)) { return WingsSlotChoice.Back; } switch (ModConfig.SlotPolicy.Value) { case WingsSlotPolicy.BackOnly: return WingsSlotChoice.Back; case WingsSlotPolicy.TrinketOnly: return WingsSlotChoice.Trinket; case WingsSlotPolicy.Either: { if (playerInitiated) { WingsSlotChoice value = ModConfig.PreferredWingsSlot.Value; if (!AlternateKeyHeld()) { return value; } return Other(value); } if (!TryRemembered(wings, out var slot2)) { return ModConfig.PreferredWingsSlot.Value; } return slot2; } default: { if (!playerInitiated && TryRemembered(wings, out var slot)) { return slot; } ItemData shoulderItem = WingsItem.GetShoulderItem((Humanoid)(object)player); ItemData trinketItem = WingsItem.GetTrinketItem((Humanoid)(object)player); if (WingsItem.IsWings(shoulderItem)) { return WingsSlotChoice.Back; } if (WingsItem.IsWings(trinketItem)) { return WingsSlotChoice.Trinket; } if (shoulderItem == null) { return WingsSlotChoice.Back; } if (trinketItem == null) { return WingsSlotChoice.Trinket; } return WingsSlotChoice.Back; } } } private static bool TrinketSlotUsable(ItemData wings) { if (!WingsItem.TrinketSlotAvailable) { if (!_warnedNoTrinketSlot) { _warnedNoTrinketSlot = true; Log.LogWarning("This game build has no trinket slot the mod can find, so the wings stay on the back whatever WingsSlot says."); } return false; } return !MadeOnLowerWorldLevel(wings); } private static bool MadeOnLowerWorldLevel(ItemData wings) { if (Game.m_worldLevel > 0 && wings != null) { return wings.m_worldLevel < Game.m_worldLevel; } return false; } internal static bool MayUseTrinketSlot(ItemData wings) { if (ModConfig.SlotPolicy.Value != WingsSlotPolicy.BackOnly) { return TrinketSlotUsable(wings); } return false; } internal static void NoteDragTarget(ItemData wings, WingsSlotChoice target) { if (wings != null) { switch (ModConfig.SlotPolicy.Value) { case WingsSlotPolicy.BackOnly: target = WingsSlotChoice.Back; break; case WingsSlotPolicy.TrinketOnly: target = WingsSlotChoice.Trinket; break; } if (!TrinketSlotUsable(wings)) { target = WingsSlotChoice.Back; } Pending[wings] = target; } } internal static void ForgetDragTarget(ItemData wings) { if (wings != null) { Pending.Remove(wings); } } private static bool AlternateKeyHeld() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) KeyboardShortcut value = ModConfig.AlternateSlotKey.Value; if ((int)((KeyboardShortcut)(ref value)).MainKey != 0) { return ((KeyboardShortcut)(ref value)).IsPressed(); } return false; } [HarmonyPatch(typeof(Player), "ToggleEquipped")] [HarmonyPrefix] private static void ToggleEquippedPrefix(Player __instance, ItemData item) { if (WingsItem.IsWings(item) && !((Humanoid)__instance).IsItemEquiped(item) && !((Character)__instance).InAttack()) { if (__instance.IsEquipActionQueued(item)) { Pending.Remove(item); } else { Pending[item] = Choose(__instance, item, playerInitiated: true); } } } [HarmonyPatch(typeof(Player), "RemoveEquipAction")] [HarmonyPostfix] private static void RemoveEquipActionPostfix(ItemData item) { if (item != null) { Pending.Remove(item); } } [HarmonyPatch(typeof(Player), "ClearActionQueue")] [HarmonyPostfix] private static void ClearActionQueuePostfix() { Pending.Clear(); } [HarmonyPatch(typeof(Humanoid), "EquipItem")] [HarmonyPrefix] private static void EquipItemPrefix(Humanoid __instance, ItemData item, out ItemType? __state) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) __state = null; Player val = (Player)(object)((__instance is Player) ? __instance : null); if (val != null && WingsItem.IsWings(item) && !((Humanoid)val).IsItemEquiped(item)) { if (Pending.TryGetValue(item, out var value)) { Pending.Remove(item); } else { value = Choose(val, item, playerInitiated: false); } if (value == WingsSlotChoice.Trinket) { __state = item.m_shared.m_itemType; item.m_shared.m_itemType = (ItemType)24; } } } [HarmonyPatch(typeof(Humanoid), "EquipItem")] [HarmonyPostfix] private static void EquipItemPostfix(Humanoid __instance, ItemData item, bool triggerEquipEffects, bool __result) { if (!__result) { return; } Player val = (Player)(object)((__instance is Player) ? __instance : null); if (val != null && WingsItem.IsWings(item)) { bool flag = WingsItem.GetTrinketItem((Humanoid)(object)val) == item; ItemData val2 = (flag ? WingsItem.GetShoulderItem((Humanoid)(object)val) : WingsItem.GetTrinketItem((Humanoid)(object)val)); if (val2 != null && val2 != item && WingsItem.IsWings(val2)) { ((Humanoid)val).UnequipItem(val2, triggerEquipEffects); } Remember(item, flag ? WingsSlotChoice.Trinket : WingsSlotChoice.Back); WingsSlotPolicy value = ModConfig.SlotPolicy.Value; if (triggerEquipEffects && (Object)(object)val == (Object)(object)Player.m_localPlayer && (value == WingsSlotPolicy.Auto || value == WingsSlotPolicy.Either)) { ((Character)val).Message((MessageType)1, flag ? "Wings in your trinket slot." : "Wings on your back.", 0, (Sprite)null, false); } } } [HarmonyPatch(typeof(Humanoid), "EquipItem")] [HarmonyFinalizer] private static void EquipItemFinalizer(ItemData item, ItemType? __state) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) if (__state.HasValue && item != null && item.m_shared != null) { item.m_shared.m_itemType = __state.Value; } } [HarmonyPatch(typeof(Player), "GetBodyArmor")] [HarmonyPostfix] private static void GetBodyArmorPostfix(Player __instance, ref float __result) { ItemData val = TrinketWings(__instance); if (val != null) { float armor = val.GetArmor(); float num = 0f; SEMan sEMan = ((Character)__instance).GetSEMan(); if (sEMan != null) { sEMan.ApplyArmorMods(ref armor); sEMan.ApplyArmorMods(ref num); } __result += armor - num; } } [HarmonyPatch(typeof(Player), "ApplyArmorDamageMods")] [HarmonyPostfix] private static void ApplyArmorDamageModsPostfix(Player __instance, ref DamageModifiers mods) { ItemData val = TrinketWings(__instance); if (val != null) { ((DamageModifiers)(ref mods)).Apply(val.m_shared.m_damageModifiers); } } [HarmonyPatch(typeof(Player), "GetEquipmentEitrRegenModifier")] [HarmonyPostfix] private static void GetEquipmentEitrRegenModifierPostfix(Player __instance, ref float __result) { ItemData val = TrinketWings(__instance); if (val != null) { __result += val.m_shared.m_eitrRegenModifier; } } [HarmonyPatch(typeof(Player), "DamageArmorDurability")] [HarmonyPrefix] private static bool DamageArmorDurabilityPrefix(Player __instance, HitData hit) { ItemData val = TrinketWings(__instance); if (val == null || hit == null) { return true; } if (ChestItemRef == null || LegItemRef == null || HelmetItemRef == null) { return true; } float num = hit.GetTotalPhysicalDamage() + hit.GetTotalElementalDamage(); if (num <= 0f) { return true; } int num2 = 0; if (ChestItemRef.Invoke((Humanoid)(object)__instance) != null) { num2++; } if (LegItemRef.Invoke((Humanoid)(object)__instance) != null) { num2++; } if (HelmetItemRef.Invoke((Humanoid)(object)__instance) != null) { num2++; } if (WingsItem.GetShoulderItem((Humanoid)(object)__instance) != null) { num2++; } if (Random.Range(0, num2 + 1) != num2) { return true; } val.m_durability = Mathf.Max(0f, val.m_durability - num); return false; } [HarmonyPatch(typeof(Player), "TryGetArmorDifference")] [HarmonyPrefix] private static bool TryGetArmorDifferencePrefix(Player __instance, ItemData item, ref float difference, ref bool __result) { if (!WingsItem.IsWings(item)) { return true; } ItemData trinketItem = WingsItem.GetTrinketItem((Humanoid)(object)__instance); if (trinketItem == item) { difference = 0f - item.m_shared.m_armor; __result = true; return false; } if (((Humanoid)__instance).IsItemEquiped(item)) { return true; } if (Choose(__instance, item, playerInitiated: true) != WingsSlotChoice.Trinket) { return true; } difference = item.m_shared.m_armor - (WingsItem.IsWings(trinketItem) ? trinketItem.m_shared.m_armor : 0f); __result = true; return false; } [HarmonyPatch(typeof(InventoryGui), "DoCrafting")] [HarmonyPrefix] private static void DoCraftingPrefix(InventoryGui __instance, out UpgradeMemory __state) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) __state = null; if (CraftUpgradeItemRef != null) { ItemData val = CraftUpgradeItemRef.Invoke(__instance); if (WingsItem.IsWings(val) && TryRemembered(val, out var slot)) { __state = new UpgradeMemory { PrefabName = ((Object)val.m_dropPrefab).name, GridPos = val.m_gridPos, Slot = slot }; } } } [HarmonyPatch(typeof(InventoryGui), "DoCrafting")] [HarmonyPostfix] private static void DoCraftingPostfix(Player player, UpgradeMemory __state) { if (__state != null && !((Object)(object)player == (Object)null)) { Inventory inventory = ((Humanoid)player).GetInventory(); ItemData val = ((inventory != null) ? inventory.GetItemAt(__state.GridPos.x, __state.GridPos.y) : null); if (WingsItem.IsWings(val) && !(((Object)val.m_dropPrefab).name != __state.PrefabName) && !TryRemembered(val, out var _)) { Remember(val, __state.Slot); } } } private static void OnSettingChanged(object sender, SettingChangedEventArgs args) { if (ModConfig.SlotPolicy != null && args != null && (object)args.ChangedSetting == ModConfig.SlotPolicy.SourceConfig) { _reseatWanted = true; _reseatAttempts = 0; _reseatRetryAt = 0f; } } internal static void Tick(Player player) { if (!_reseatWanted || (Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer) { return; } ItemData equippedWings = WingsItem.GetEquippedWings(player); if (equippedWings == null) { _reseatWanted = false; return; } WingsSlotChoice wingsSlotChoice = ((WingsItem.GetTrinketItem((Humanoid)(object)player) == equippedWings) ? WingsSlotChoice.Trinket : WingsSlotChoice.Back); WingsSlotChoice wingsSlotChoice2 = wingsSlotChoice; switch (ModConfig.SlotPolicy.Value) { case WingsSlotPolicy.TrinketOnly: wingsSlotChoice2 = WingsSlotChoice.Trinket; break; case WingsSlotPolicy.BackOnly: wingsSlotChoice2 = WingsSlotChoice.Back; break; } if (!TrinketSlotUsable(equippedWings)) { wingsSlotChoice2 = WingsSlotChoice.Back; } if (wingsSlotChoice2 == wingsSlotChoice) { _reseatWanted = false; } else { if (!SafeToMove(player) || Time.time < _reseatRetryAt) { return; } if (Move(player, equippedWings, wingsSlotChoice2)) { _reseatWanted = false; ((Character)player).Message((MessageType)1, (wingsSlotChoice2 == WingsSlotChoice.Trinket) ? "The server moved your wings to the trinket slot." : "The server moved your wings to your back.", 0, (Sprite)null, false); return; } _reseatAttempts++; _reseatRetryAt = Time.time + 2f; if (_reseatAttempts >= 5) { _reseatWanted = false; Log.LogWarning($"The wings could not be moved to the slot WingsSlot now requires after {5} attempts; they stay where they are until re-equipped."); } } } private static bool SafeToMove(Player player) { if (((Character)player).IsOnGround() && !((Character)player).IsSwimming() && !((Character)player).InWater() && !((Character)player).InAttack() && !((Character)player).InDodge() && !((Character)player).IsDead()) { return !((Character)player).IsTeleporting(); } return false; } private static bool Move(Player player, ItemData wings, WingsSlotChoice slot) { if (_moving || (Object)(object)player == (Object)null || wings == null) { return false; } WingsSlotChoice value = ((WingsItem.GetTrinketItem((Humanoid)(object)player) == wings) ? WingsSlotChoice.Trinket : WingsSlotChoice.Back); _moving = true; try { ((Humanoid)player).UnequipItem(wings, false); Pending[wings] = slot; if (((Humanoid)player).EquipItem(wings, false)) { return true; } Pending[wings] = value; if (!((Humanoid)player).EquipItem(wings, false)) { Log.LogWarning("The wings could not be re-equipped after a slot change; they are in the inventory."); } return false; } finally { Pending.Remove(wings); _moving = false; } } internal static IEnumerable Command(Player player, string argument) { WingsSlotPolicy policy = ModConfig.SlotPolicy.Value; ItemData wings = WingsItem.GetEquippedWings(player); string worn = ((wings == null) ? "You are not wearing wings." : ("Your wings are " + Describe((WingsItem.GetTrinketItem((Humanoid)(object)player) == wings) ? WingsSlotChoice.Trinket : WingsSlotChoice.Back) + ".")); if (string.IsNullOrEmpty(argument)) { yield return "Server rule (WingsSlot): " + policy.ToString() + ". " + DescribePolicy(policy); yield return "Your preference (PreferredWingsSlot): " + Describe(ModConfig.PreferredWingsSlot.Value) + ". Alternate key: " + ((object)ModConfig.AlternateSlotKey.Value/*cast due to .constrained prefix*/).ToString() + "."; yield return worn; yield break; } WingsSlotChoice choice; if (!(argument == "back")) { if (!(argument == "trinket")) { yield return "Say 'wov slot back' or 'wov slot trinket'."; yield break; } choice = WingsSlotChoice.Trinket; } else { choice = WingsSlotChoice.Back; } ModConfig.PreferredWingsSlot.Value = choice; yield return "Preferred wing slot set to " + Describe(choice) + "."; if (policy != WingsSlotPolicy.Either) { yield return "The server's rule is " + policy.ToString() + ", so the preference waits until an admin sets WingsSlot to Either."; } else if (wings == null) { yield return "The next pair you equip goes there."; } else if (WingsItem.GetTrinketItem((Humanoid)(object)player) == wings == (choice == WingsSlotChoice.Trinket)) { yield return worn; } else if (choice == WingsSlotChoice.Trinket && !TrinketSlotUsable(wings)) { yield return MadeOnLowerWorldLevel(wings) ? "These wings were made on a lower world level, and the game will not take them as a trinket here. They stay on your back." : "This game build has no trinket slot the mod can find. They stay on your back."; } else if (!SafeToMove(player)) { yield return "Land first - wings are not moved in mid-air. Re-equip them once you are down, or run this again."; } else { yield return Move(player, wings, choice) ? ("Wings moved " + Describe(choice) + ".") : "The wings could not be moved right now and stay where they were."; } } private static ItemData TrinketWings(Player player) { ItemData trinketItem = WingsItem.GetTrinketItem((Humanoid)(object)player); if (!WingsItem.IsWings(trinketItem)) { return null; } return trinketItem; } private static bool TryRemembered(ItemData wings, out WingsSlotChoice slot) { slot = WingsSlotChoice.Back; if (wings == null || wings.m_customData == null || !wings.m_customData.TryGetValue("wotv.slot", out var value)) { return false; } if (value == "trinket") { slot = WingsSlotChoice.Trinket; return true; } return value == "back"; } private static void Remember(ItemData wings, WingsSlotChoice slot) { if (wings != null) { if (wings.m_customData == null) { wings.m_customData = new Dictionary(); } wings.m_customData["wotv.slot"] = ((slot == WingsSlotChoice.Trinket) ? "trinket" : "back"); } } private static WingsSlotChoice Other(WingsSlotChoice slot) { if (slot != WingsSlotChoice.Trinket) { return WingsSlotChoice.Trinket; } return WingsSlotChoice.Back; } private static string Describe(WingsSlotChoice slot) { if (slot != WingsSlotChoice.Trinket) { return "on your back"; } return "in the trinket slot"; } private static string DescribePolicy(WingsSlotPolicy policy) { return policy switch { WingsSlotPolicy.Either => "You choose - set a preference here, or hold the alternate key while equipping.", WingsSlotPolicy.TrinketOnly => "Wings always go in the trinket slot.", WingsSlotPolicy.BackOnly => "Wings always go on your back.", _ => "Wings go on your back unless a cape is already there and the trinket slot is free.", }; } } } namespace WingsoftheValkyrie.VFX { public class RuneWingVFX : MonoBehaviour { private Player _player; private ParticleSystem _leftWing; private ParticleSystem _rightWing; private Transform _leftRoot; private Transform _rightRoot; private LineRenderer[] _leftLines = (LineRenderer[])(object)new LineRenderer[7]; private LineRenderer[] _rightLines = (LineRenderer[])(object)new LineRenderer[7]; private MeshFilter _leftMeshFilter; private MeshFilter _rightMeshFilter; private Mesh _leftMesh; private Mesh _rightMesh; private bool _isGliding; private float _flapTimer; private Color _currentTierColor = Color.clear; private Vector3 _lastEmitPosL; private Vector3 _lastEmitPosR; public bool IsGlidingLocal; public bool WantsToFlap; public int FlapCount; public int LastSeenFlapCount = int.MinValue; private Color[] _whiteColors; public ZNetView NView { get; private set; } private void Awake() { _player = ((Component)this).GetComponent(); NView = ((Component)this).GetComponent(); } public void EnsureEmitters() { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_leftWing != (Object)null) || !((Object)(object)_rightWing != (Object)null)) { Transform transform = ((Component)_player).transform; Material orCreateRuneMaterial = ValkyrieRuneVFX_Helper.GetOrCreateRuneMaterial(ValkyrieRuneTextureGenerator.GenerateSoftTrail(Color.white), Color.white); Material orCreateRuneMaterial2 = ValkyrieRuneVFX_Helper.GetOrCreateRuneMaterial(ValkyrieRuneTextureGenerator.GenerateRuneAtlas(Color.white), Color.white); _leftRoot = new GameObject("RuneWing_Left").transform; ((Component)_leftRoot).gameObject.layer = ((Component)_player).gameObject.layer; _leftRoot.SetParent(transform, false); _leftRoot.localPosition = new Vector3(-0.3f, 1.2f, -0.3f); _rightRoot = new GameObject("RuneWing_Right").transform; ((Component)_rightRoot).gameObject.layer = ((Component)_player).gameObject.layer; _rightRoot.SetParent(transform, false); _rightRoot.localPosition = new Vector3(0.3f, 1.2f, -0.3f); InitWingObjects(((Component)_leftRoot).gameObject, orCreateRuneMaterial, orCreateRuneMaterial2, isRight: false, ref _leftLines, out _leftMeshFilter, out _leftMesh); InitWingObjects(((Component)_rightRoot).gameObject, orCreateRuneMaterial, orCreateRuneMaterial2, isRight: true, ref _rightLines, out _rightMeshFilter, out _rightMesh); _leftWing = CreateParticleSystem(((Component)_leftRoot).gameObject, orCreateRuneMaterial2); _rightWing = CreateParticleSystem(((Component)_rightRoot).gameObject, orCreateRuneMaterial2); UpdateWingMeshes(0f, 0f); } } private void InitWingObjects(GameObject root, Material lineMat, Material atlasMat, bool isRight, ref LineRenderer[] lines, out MeshFilter meshFilter, out Mesh mesh) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown //IL_00e4: 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_00f3: 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_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_0214: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_0230: 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) //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_0272: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_0289: Unknown result type (might be due to invalid IL or missing references) //IL_0293: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_02aa: Unknown result type (might be due to invalid IL or missing references) //IL_02b4: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02cb: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: 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) //IL_0372: Unknown result type (might be due to invalid IL or missing references) //IL_0378: Expected O, but got Unknown //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < 7; i++) { GameObject val = new GameObject("BoneLine_" + i) { layer = root.layer }; val.transform.SetParent(root.transform, false); LineRenderer val2 = val.AddComponent(); val2.useWorldSpace = false; ((Renderer)val2).material = lineMat; ((Renderer)val2).enabled = false; lines[i] = val2; } mesh = new Mesh(); mesh.MarkDynamic(); mesh.vertices = (Vector3[])(object)new Vector3[23]; if (_whiteColors == null) { _whiteColors = (Color[])(object)new Color[23]; for (int j = 0; j < 23; j++) { _whiteColors[j] = Color.white; } } mesh.colors = _whiteColors; Vector2[] uv = (Vector2[])(object)new Vector2[23] { new Vector2(0f, 1f) * 3f, new Vector2(0.2f, 0.8f) * 3f, new Vector2(0.3f, 1f) * 3f, new Vector2(0.5f, 0.9f) * 3f, new Vector2(0.7f, 0.8f) * 3f, new Vector2(1f, 0.8f) * 3f, new Vector2(0.5f, 0.6f) * 3f, new Vector2(0.7f, 0.5f) * 3f, new Vector2(1f, 0.5f) * 3f, new Vector2(0.4f, 0.4f) * 3f, new Vector2(0.6f, 0.3f) * 3f, new Vector2(0.9f, 0.2f) * 3f, new Vector2(0.3f, 0.2f) * 3f, new Vector2(0.4f, 0.1f) * 3f, new Vector2(0.6f, 0f) * 3f, new Vector2(0f, 0f) * 3f, default(Vector2), default(Vector2), default(Vector2), default(Vector2), default(Vector2), default(Vector2), default(Vector2) }; mesh.uv = uv; int[] array = new int[63] { 0, 1, 2, 2, 6, 3, 3, 6, 7, 3, 7, 4, 4, 7, 8, 4, 8, 5, 2, 9, 6, 6, 9, 10, 6, 10, 7, 7, 10, 11, 7, 11, 8, 2, 12, 9, 9, 12, 13, 9, 13, 10, 10, 13, 14, 10, 14, 11, 2, 1, 12, 1, 0, 12, 0, 15, 12, 15, 13, 12, 15, 14, 13 }; int[] array2 = new int[array.Length * 2]; for (int k = 0; k < array.Length; k += 3) { array2[k] = array[k]; array2[k + 1] = array[k + 1]; array2[k + 2] = array[k + 2]; array2[array.Length + k] = array[k]; array2[array.Length + k + 1] = array[k + 2]; array2[array.Length + k + 2] = array[k + 1]; } mesh.triangles = array2; GameObject val3 = new GameObject("Membrane"); val3.layer = root.layer; val3.transform.SetParent(root.transform, false); meshFilter = val3.AddComponent(); meshFilter.mesh = mesh; MeshRenderer obj = val3.AddComponent(); ((Renderer)obj).material = atlasMat; ((Renderer)obj).enabled = false; } private Vector3[] GetBezierCurve(Vector3 p0, Vector3 p1, Vector3 p2, int segments) { //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) //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_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) Vector3[] array = (Vector3[])(object)new Vector3[segments + 1]; for (int i = 0; i <= segments; i++) { float num = (float)i / (float)segments; float num2 = 1f - num; array[i] = num2 * num2 * p0 + 2f * num2 * num * p1 + num * num * p2; } return array; } private void SetupBoneLine(LineRenderer lr, Vector3[] points, float startWidth, float endWidth) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) lr.positionCount = points.Length; lr.SetPositions(points); lr.startWidth = startWidth; lr.endWidth = endWidth; if (_currentTierColor != Color.clear) { lr.startColor = _currentTierColor; lr.endColor = new Color(_currentTierColor.r, _currentTierColor.g, _currentTierColor.b, 0.2f); } } private ParticleSystem CreateParticleSystem(GameObject go, Material mat) { //IL_0007: 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_0024: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: 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) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) ParticleSystem obj = go.AddComponent(); MainModule main = obj.main; ((MainModule)(ref main)).loop = true; ((MainModule)(ref main)).playOnAwake = true; ((MainModule)(ref main)).startSpeed = MinMaxCurve.op_Implicit(0f); ((MainModule)(ref main)).startLifetime = new MinMaxCurve(0.5f, 1.2f); ((MainModule)(ref main)).startSize = new MinMaxCurve(0.1f, 0.2f); ((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1; ((MainModule)(ref main)).scalingMode = (ParticleSystemScalingMode)1; EmissionModule emission = obj.emission; ((EmissionModule)(ref emission)).enabled = false; ShapeModule shape = obj.shape; ((ShapeModule)(ref shape)).enabled = true; ((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)12; ((ShapeModule)(ref shape)).radius = 3f; TextureSheetAnimationModule textureSheetAnimation = obj.textureSheetAnimation; ((TextureSheetAnimationModule)(ref textureSheetAnimation)).enabled = true; ((TextureSheetAnimationModule)(ref textureSheetAnimation)).numTilesX = 4; ((TextureSheetAnimationModule)(ref textureSheetAnimation)).numTilesY = 4; ((TextureSheetAnimationModule)(ref textureSheetAnimation)).animation = (ParticleSystemAnimationType)0; ((TextureSheetAnimationModule)(ref textureSheetAnimation)).startFrame = new MinMaxCurve(0f, 15f); ((TextureSheetAnimationModule)(ref textureSheetAnimation)).timeMode = (ParticleSystemAnimationTimeMode)0; ParticleSystemRenderer component = go.GetComponent(); component.renderMode = (ParticleSystemRenderMode)0; if ((Object)(object)mat != (Object)null) { ((Renderer)component).material = mat; } obj.Stop(true, (ParticleSystemStopBehavior)0); return obj; } public void SetTierColor(Color c) { //IL_0001: 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_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_003e: 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_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_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_005f: 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_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_019b: 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_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_028a: Unknown result type (might be due to invalid IL or missing references) //IL_0295: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_0364: Unknown result type (might be due to invalid IL or missing references) //IL_036a: Unknown result type (might be due to invalid IL or missing references) //IL_0370: Unknown result type (might be due to invalid IL or missing references) //IL_037b: 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_03a4: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: Unknown result type (might be due to invalid IL or missing references) //IL_03b0: Unknown result type (might be due to invalid IL or missing references) //IL_03bb: Unknown result type (might be due to invalid IL or missing references) //IL_0246: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Unknown result type (might be due to invalid IL or missing references) //IL_03e4: Unknown result type (might be due to invalid IL or missing references) //IL_03ea: Unknown result type (might be due to invalid IL or missing references) //IL_03f0: 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_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_0431: Unknown result type (might be due to invalid IL or missing references) //IL_0437: Unknown result type (might be due to invalid IL or missing references) //IL_043d: Unknown result type (might be due to invalid IL or missing references) //IL_0448: Unknown result type (might be due to invalid IL or missing references) //IL_0321: Unknown result type (might be due to invalid IL or missing references) //IL_0471: Unknown result type (might be due to invalid IL or missing references) //IL_0477: Unknown result type (might be due to invalid IL or missing references) //IL_047d: Unknown result type (might be due to invalid IL or missing references) //IL_0488: Unknown result type (might be due to invalid IL or missing references) //IL_04b1: Unknown result type (might be due to invalid IL or missing references) //IL_04b7: Unknown result type (might be due to invalid IL or missing references) //IL_04bd: Unknown result type (might be due to invalid IL or missing references) //IL_04c8: Unknown result type (might be due to invalid IL or missing references) if (_currentTierColor == c) { return; } _currentTierColor = c; if ((Object)(object)_leftWing == (Object)null || (Object)(object)_rightWing == (Object)null) { EnsureEmitters(); } MainModule main = _leftWing.main; ((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(c); MainModule main2 = _rightWing.main; ((MainModule)(ref main2)).startColor = MinMaxGradient.op_Implicit(c); ParticleSystemRenderer component = ((Component)_leftWing).GetComponent(); if ((Object)(object)component != (Object)null && (Object)(object)((Renderer)component).material != (Object)null) { if (((Renderer)component).material.HasProperty("_Color")) { ((Renderer)component).material.SetColor("_Color", c); } if (((Renderer)component).material.HasProperty("_TintColor")) { ((Renderer)component).material.SetColor("_TintColor", c); } if (((Renderer)component).material.HasProperty("_EmissionColor")) { ((Renderer)component).material.SetColor("_EmissionColor", c); } } ParticleSystemRenderer component2 = ((Component)_rightWing).GetComponent(); if ((Object)(object)component2 != (Object)null && (Object)(object)((Renderer)component2).material != (Object)null) { if (((Renderer)component2).material.HasProperty("_Color")) { ((Renderer)component2).material.SetColor("_Color", c); } if (((Renderer)component2).material.HasProperty("_TintColor")) { ((Renderer)component2).material.SetColor("_TintColor", c); } if (((Renderer)component2).material.HasProperty("_EmissionColor")) { ((Renderer)component2).material.SetColor("_EmissionColor", c); } } LineRenderer[] leftLines = _leftLines; foreach (LineRenderer val in leftLines) { val.startColor = c; val.endColor = new Color(c.r, c.g, c.b, 0.2f); if ((Object)(object)val != (Object)null && (Object)(object)((Renderer)val).material != (Object)null) { if (((Renderer)val).material.HasProperty("_Color")) { ((Renderer)val).material.SetColor("_Color", c); } if (((Renderer)val).material.HasProperty("_TintColor")) { ((Renderer)val).material.SetColor("_TintColor", c); } if (((Renderer)val).material.HasProperty("_EmissionColor")) { ((Renderer)val).material.SetColor("_EmissionColor", c); } } } leftLines = _rightLines; foreach (LineRenderer val2 in leftLines) { val2.startColor = c; val2.endColor = new Color(c.r, c.g, c.b, 0.2f); if ((Object)(object)val2 != (Object)null && (Object)(object)((Renderer)val2).material != (Object)null) { if (((Renderer)val2).material.HasProperty("_Color")) { ((Renderer)val2).material.SetColor("_Color", c); } if (((Renderer)val2).material.HasProperty("_TintColor")) { ((Renderer)val2).material.SetColor("_TintColor", c); } if (((Renderer)val2).material.HasProperty("_EmissionColor")) { ((Renderer)val2).material.SetColor("_EmissionColor", c); } } } MeshRenderer component3 = ((Component)_leftMeshFilter).GetComponent(); if (((Renderer)component3).material.HasProperty("_Color")) { ((Renderer)component3).material.SetColor("_Color", new Color(c.r, c.g, c.b, 0.15f)); } if (((Renderer)component3).material.HasProperty("_TintColor")) { ((Renderer)component3).material.SetColor("_TintColor", new Color(c.r, c.g, c.b, 0.15f)); } if (((Renderer)component3).material.HasProperty("_EmissionColor")) { ((Renderer)component3).material.SetColor("_EmissionColor", new Color(c.r, c.g, c.b, 0.05f)); } MeshRenderer component4 = ((Component)_rightMeshFilter).GetComponent(); if (((Renderer)component4).material.HasProperty("_Color")) { ((Renderer)component4).material.SetColor("_Color", new Color(c.r, c.g, c.b, 0.15f)); } if (((Renderer)component4).material.HasProperty("_TintColor")) { ((Renderer)component4).material.SetColor("_TintColor", new Color(c.r, c.g, c.b, 0.15f)); } if (((Renderer)component4).material.HasProperty("_EmissionColor")) { ((Renderer)component4).material.SetColor("_EmissionColor", new Color(c.r, c.g, c.b, 0.05f)); } } public void SetGlidingState(bool gliding) { if (_isGliding == gliding) { return; } _isGliding = gliding; if ((Object)(object)_leftWing == (Object)null || (Object)(object)_rightWing == (Object)null) { EnsureEmitters(); } if (_isGliding) { if (!_leftWing.isPlaying) { _leftWing.Play(); } if (!_rightWing.isPlaying) { _rightWing.Play(); } LineRenderer[] leftLines = _leftLines; for (int i = 0; i < leftLines.Length; i++) { ((Renderer)leftLines[i]).enabled = true; } leftLines = _rightLines; for (int i = 0; i < leftLines.Length; i++) { ((Renderer)leftLines[i]).enabled = true; } ((Renderer)((Component)_leftMeshFilter).GetComponent()).enabled = true; ((Renderer)((Component)_rightMeshFilter).GetComponent()).enabled = true; } else { _leftWing.Stop(true, (ParticleSystemStopBehavior)1); _rightWing.Stop(true, (ParticleSystemStopBehavior)1); LineRenderer[] leftLines = _leftLines; for (int i = 0; i < leftLines.Length; i++) { ((Renderer)leftLines[i]).enabled = false; } leftLines = _rightLines; for (int i = 0; i < leftLines.Length; i++) { ((Renderer)leftLines[i]).enabled = false; } ((Renderer)((Component)_leftMeshFilter).GetComponent()).enabled = false; ((Renderer)((Component)_rightMeshFilter).GetComponent()).enabled = false; } } public void TriggerFlap() { if ((Object)(object)_leftWing == (Object)null || (Object)(object)_rightWing == (Object)null) { EnsureEmitters(); } _flapTimer = 0.4f; if (!_isGliding) { _leftWing.Emit(15); _rightWing.Emit(15); } } private void Update() { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_021d: 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_023d: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Unknown result type (might be due to invalid IL or missing references) //IL_0275: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_leftRoot == (Object)null || (Object)(object)_rightRoot == (Object)null) { return; } float num = ModConfig.GlobalWingSpan?.Value ?? 1f; _leftRoot.localScale = new Vector3(num, num, num); _rightRoot.localScale = new Vector3(num, num, num); float num2 = 0f; if (_flapTimer > 0f) { _flapTimer -= Time.deltaTime; num2 = 1f - Mathf.Clamp01(_flapTimer / 0.4f); } if (_isGliding && (Object)(object)_leftWing != (Object)null && (Object)(object)_rightWing != (Object)null) { if (Vector3.Distance(_leftRoot.position, _lastEmitPosL) > 0.1f) { _leftWing.Emit(1); _lastEmitPosL = _leftRoot.position; } if (Vector3.Distance(_rightRoot.position, _lastEmitPosR) > 0.1f) { _rightWing.Emit(1); _lastEmitPosR = _rightRoot.position; } } float num3 = ((_isGliding && _flapTimer <= 0f) ? Time.time : 0f); UpdateWingMeshes(num2, num3); float num4 = 0f; if (num2 > 0f) { num4 = ((num2 < 0.2f) ? Mathf.Lerp(0f, 20f, num2 / 0.2f) : ((!(num2 < 0.5f)) ? Mathf.Lerp(-50f, 0f, (num2 - 0.5f) / 0.5f) : Mathf.Lerp(20f, -50f, (num2 - 0.2f) / 0.3f))); } else if (num3 > 0f) { num4 = Mathf.Sin(num3 * 4f) * 5f; } float num5 = ((num3 > 0f) ? (Mathf.Cos(num3 * 2f) * 2f) : 0f); _leftRoot.localRotation = Quaternion.Lerp(_leftRoot.localRotation, Quaternion.Euler(num5, -20f + num5, num4), Time.deltaTime * 15f); _rightRoot.localRotation = Quaternion.Lerp(_rightRoot.localRotation, Quaternion.Euler(0f - num5, 20f - num5, 0f - num4), Time.deltaTime * 15f); } private void UpdateWingMeshes(float flapProgress, float idleTime) { UpdateSingleWing(isRight: false, _leftLines, _leftMesh, flapProgress, idleTime); UpdateSingleWing(isRight: true, _rightLines, _rightMesh, flapProgress, idleTime); } private void UpdateSingleWing(bool isRight, LineRenderer[] lines, Mesh mesh, float flapProgress, float idleTime) { //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_019e: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_020b: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_023c: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0246: 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_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_0269: 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_0290: Unknown result type (might be due to invalid IL or missing references) //IL_0295: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_029c: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_02bd: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_02e4: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02ee: Unknown result type (might be due to invalid IL or missing references) //IL_0309: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Unknown result type (might be due to invalid IL or missing references) //IL_030c: Unknown result type (might be due to invalid IL or missing references) //IL_0318: Unknown result type (might be due to invalid IL or missing references) //IL_031a: Unknown result type (might be due to invalid IL or missing references) //IL_031c: Unknown result type (might be due to invalid IL or missing references) //IL_0328: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Unknown result type (might be due to invalid IL or missing references) //IL_032c: Unknown result type (might be due to invalid IL or missing references) //IL_0338: Unknown result type (might be due to invalid IL or missing references) //IL_033a: Unknown result type (might be due to invalid IL or missing references) //IL_033c: Unknown result type (might be due to invalid IL or missing references) //IL_0348: Unknown result type (might be due to invalid IL or missing references) //IL_034a: Unknown result type (might be due to invalid IL or missing references) //IL_034c: Unknown result type (might be due to invalid IL or missing references) //IL_0378: Unknown result type (might be due to invalid IL or missing references) //IL_037a: Unknown result type (might be due to invalid IL or missing references) //IL_0381: Unknown result type (might be due to invalid IL or missing references) //IL_0383: Unknown result type (might be due to invalid IL or missing references) //IL_038a: Unknown result type (might be due to invalid IL or missing references) //IL_038c: Unknown result type (might be due to invalid IL or missing references) //IL_0400: Unknown result type (might be due to invalid IL or missing references) //IL_0401: Unknown result type (might be due to invalid IL or missing references) //IL_0408: Unknown result type (might be due to invalid IL or missing references) //IL_040a: Unknown result type (might be due to invalid IL or missing references) //IL_042a: Unknown result type (might be due to invalid IL or missing references) //IL_042b: Unknown result type (might be due to invalid IL or missing references) //IL_0436: Unknown result type (might be due to invalid IL or missing references) //IL_043b: Unknown result type (might be due to invalid IL or missing references) //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_0445: Unknown result type (might be due to invalid IL or missing references) //IL_0450: Unknown result type (might be due to invalid IL or missing references) //IL_0455: Unknown result type (might be due to invalid IL or missing references) //IL_0460: Unknown result type (might be due to invalid IL or missing references) //IL_0465: Unknown result type (might be due to invalid IL or missing references) //IL_046d: Unknown result type (might be due to invalid IL or missing references) //IL_046f: Unknown result type (might be due to invalid IL or missing references) //IL_047a: Unknown result type (might be due to invalid IL or missing references) //IL_047f: Unknown result type (might be due to invalid IL or missing references) //IL_048a: Unknown result type (might be due to invalid IL or missing references) //IL_048f: Unknown result type (might be due to invalid IL or missing references) //IL_0497: Unknown result type (might be due to invalid IL or missing references) //IL_0499: Unknown result type (might be due to invalid IL or missing references) //IL_04a5: Unknown result type (might be due to invalid IL or missing references) //IL_04aa: Unknown result type (might be due to invalid IL or missing references) //IL_04b6: Unknown result type (might be due to invalid IL or missing references) //IL_04bb: Unknown result type (might be due to invalid IL or missing references) //IL_04c4: Unknown result type (might be due to invalid IL or missing references) //IL_04c6: Unknown result type (might be due to invalid IL or missing references) //IL_04d2: Unknown result type (might be due to invalid IL or missing references) //IL_04d7: Unknown result type (might be due to invalid IL or missing references) //IL_04e3: Unknown result type (might be due to invalid IL or missing references) //IL_04e8: Unknown result type (might be due to invalid IL or missing references) //IL_04f1: Unknown result type (might be due to invalid IL or missing references) //IL_04f3: Unknown result type (might be due to invalid IL or missing references) //IL_04fc: Unknown result type (might be due to invalid IL or missing references) //IL_04fe: Unknown result type (might be due to invalid IL or missing references) float num = (isRight ? 1f : (-1f)); float num2 = 0f; float num3 = 0f; if (flapProgress > 0f) { if (flapProgress < 0.2f) { float num4 = flapProgress / 0.2f; num2 = Mathf.Lerp(0f, -0.8f, num4); num3 = Mathf.Lerp(0f, -0.5f, num4); } else if (flapProgress < 0.5f) { float num5 = (flapProgress - 0.2f) / 0.3f; num2 = Mathf.Lerp(-0.8f, 0.2f, num5); num3 = Mathf.Lerp(-0.5f, 0.3f, num5); } else { float num6 = (flapProgress - 0.5f) / 0.5f; num2 = Mathf.Lerp(0.2f, 0f, num6); num3 = Mathf.Lerp(0.3f, 0f, num6); } } else if (idleTime > 0f) { num2 = Mathf.Sin(idleTime * 2f) * 0.1f; num3 = Mathf.Cos(idleTime * 4f) * 0.1f; } Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(0f, 0f, 0f); Vector3 p = default(Vector3); ((Vector3)(ref p))..ctor(0.8f * num, 0.2f, 0.4f); Vector3 val2 = default(Vector3); ((Vector3)(ref val2))..ctor((2.2f + num2 * 0.5f) * num, 0.5f + num3 * 0.5f, 0.2f + num2); Vector3 val3 = val2 + new Vector3(0.2f * num, 0.2f, 0.1f); Vector3 val4 = val2 + new Vector3(0.3f * num, 0.4f, 0.2f); Vector3 p2 = val2 + new Vector3(1.6f * num, -0.1f + num3, -0.4f + num2); Vector3 val5 = val2 + new Vector3((2.8f + num2) * num, -0.3f + num3 * 2f, -1.2f + num2 * 2f); Vector3 p3 = val2 + new Vector3(1.3f * num, -0.4f + num3, -0.8f + num2); Vector3 val6 = val2 + new Vector3((2.4f + num2) * num, -0.7f + num3 * 2f, -1.8f + num2 * 2f); Vector3 p4 = val2 + new Vector3(0.8f * num, -0.7f + num3, -1.2f + num2); Vector3 val7 = val2 + new Vector3((1.6f + num2) * num, -1f + num3 * 2f, -2.4f + num2 * 2f); Vector3 p5 = val2 + new Vector3(0.1f * num, -0.9f + num3, -1.4f + num2); Vector3 val8 = val2 + new Vector3((0.4f + num2) * num, -1.2f + num3 * 2f, -2.8f + num2 * 2f); Vector3 val9 = default(Vector3); ((Vector3)(ref val9))..ctor(0.2f * num, -0.5f, -0.5f); Vector3[] bezierCurve = GetBezierCurve(val, p, val2, 10); Vector3[] bezierCurve2 = GetBezierCurve(val2, p2, val5, 10); Vector3[] bezierCurve3 = GetBezierCurve(val2, p3, val6, 10); Vector3[] bezierCurve4 = GetBezierCurve(val2, p4, val7, 10); Vector3[] bezierCurve5 = GetBezierCurve(val2, p5, val8, 10); SetupBoneLine(lines[0], bezierCurve, 0.25f, 0.15f); SetupBoneLine(lines[1], (Vector3[])(object)new Vector3[3] { val2, val3, val4 }, 0.08f, 0.01f); SetupBoneLine(lines[2], bezierCurve2, 0.12f, 0.01f); SetupBoneLine(lines[3], bezierCurve3, 0.12f, 0.01f); SetupBoneLine(lines[4], bezierCurve4, 0.12f, 0.01f); SetupBoneLine(lines[5], bezierCurve5, 0.12f, 0.01f); SetupBoneLine(lines[6], (Vector3[])(object)new Vector3[2] { val, val9 }, 0.1f, 0.05f); mesh.vertices = (Vector3[])(object)new Vector3[23] { val, bezierCurve[5], val2, bezierCurve2[2], bezierCurve2[6], val5, bezierCurve3[2], bezierCurve3[6], val6, bezierCurve4[2], bezierCurve4[6], val7, bezierCurve5[2], bezierCurve5[6], val8, val9, default(Vector3), default(Vector3), default(Vector3), default(Vector3), default(Vector3), default(Vector3), default(Vector3) }; if (_whiteColors != null) { mesh.colors = _whiteColors; } mesh.RecalculateNormals(); mesh.RecalculateBounds(); } } public static class ValkyrieRuneTextureGenerator { private const int Size = 128; public unsafe static Texture2D GenerateRune(Color color) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) int runeIndex = Mathf.Abs(((object)(*(Color*)(&color))/*cast due to .constrained prefix*/).GetHashCode()) % 16; return GenerateRune(color, runeIndex); } public static Texture2D GenerateRuneAtlas(Color color) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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) int num = 128; Texture2D val = new Texture2D(512, 512, (TextureFormat)4, true); ((Texture)val).filterMode = (FilterMode)1; ((Texture)val).wrapMode = (TextureWrapMode)1; Color val2 = default(Color); ((Color)(ref val2))..ctor(0f, 0f, 0f, 0f); Color[] array = (Color[])(object)new Color[512 * 512]; for (int i = 0; i < array.Length; i++) { array[i] = val2; } val.SetPixels(array); for (int j = 0; j < 16; j++) { int num2 = j % 4; int num3 = 3 - j / 4; DrawRuneOntoAtlas(val, color, j, num2 * num, num3 * num, num); } val.Apply(true); return val; } public static Texture2D GenerateSoftTrail(Color color) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown //IL_0050: 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_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0097: 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_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) Texture2D val = new Texture2D(128, 128, (TextureFormat)4, false); ((Texture)val).filterMode = (FilterMode)1; Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor(64f, 64f); float num = 64f; Color val3 = default(Color); for (int i = 0; i < 128; i++) { for (int j = 0; j < 128; j++) { float num2 = Vector2.Distance(new Vector2((float)j + 0.5f, (float)i + 0.5f), val2) / num; float num3 = Mathf.Clamp01(1f - num2); num3 = Mathf.SmoothStep(0f, 1f, num3); num3 = Mathf.Pow(num3, 1.6f); ((Color)(ref val3))..ctor(color.r, color.g, color.b, color.a * num3); val.SetPixel(j, i, val3); } } val.Apply(true); return val; } public static Texture2D GenerateStreak(Color color) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown //IL_0047: 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_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: 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) Texture2D val = new Texture2D(128, 128, (TextureFormat)4, false); ((Texture)val).filterMode = (FilterMode)1; Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor(64f, 64f); float num = 64f; Color val3 = default(Color); for (int i = 0; i < 128; i++) { for (int j = 0; j < 128; j++) { float num2 = Mathf.Abs((float)i + 0.5f - val2.y) / num; float num3 = Mathf.Abs((float)j + 0.5f - val2.x) / (num * 0.6f); float num4 = Mathf.Clamp01(1f - num3); float num5 = Mathf.SmoothStep(1f, 0f, num2); num4 *= Mathf.Pow(num5, 0.9f); ((Color)(ref val3))..ctor(color.r, color.g, color.b, color.a * num4); val.SetPixel(j, i, val3); } } val.Apply(true); return val; } public static Texture2D GenerateBlend(Color color) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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_0049: 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_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) Texture2D val = GenerateSoftTrail(color); Texture2D val2 = GenerateRune(color); Texture2D val3 = new Texture2D(128, 128, (TextureFormat)4, false); ((Texture)val3).filterMode = (FilterMode)1; Color val4 = default(Color); for (int i = 0; i < 128; i++) { for (int j = 0; j < 128; j++) { Color pixel = val.GetPixel(j, i); Color pixel2 = val2.GetPixel(j, i); float num = Mathf.Clamp01(pixel.a + pixel2.a * 0.65f); ((Color)(ref val4))..ctor(color.r, color.g, color.b, color.a * num); val3.SetPixel(j, i, val4); } } val3.Apply(true); return val3; } private static void DrawRuneOntoAtlas(Texture2D tex, Color color, int runeIndex, int offsetX, int offsetY, int size) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: 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_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0160: 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_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_020c: Unknown result type (might be due to invalid IL or missing references) //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0262: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0285: 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_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_02c9: 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) //IL_02ec: Unknown result type (might be due to invalid IL or missing references) //IL_02fd: Unknown result type (might be due to invalid IL or missing references) //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_031f: Unknown result type (might be due to invalid IL or missing references) //IL_0330: Unknown result type (might be due to invalid IL or missing references) //IL_0341: Unknown result type (might be due to invalid IL or missing references) //IL_0353: Unknown result type (might be due to invalid IL or missing references) //IL_0364: Unknown result type (might be due to invalid IL or missing references) //IL_0375: Unknown result type (might be due to invalid IL or missing references) //IL_0386: Unknown result type (might be due to invalid IL or missing references) //IL_0397: 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_03b9: Unknown result type (might be due to invalid IL or missing references) //IL_03ca: Unknown result type (might be due to invalid IL or missing references) //IL_03dc: Unknown result type (might be due to invalid IL or missing references) //IL_03ed: Unknown result type (might be due to invalid IL or missing references) //IL_03fe: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_0421: Unknown result type (might be due to invalid IL or missing references) //IL_0432: Unknown result type (might be due to invalid IL or missing references) //IL_0443: 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_0465: Unknown result type (might be due to invalid IL or missing references) //IL_0476: Unknown result type (might be due to invalid IL or missing references) //IL_0487: Unknown result type (might be due to invalid IL or missing references) //IL_0498: Unknown result type (might be due to invalid IL or missing references) //IL_04aa: Unknown result type (might be due to invalid IL or missing references) //IL_04bb: Unknown result type (might be due to invalid IL or missing references) //IL_04cc: Unknown result type (might be due to invalid IL or missing references) //IL_04dd: Unknown result type (might be due to invalid IL or missing references) //IL_04ef: Unknown result type (might be due to invalid IL or missing references) //IL_0500: Unknown result type (might be due to invalid IL or missing references) //IL_0511: Unknown result type (might be due to invalid IL or missing references) //IL_0522: Unknown result type (might be due to invalid IL or missing references) //IL_0533: Unknown result type (might be due to invalid IL or missing references) //IL_0544: Unknown result type (might be due to invalid IL or missing references) //IL_0555: Unknown result type (might be due to invalid IL or missing references) //IL_0566: Unknown result type (might be due to invalid IL or missing references) //IL_0577: Unknown result type (might be due to invalid IL or missing references) //IL_0588: Unknown result type (might be due to invalid IL or missing references) //IL_0599: Unknown result type (might be due to invalid IL or missing references) //IL_05aa: Unknown result type (might be due to invalid IL or missing references) //IL_05bc: Unknown result type (might be due to invalid IL or missing references) //IL_05cd: Unknown result type (might be due to invalid IL or missing references) //IL_05de: Unknown result type (might be due to invalid IL or missing references) //IL_05ef: Unknown result type (might be due to invalid IL or missing references) //IL_0600: Unknown result type (might be due to invalid IL or missing references) //IL_0611: Unknown result type (might be due to invalid IL or missing references) //IL_0622: Unknown result type (might be due to invalid IL or missing references) //IL_0633: Unknown result type (might be due to invalid IL or missing references) //IL_0645: Unknown result type (might be due to invalid IL or missing references) //IL_0656: Unknown result type (might be due to invalid IL or missing references) //IL_0667: Unknown result type (might be due to invalid IL or missing references) //IL_0678: Unknown result type (might be due to invalid IL or missing references) //IL_0689: Unknown result type (might be due to invalid IL or missing references) //IL_069a: Unknown result type (might be due to invalid IL or missing references) //IL_06ab: Unknown result type (might be due to invalid IL or missing references) //IL_06bc: Unknown result type (might be due to invalid IL or missing references) //IL_06cd: Unknown result type (might be due to invalid IL or missing references) //IL_06de: Unknown result type (might be due to invalid IL or missing references) //IL_06f0: Unknown result type (might be due to invalid IL or missing references) //IL_0701: Unknown result type (might be due to invalid IL or missing references) //IL_0712: Unknown result type (might be due to invalid IL or missing references) //IL_0723: Unknown result type (might be due to invalid IL or missing references) //IL_0734: Unknown result type (might be due to invalid IL or missing references) //IL_0745: Unknown result type (might be due to invalid IL or missing references) //IL_0756: Unknown result type (might be due to invalid IL or missing references) //IL_0767: Unknown result type (might be due to invalid IL or missing references) //IL_0779: Unknown result type (might be due to invalid IL or missing references) //IL_078a: Unknown result type (might be due to invalid IL or missing references) //IL_079b: Unknown result type (might be due to invalid IL or missing references) //IL_07ac: Unknown result type (might be due to invalid IL or missing references) //IL_07bd: Unknown result type (might be due to invalid IL or missing references) //IL_07ce: Unknown result type (might be due to invalid IL or missing references) //IL_07df: Unknown result type (might be due to invalid IL or missing references) //IL_07f0: Unknown result type (might be due to invalid IL or missing references) Color c = default(Color); ((Color)(ref c))..ctor(color.r * 0.6f, color.g * 0.6f, color.b * 0.6f, 0.6f); Color c2 = default(Color); ((Color)(ref c2))..ctor(color.r, color.g, color.b, 1f); float scale = (float)size / 128f; switch (runeIndex) { case 0: DrawLineLocal(20, 20, 108, 108, c, 6); DrawLineLocal(108, 20, 20, 108, c, 6); DrawLineLocal(20, 20, 108, 108, c2, 3); DrawLineLocal(108, 20, 20, 108, c2, 3); break; case 1: DrawLineLocal(64, 16, 64, 112, c, 6); DrawLineLocal(64, 64, 32, 96, c, 5); DrawLineLocal(64, 64, 96, 96, c, 5); DrawLineLocal(64, 16, 64, 112, c2, 3); DrawLineLocal(64, 64, 32, 96, c2, 2); DrawLineLocal(64, 64, 96, 96, c2, 2); break; case 2: DrawLineLocal(40, 20, 40, 108, c, 6); DrawLineLocal(40, 96, 96, 112, c, 5); DrawLineLocal(40, 72, 96, 88, c, 5); DrawLineLocal(40, 20, 40, 108, c2, 3); DrawLineLocal(40, 96, 96, 112, c2, 2); DrawLineLocal(40, 72, 96, 88, c2, 2); break; case 3: DrawLineLocal(40, 20, 40, 112, c, 6); DrawLineLocal(40, 96, 88, 112, c, 5); DrawLineLocal(88, 112, 88, 80, c, 5); DrawLineLocal(88, 80, 40, 96, c, 5); DrawLineLocal(40, 20, 40, 112, c2, 3); DrawLineLocal(40, 96, 88, 112, c2, 2); DrawLineLocal(88, 112, 88, 80, c2, 2); DrawLineLocal(88, 80, 40, 96, c2, 2); break; case 4: DrawLineLocal(64, 16, 64, 112, c, 8); DrawLineLocal(64, 16, 64, 112, c2, 4); break; case 5: DrawLineLocal(64, 16, 64, 112, c, 6); DrawLineLocal(64, 40, 32, 72, c, 5); DrawLineLocal(64, 40, 96, 72, c, 5); DrawLineLocal(64, 16, 64, 112, c2, 3); DrawLineLocal(64, 40, 32, 72, c2, 2); DrawLineLocal(64, 40, 96, 72, c2, 2); break; case 6: DrawLineLocal(36, 16, 36, 112, c, 6); DrawLineLocal(92, 16, 92, 112, c, 6); DrawLineLocal(36, 36, 92, 92, c, 5); DrawLineLocal(36, 16, 36, 112, c2, 3); DrawLineLocal(92, 16, 92, 112, c2, 3); DrawLineLocal(36, 36, 92, 92, c2, 2); break; case 7: DrawLineLocal(80, 20, 40, 20, c, 5); DrawLineLocal(80, 20, 40, 64, c, 5); DrawLineLocal(40, 64, 80, 108, c, 5); DrawLineLocal(80, 108, 40, 108, c, 5); DrawLineLocal(80, 20, 40, 20, c2, 2); DrawLineLocal(80, 20, 40, 64, c2, 2); DrawLineLocal(40, 64, 80, 108, c2, 2); DrawLineLocal(80, 108, 40, 108, c2, 2); break; case 8: DrawLineLocal(64, 16, 64, 112, c, 6); DrawLineLocal(96, 96, 32, 32, c, 5); DrawLineLocal(64, 16, 64, 112, c2, 3); DrawLineLocal(96, 96, 32, 32, c2, 2); break; case 9: DrawLineLocal(32, 48, 32, 112, c, 6); DrawLineLocal(96, 48, 96, 112, c, 6); DrawLineLocal(32, 48, 64, 16, c, 5); DrawLineLocal(64, 16, 96, 48, c, 5); DrawLineLocal(32, 48, 32, 112, c2, 3); DrawLineLocal(96, 48, 96, 112, c2, 3); DrawLineLocal(32, 48, 64, 16, c2, 2); DrawLineLocal(64, 16, 96, 48, c2, 2); break; case 10: DrawLineLocal(48, 16, 48, 112, c, 6); DrawLineLocal(48, 80, 96, 48, c, 5); DrawLineLocal(48, 16, 48, 112, c2, 3); DrawLineLocal(48, 80, 96, 48, c2, 2); break; case 11: DrawLineLocal(64, 112, 96, 72, c, 5); DrawLineLocal(96, 72, 64, 32, c, 5); DrawLineLocal(64, 32, 32, 72, c, 5); DrawLineLocal(32, 72, 64, 112, c, 5); DrawLineLocal(32, 72, 16, 16, c, 5); DrawLineLocal(96, 72, 112, 16, c, 5); DrawLineLocal(64, 112, 96, 72, c2, 2); DrawLineLocal(96, 72, 64, 32, c2, 2); DrawLineLocal(64, 32, 32, 72, c2, 2); DrawLineLocal(32, 72, 64, 112, c2, 2); DrawLineLocal(32, 72, 16, 16, c2, 2); DrawLineLocal(96, 72, 112, 16, c2, 2); break; case 12: DrawLineLocal(20, 20, 64, 64, c, 5); DrawLineLocal(20, 108, 64, 64, c, 5); DrawLineLocal(108, 20, 64, 64, c, 5); DrawLineLocal(108, 108, 64, 64, c, 5); DrawLineLocal(20, 20, 64, 64, c2, 2); DrawLineLocal(20, 108, 64, 64, c2, 2); DrawLineLocal(108, 20, 64, 64, c2, 2); DrawLineLocal(108, 108, 64, 64, c2, 2); break; case 13: DrawLineLocal(36, 16, 36, 112, c, 6); DrawLineLocal(36, 96, 80, 80, c, 5); DrawLineLocal(80, 80, 36, 64, c, 5); DrawLineLocal(36, 64, 80, 48, c, 5); DrawLineLocal(80, 48, 36, 32, c, 5); DrawLineLocal(36, 16, 36, 112, c2, 3); DrawLineLocal(36, 96, 80, 80, c2, 2); DrawLineLocal(80, 80, 36, 64, c2, 2); DrawLineLocal(36, 64, 80, 48, c2, 2); DrawLineLocal(80, 48, 36, 32, c2, 2); break; case 14: DrawLineLocal(32, 16, 32, 112, c, 6); DrawLineLocal(96, 16, 96, 112, c, 6); DrawLineLocal(32, 112, 96, 64, c, 5); DrawLineLocal(96, 112, 32, 64, c, 5); DrawLineLocal(32, 16, 32, 112, c2, 3); DrawLineLocal(96, 16, 96, 112, c2, 3); DrawLineLocal(32, 112, 96, 64, c2, 2); DrawLineLocal(96, 112, 32, 64, c2, 2); break; case 15: DrawLineLocal(64, 16, 108, 64, c, 6); DrawLineLocal(108, 64, 64, 112, c, 6); DrawLineLocal(64, 112, 20, 64, c, 6); DrawLineLocal(20, 64, 64, 16, c, 6); DrawLineLocal(64, 16, 108, 64, c2, 3); DrawLineLocal(108, 64, 64, 112, c2, 3); DrawLineLocal(64, 112, 20, 64, c2, 3); DrawLineLocal(20, 64, 64, 16, c2, 3); break; } void DrawLineLocal(int x0, int y0, int x1, int y1, Color c3, int thickness) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) DrawLineAtlas(tex, offsetX + (int)((float)x0 * scale), offsetY + (int)((float)y0 * scale), offsetX + (int)((float)x1 * scale), offsetY + (int)((float)y1 * scale), c3, thickness, 512); } } public static Texture2D GenerateRune(Color color, int runeIndex) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_010e: 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_012e: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0193: 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_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_021d: 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_023d: 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_025d: Unknown result type (might be due to invalid IL or missing references) //IL_026d: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_02a2: Unknown result type (might be due to invalid IL or missing references) //IL_02b2: Unknown result type (might be due to invalid IL or missing references) //IL_02c7: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Unknown result type (might be due to invalid IL or missing references) //IL_02e7: Unknown result type (might be due to invalid IL or missing references) //IL_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_0307: 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_032c: Unknown result type (might be due to invalid IL or missing references) //IL_033c: Unknown result type (might be due to invalid IL or missing references) //IL_034c: Unknown result type (might be due to invalid IL or missing references) //IL_035c: Unknown result type (might be due to invalid IL or missing references) //IL_036c: Unknown result type (might be due to invalid IL or missing references) //IL_037c: Unknown result type (might be due to invalid IL or missing references) //IL_0391: Unknown result type (might be due to invalid IL or missing references) //IL_03a1: Unknown result type (might be due to invalid IL or missing references) //IL_03b1: Unknown result type (might be due to invalid IL or missing references) //IL_03c1: Unknown result type (might be due to invalid IL or missing references) //IL_03d1: Unknown result type (might be due to invalid IL or missing references) //IL_03e1: Unknown result type (might be due to invalid IL or missing references) //IL_03f1: Unknown result type (might be due to invalid IL or missing references) //IL_0401: 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_0426: Unknown result type (might be due to invalid IL or missing references) //IL_0436: Unknown result type (might be due to invalid IL or missing references) //IL_0446: Unknown result type (might be due to invalid IL or missing references) //IL_045b: Unknown result type (might be due to invalid IL or missing references) //IL_046b: Unknown result type (might be due to invalid IL or missing references) //IL_047b: Unknown result type (might be due to invalid IL or missing references) //IL_048b: Unknown result type (might be due to invalid IL or missing references) //IL_049b: Unknown result type (might be due to invalid IL or missing references) //IL_04ab: Unknown result type (might be due to invalid IL or missing references) //IL_04bb: Unknown result type (might be due to invalid IL or missing references) //IL_04cb: Unknown result type (might be due to invalid IL or missing references) //IL_04e0: Unknown result type (might be due to invalid IL or missing references) //IL_04f0: Unknown result type (might be due to invalid IL or missing references) //IL_0500: Unknown result type (might be due to invalid IL or missing references) //IL_0510: Unknown result type (might be due to invalid IL or missing references) //IL_0525: Unknown result type (might be due to invalid IL or missing references) //IL_0535: Unknown result type (might be due to invalid IL or missing references) //IL_0545: Unknown result type (might be due to invalid IL or missing references) //IL_0555: Unknown result type (might be due to invalid IL or missing references) //IL_0565: Unknown result type (might be due to invalid IL or missing references) //IL_0575: Unknown result type (might be due to invalid IL or missing references) //IL_0585: Unknown result type (might be due to invalid IL or missing references) //IL_0595: Unknown result type (might be due to invalid IL or missing references) //IL_05a5: Unknown result type (might be due to invalid IL or missing references) //IL_05b5: Unknown result type (might be due to invalid IL or missing references) //IL_05c5: Unknown result type (might be due to invalid IL or missing references) //IL_05d5: Unknown result type (might be due to invalid IL or missing references) //IL_05ea: Unknown result type (might be due to invalid IL or missing references) //IL_05fa: Unknown result type (might be due to invalid IL or missing references) //IL_060a: Unknown result type (might be due to invalid IL or missing references) //IL_061a: Unknown result type (might be due to invalid IL or missing references) //IL_062a: Unknown result type (might be due to invalid IL or missing references) //IL_063a: Unknown result type (might be due to invalid IL or missing references) //IL_064a: Unknown result type (might be due to invalid IL or missing references) //IL_065a: Unknown result type (might be due to invalid IL or missing references) //IL_066f: Unknown result type (might be due to invalid IL or missing references) //IL_067f: Unknown result type (might be due to invalid IL or missing references) //IL_068f: Unknown result type (might be due to invalid IL or missing references) //IL_069f: Unknown result type (might be due to invalid IL or missing references) //IL_06af: Unknown result type (might be due to invalid IL or missing references) //IL_06bf: Unknown result type (might be due to invalid IL or missing references) //IL_06cf: Unknown result type (might be due to invalid IL or missing references) //IL_06df: Unknown result type (might be due to invalid IL or missing references) //IL_06ef: Unknown result type (might be due to invalid IL or missing references) //IL_06ff: Unknown result type (might be due to invalid IL or missing references) //IL_0714: Unknown result type (might be due to invalid IL or missing references) //IL_0724: Unknown result type (might be due to invalid IL or missing references) //IL_0734: Unknown result type (might be due to invalid IL or missing references) //IL_0744: Unknown result type (might be due to invalid IL or missing references) //IL_0754: Unknown result type (might be due to invalid IL or missing references) //IL_0764: Unknown result type (might be due to invalid IL or missing references) //IL_0774: Unknown result type (might be due to invalid IL or missing references) //IL_0784: Unknown result type (might be due to invalid IL or missing references) //IL_0799: Unknown result type (might be due to invalid IL or missing references) //IL_07a9: Unknown result type (might be due to invalid IL or missing references) //IL_07b9: Unknown result type (might be due to invalid IL or missing references) //IL_07c9: Unknown result type (might be due to invalid IL or missing references) //IL_07d9: Unknown result type (might be due to invalid IL or missing references) //IL_07e9: Unknown result type (might be due to invalid IL or missing references) //IL_07f9: Unknown result type (might be due to invalid IL or missing references) //IL_0809: Unknown result type (might be due to invalid IL or missing references) Texture2D val = new Texture2D(128, 128, (TextureFormat)4, true); ((Texture)val).filterMode = (FilterMode)1; ((Texture)val).wrapMode = (TextureWrapMode)1; Color val2 = default(Color); ((Color)(ref val2))..ctor(0f, 0f, 0f, 0f); Color c = default(Color); ((Color)(ref c))..ctor(color.r * 0.6f, color.g * 0.6f, color.b * 0.6f, 0.6f); Color c2 = default(Color); ((Color)(ref c2))..ctor(color.r, color.g, color.b, 1f); Color[] array = (Color[])(object)new Color[16384]; for (int i = 0; i < array.Length; i++) { array[i] = val2; } val.SetPixels(array); switch (runeIndex) { case 0: DrawLine(val, 20, 20, 108, 108, c, 6); DrawLine(val, 108, 20, 20, 108, c, 6); DrawLine(val, 20, 20, 108, 108, c2, 3); DrawLine(val, 108, 20, 20, 108, c2, 3); break; case 1: DrawLine(val, 64, 16, 64, 112, c, 6); DrawLine(val, 64, 64, 32, 96, c, 5); DrawLine(val, 64, 64, 96, 96, c, 5); DrawLine(val, 64, 16, 64, 112, c2, 3); DrawLine(val, 64, 64, 32, 96, c2, 2); DrawLine(val, 64, 64, 96, 96, c2, 2); break; case 2: DrawLine(val, 40, 20, 40, 108, c, 6); DrawLine(val, 40, 96, 96, 112, c, 5); DrawLine(val, 40, 72, 96, 88, c, 5); DrawLine(val, 40, 20, 40, 108, c2, 3); DrawLine(val, 40, 96, 96, 112, c2, 2); DrawLine(val, 40, 72, 96, 88, c2, 2); break; case 3: DrawLine(val, 40, 20, 40, 112, c, 6); DrawLine(val, 40, 96, 88, 112, c, 5); DrawLine(val, 88, 112, 88, 80, c, 5); DrawLine(val, 88, 80, 40, 96, c, 5); DrawLine(val, 40, 20, 40, 112, c2, 3); DrawLine(val, 40, 96, 88, 112, c2, 2); DrawLine(val, 88, 112, 88, 80, c2, 2); DrawLine(val, 88, 80, 40, 96, c2, 2); break; case 4: DrawLine(val, 64, 16, 64, 112, c, 8); DrawLine(val, 64, 16, 64, 112, c2, 4); break; case 5: DrawLine(val, 64, 16, 64, 112, c, 6); DrawLine(val, 64, 40, 32, 72, c, 5); DrawLine(val, 64, 40, 96, 72, c, 5); DrawLine(val, 64, 16, 64, 112, c2, 3); DrawLine(val, 64, 40, 32, 72, c2, 2); DrawLine(val, 64, 40, 96, 72, c2, 2); break; case 6: DrawLine(val, 36, 16, 36, 112, c, 6); DrawLine(val, 92, 16, 92, 112, c, 6); DrawLine(val, 36, 36, 92, 92, c, 5); DrawLine(val, 36, 16, 36, 112, c2, 3); DrawLine(val, 92, 16, 92, 112, c2, 3); DrawLine(val, 36, 36, 92, 92, c2, 2); break; default: DrawLine(val, 80, 20, 40, 20, c, 5); DrawLine(val, 80, 20, 40, 64, c, 5); DrawLine(val, 40, 64, 80, 108, c, 5); DrawLine(val, 80, 108, 40, 108, c, 5); DrawLine(val, 80, 20, 40, 20, c2, 2); DrawLine(val, 80, 20, 40, 64, c2, 2); DrawLine(val, 40, 64, 80, 108, c2, 2); DrawLine(val, 80, 108, 40, 108, c2, 2); break; case 8: DrawLine(val, 64, 16, 64, 112, c, 6); DrawLine(val, 96, 96, 32, 32, c, 5); DrawLine(val, 64, 16, 64, 112, c2, 3); DrawLine(val, 96, 96, 32, 32, c2, 2); break; case 9: DrawLine(val, 32, 48, 32, 112, c, 6); DrawLine(val, 96, 48, 96, 112, c, 6); DrawLine(val, 32, 48, 64, 16, c, 5); DrawLine(val, 64, 16, 96, 48, c, 5); DrawLine(val, 32, 48, 32, 112, c2, 3); DrawLine(val, 96, 48, 96, 112, c2, 3); DrawLine(val, 32, 48, 64, 16, c2, 2); DrawLine(val, 64, 16, 96, 48, c2, 2); break; case 10: DrawLine(val, 48, 16, 48, 112, c, 6); DrawLine(val, 48, 80, 96, 48, c, 5); DrawLine(val, 48, 16, 48, 112, c2, 3); DrawLine(val, 48, 80, 96, 48, c2, 2); break; case 11: DrawLine(val, 64, 112, 96, 72, c, 5); DrawLine(val, 96, 72, 64, 32, c, 5); DrawLine(val, 64, 32, 32, 72, c, 5); DrawLine(val, 32, 72, 64, 112, c, 5); DrawLine(val, 32, 72, 16, 16, c, 5); DrawLine(val, 96, 72, 112, 16, c, 5); DrawLine(val, 64, 112, 96, 72, c2, 2); DrawLine(val, 96, 72, 64, 32, c2, 2); DrawLine(val, 64, 32, 32, 72, c2, 2); DrawLine(val, 32, 72, 64, 112, c2, 2); DrawLine(val, 32, 72, 16, 16, c2, 2); DrawLine(val, 96, 72, 112, 16, c2, 2); break; case 12: DrawLine(val, 20, 20, 64, 64, c, 5); DrawLine(val, 20, 108, 64, 64, c, 5); DrawLine(val, 108, 20, 64, 64, c, 5); DrawLine(val, 108, 108, 64, 64, c, 5); DrawLine(val, 20, 20, 64, 64, c2, 2); DrawLine(val, 20, 108, 64, 64, c2, 2); DrawLine(val, 108, 20, 64, 64, c2, 2); DrawLine(val, 108, 108, 64, 64, c2, 2); break; case 13: DrawLine(val, 36, 16, 36, 112, c, 6); DrawLine(val, 36, 96, 80, 80, c, 5); DrawLine(val, 80, 80, 36, 64, c, 5); DrawLine(val, 36, 64, 80, 48, c, 5); DrawLine(val, 80, 48, 36, 32, c, 5); DrawLine(val, 36, 16, 36, 112, c2, 3); DrawLine(val, 36, 96, 80, 80, c2, 2); DrawLine(val, 80, 80, 36, 64, c2, 2); DrawLine(val, 36, 64, 80, 48, c2, 2); DrawLine(val, 80, 48, 36, 32, c2, 2); break; case 14: DrawLine(val, 32, 16, 32, 112, c, 6); DrawLine(val, 96, 16, 96, 112, c, 6); DrawLine(val, 32, 112, 96, 64, c, 5); DrawLine(val, 96, 112, 32, 64, c, 5); DrawLine(val, 32, 16, 32, 112, c2, 3); DrawLine(val, 96, 16, 96, 112, c2, 3); DrawLine(val, 32, 112, 96, 64, c2, 2); DrawLine(val, 96, 112, 32, 64, c2, 2); break; case 15: DrawLine(val, 64, 16, 108, 64, c, 6); DrawLine(val, 108, 64, 64, 112, c, 6); DrawLine(val, 64, 112, 20, 64, c, 6); DrawLine(val, 20, 64, 64, 16, c, 6); DrawLine(val, 64, 16, 108, 64, c2, 3); DrawLine(val, 108, 64, 64, 112, c2, 3); DrawLine(val, 64, 112, 20, 64, c2, 3); DrawLine(val, 20, 64, 64, 16, c2, 3); break; } val.Apply(true); return val; } private static void DrawLineAtlas(Texture2D tex, int x0, int y0, int x1, int y1, Color c, int thickness, int atlasSize) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) int num = Mathf.Abs(x1 - x0); int num2 = Mathf.Abs(y1 - y0); int num3 = ((x0 < x1) ? 1 : (-1)); int num4 = ((y0 < y1) ? 1 : (-1)); int num5 = num - num2; while (true) { DrawCircleAtlas(tex, x0, y0, thickness, c, atlasSize); if (x0 != x1 || y0 != y1) { int num6 = 2 * num5; if (num6 > -num2) { num5 -= num2; x0 += num3; } if (num6 < num) { num5 += num; y0 += num4; } continue; } break; } } private static void DrawCircleAtlas(Texture2D tex, int cx, int cy, int r, Color c, int atlasSize) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) for (int i = -r; i <= r; i++) { for (int j = -r; j <= r; j++) { if (j * j + i * i <= r * r) { int num = cx + j; int num2 = cy + i; if (num >= 0 && num < atlasSize && num2 >= 0 && num2 < atlasSize) { tex.SetPixel(num, num2, c); } } } } } private static void DrawLine(Texture2D tex, int x0, int y0, int x1, int y1, Color c, int thickness) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) int num = Mathf.Abs(x1 - x0); int num2 = Mathf.Abs(y1 - y0); int num3 = ((x0 < x1) ? 1 : (-1)); int num4 = ((y0 < y1) ? 1 : (-1)); int num5 = num - num2; while (true) { DrawCircle(tex, x0, y0, thickness, c); if (x0 != x1 || y0 != y1) { int num6 = 2 * num5; if (num6 > -num2) { num5 -= num2; x0 += num3; } if (num6 < num) { num5 += num; y0 += num4; } continue; } break; } } private static void DrawCircle(Texture2D tex, int cx, int cy, int r, Color c) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) for (int i = -r; i <= r; i++) { for (int j = -r; j <= r; j++) { if (j * j + i * i <= r * r) { int num = cx + j; int num2 = cy + i; if (num >= 0 && num < 128 && num2 >= 0 && num2 < 128) { tex.SetPixel(num, num2, c); } } } } } } public static class ValkyrieRuneVFX_Helper { private static readonly Dictionary _materialCache = new Dictionary(); private static bool _initialized = false; private static void Init() { if (!_initialized) { _initialized = true; Log.LogInfo("\ud83d\udf01 VFX‑Forge: Seeking glowing, additive, unlit shaders worthy of Njord."); } } private unsafe static long MakeCacheKey(Shader shader, Texture2D tex, Color color) { int num = (((Object)(object)shader != (Object)null) ? ((Object)shader).GetInstanceID() : 0); int num2 = (((Object)(object)tex != (Object)null) ? ((Object)tex).GetInstanceID() : 0); int hashCode = ((object)(*(Color*)(&color))/*cast due to .constrained prefix*/).GetHashCode(); return (long)((ulong)((long)num << 32) ^ ((ulong)(uint)num2 << 16) ^ (uint)hashCode); } public static Material GetOrCreateRuneMaterial(Texture2D runeTex, Color color) { //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_014a: 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_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Expected O, but got Unknown //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) Init(); Shader val = Shader.Find("Particles/Standard Unlit") ?? Shader.Find("Legacy Shaders/Particles/Alpha Blended") ?? Shader.Find("Particles/Alpha Blended") ?? Shader.Find("Particles/Additive"); if ((Object)(object)val == (Object)null) { float num = float.MinValue; Material[] array = Resources.FindObjectsOfTypeAll(); foreach (Material val2 in array) { if (!((Object)(object)val2 == (Object)null) && !((Object)(object)val2.shader == (Object)null)) { Shader shader = val2.shader; string text = ((Object)shader).name.ToLower(); float num2 = 0f; if (text.Contains("particle")) { num2 += 3f; } if (text.Contains("add")) { num2 += 3f; } if (text.Contains("unlit")) { num2 += 2f; } if (text.Contains("transparent")) { num2 += 1.5f; } if ((val2.HasProperty("_Color") || val2.HasProperty("_TintColor")) && num2 > num) { num = num2; val = shader; } } } } if ((Object)(object)val == (Object)null) { Log.LogError("\ud83d\udf01 VFX‑Forge: No glowing shader found. The runes refuse to shine."); return null; } long key = MakeCacheKey(val, runeTex, color); if (_materialCache.TryGetValue(key, out var value) && (Object)(object)value != (Object)null) { return value; } Material val3 = new Material(val); if ((Object)(object)runeTex != (Object)null) { if (val3.HasProperty("_MainTex")) { val3.SetTexture("_MainTex", (Texture)(object)runeTex); } if (val3.HasProperty("_BaseMap")) { val3.SetTexture("_BaseMap", (Texture)(object)runeTex); } try { val3.mainTexture = (Texture)(object)runeTex; } catch { } } if (val3.HasProperty("_Color")) { val3.SetColor("_Color", color); } if (val3.HasProperty("_TintColor")) { val3.SetColor("_TintColor", color); } if (val3.HasProperty("_EmissionColor")) { val3.SetColor("_EmissionColor", color * 3f); } val3.SetInt("_SrcBlend", 1); val3.SetInt("_DstBlend", 1); val3.SetInt("_ZWrite", 0); val3.DisableKeyword("_ALPHATEST_ON"); val3.EnableKeyword("_ALPHABLEND_ON"); val3.DisableKeyword("_ALPHAPREMULTIPLY_ON"); val3.renderQueue = 3000; _materialCache[key] = val3; Log.LogInfo("\ud83d\udf01 VFX‑Forge: Forged glowing additive rune material from '" + ((Object)val).name + "'."); return val3; } public static void ClearCache() { _materialCache.Clear(); _initialized = false; } } }