Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of HBK Addon v1.0.0
plugins/Discord_Screenshots/discordScreenshots.dll
Decompiled 5 hours agousing System; using System.Collections; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Jotunn.Extensions; using Jotunn.Utils; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using UnityEngine; using discordScreenshots.Patches; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("discordScreenshots")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("discordScreenshots")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("CA695DDD-2CE8-407B-B7A2-9FB6D3783286")] [assembly: AssemblyFileVersion("1.6.8")] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.6.8.0")] [module: UnverifiableCode] 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; } } } [HarmonyPatch(typeof(Player), "OnDamaged")] public static class RemoveDamageFlashOnDeath { [HarmonyPostfix] private static bool Prefix(Player __instance, HitData hit) { if (hit.GetTotalDamage() >= ((Character)__instance).GetHealth()) { return false; } return true; } } namespace discordScreenshots { public class BepinexConfiguration { public static ConfigFile Config; public static ConfigEntry<string> WebhookURL; public static ConfigEntry<string> WebhookUsername; public static ConfigEntry<string> WebhookAvatarURL; public static ConfigEntry<int> WebhookTimeoutSeconds = null; public static ConfigEntry<string> DeathMessage; public static ConfigEntry<KeyCode> ScreenshotHotkey; public static ConfigEntry<string> HotkeyScreenshotWebhookURL; public static ConfigEntry<string> HotkeyScreenshotWebhookUsername; public static ConfigEntry<string> HotkeyScreenshotWebhookAvatarURL; public static ConfigEntry<string> HotkeyScreenshotMessage; private static readonly Random _random = new Random(); private static string _localWebhookURL = ""; private static string _localWebhookUsername = ""; private static string _localWebhookAvatarURL = ""; private static string _localHotkeyScreenshotWebhookURL = ""; private static string _localHotkeyScreenshotWebhookUsername = ""; private static string _localHotkeyScreenshotWebhookAvatarURL = ""; public static string GetRandomDeathMessage() { string value = DeathMessage.Value; if (string.IsNullOrEmpty(value)) { return "met their demise!"; } string[] array = (from m in value.Split(new char[1] { ';' }) select m.Trim() into m where !string.IsNullOrEmpty(m) select m).ToArray(); if (array.Length == 0) { return "met their demise!"; } return array[_random.Next(array.Length)]; } public static string GetWebhookURL() { return GetSyncedValueOrLocalFallback(WebhookURL, _localWebhookURL); } public static string GetWebhookUsername() { if (ShouldUseLocalFallback(WebhookURL, _localWebhookURL)) { return _localWebhookUsername; } return GetSyncedValueOrLocalFallback(WebhookUsername, _localWebhookUsername); } public static string GetWebhookAvatarURL() { if (ShouldUseLocalFallback(WebhookURL, _localWebhookURL)) { return _localWebhookAvatarURL; } return GetSyncedValueOrLocalFallback(WebhookAvatarURL, _localWebhookAvatarURL); } public static string GetHotkeyScreenshotWebhookURL() { return GetSyncedValueOrLocalFallback(HotkeyScreenshotWebhookURL, _localHotkeyScreenshotWebhookURL); } public static string GetHotkeyScreenshotWebhookUsername() { if (ShouldUseLocalFallback(HotkeyScreenshotWebhookURL, _localHotkeyScreenshotWebhookURL)) { return _localHotkeyScreenshotWebhookUsername; } return GetSyncedValueOrLocalFallback(HotkeyScreenshotWebhookUsername, _localHotkeyScreenshotWebhookUsername); } public static string GetHotkeyScreenshotWebhookAvatarURL() { if (ShouldUseLocalFallback(HotkeyScreenshotWebhookURL, _localHotkeyScreenshotWebhookURL)) { return _localHotkeyScreenshotWebhookAvatarURL; } return GetSyncedValueOrLocalFallback(HotkeyScreenshotWebhookAvatarURL, _localHotkeyScreenshotWebhookAvatarURL); } public static void GenerateConfigs(ConfigFile configFile) { Config = configFile; ScreenshotHotkey = ConfigFileExtensions.BindConfig<KeyCode>(Config, "Screenshot", "Hotkey", (KeyCode)293, "The hotkey to take a screenshot and send to Discord.", false, (int?)1, (AcceptableValueBase)null, (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null); WebhookURL = ConfigFileExtensions.BindConfig<string>(Config, "Webhook", "URL", "", "The URL of the Discord webhook to send messages to.", true, (int?)2, (AcceptableValueBase)null, (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null); WebhookUsername = ConfigFileExtensions.BindConfig<string>(Config, "Webhook", "Username", "Valheim Death Bot", "The username of the Discord webhook to send messages to.", true, (int?)3, (AcceptableValueBase)null, (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null); WebhookAvatarURL = ConfigFileExtensions.BindConfig<string>(Config, "Webhook", "AvatarURL", "", "The avatar URL of the Discord webhook to send messages to.", true, (int?)4, (AcceptableValueBase)null, (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null); WebhookTimeoutSeconds = ConfigFileExtensions.BindConfig<int>(Config, "Webhook", "TimeoutSeconds", 60, "The maximum time to wait for each Discord webhook request.", false, (int?)10, (AcceptableValueBase)(object)new AcceptableValueRange<int>(5, 600), (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null); DeathMessage = ConfigFileExtensions.BindConfig<string>(Config, "Death Screenshot", "Message", "met their demise! Final moments captured...", "The message to send with death screenshots (player name will be prepended automatically).", true, (int?)5, (AcceptableValueBase)null, (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null); HotkeyScreenshotWebhookURL = ConfigFileExtensions.BindConfig<string>(Config, "Player Capture Webhook", "URL", "", "Optional separate webhook URL for player capture (F12) screenshots. If empty, uses the main Webhook URL.", true, (int?)6, (AcceptableValueBase)null, (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null); HotkeyScreenshotWebhookUsername = ConfigFileExtensions.BindConfig<string>(Config, "Player Capture Webhook", "Username", "Valheim Screenshot Bot", "The username for the player capture webhook.", true, (int?)7, (AcceptableValueBase)null, (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null); HotkeyScreenshotWebhookAvatarURL = ConfigFileExtensions.BindConfig<string>(Config, "Player Capture Webhook", "AvatarURL", "", "The avatar URL for the player capture webhook.", true, (int?)8, (AcceptableValueBase)null, (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null); HotkeyScreenshotMessage = ConfigFileExtensions.BindConfig<string>(Config, "Player Capture Webhook", "Message", "captured this screenshot!", "The message to send with player capture screenshots (player name will be prepended automatically).", true, (int?)9, (AcceptableValueBase)null, (Action<ConfigEntryBase>)null, (ConfigurationManagerAttributes)null); _localWebhookURL = Normalize(WebhookURL.Value); _localWebhookUsername = Normalize(WebhookUsername.Value); _localWebhookAvatarURL = Normalize(WebhookAvatarURL.Value); _localHotkeyScreenshotWebhookURL = Normalize(HotkeyScreenshotWebhookURL.Value); _localHotkeyScreenshotWebhookUsername = Normalize(HotkeyScreenshotWebhookUsername.Value); _localHotkeyScreenshotWebhookAvatarURL = Normalize(HotkeyScreenshotWebhookAvatarURL.Value); } private static string GetSyncedValueOrLocalFallback(ConfigEntry<string> entry, string localFallback) { string text = Normalize(entry.Value); if (text.Length <= 0) { return localFallback; } return text; } private static bool ShouldUseLocalFallback(ConfigEntry<string> entry, string localFallback) { if (Normalize(entry.Value).Length == 0) { return localFallback.Length > 0; } return false; } private static string Normalize(string value) { if (!string.IsNullOrWhiteSpace(value)) { return value.Trim(); } return ""; } } public class SimpleDiscordWebhook { private const int LargeScreenshotPixelThreshold = 4000000; private const int LargeScreenshotJpegQuality = 90; private static readonly HttpClient WebhookHttpClient = CreateHttpClient(); private readonly Uri _webhookUri; private readonly string? _username; private readonly string? _avatarUrl; public SimpleDiscordWebhook(string webhookUrl, string? username = null, string? avatarUrl = null) { if (!TryNormalizeWebhookUrl(webhookUrl, out Uri webhookUri, out string reason)) { throw new ArgumentException("Invalid webhook URL: " + reason, "webhookUrl"); } _webhookUri = webhookUri; _username = NormalizeOptionalText(username); _avatarUrl = NormalizeOptionalText(avatarUrl); } public static string CreateScreenshotFilename(string baseName, DateTime timestamp) { return CreateScreenshotFilename(baseName, timestamp, "png"); } public static string CreateScreenshotFilename(string baseName, DateTime timestamp, string extension) { return $"{baseName}_{timestamp:yyyy-MM-dd_HH-mm-ss}.{extension}"; } public async Task SendMessageAsync(string message) { if (string.IsNullOrEmpty(message)) { throw new ArgumentException("Message cannot be null or empty", "message"); } string jsonPayload = JsonConvert.SerializeObject((object)new SimpleWebhookPayload { content = message, username = _username, avatar_url = _avatarUrl }); await SendPayloadAsync(jsonPayload); } public void SendMessage(string message) { SendMessageAsync(message).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter().GetResult(); } public async Task SendScreenshotAsync(string? message = null, string? filename = null) { try { Texture2D val = ScreenCapture.CaptureScreenshotAsTexture(); if ((Object)(object)val == (Object)null) { throw new Exception("Failed to capture screenshot - returned null texture"); } ScreenshotUploadData uploadData = ProcessScreenshotForUpload(val); filename = NormalizeScreenshotFilename(filename, uploadData.Extension); await Task.Run(async delegate { await SendFileAsync(uploadData.Data, filename, message, uploadData.ContentType); }); } catch (Exception ex) { throw new Exception("Error capturing and sending screenshot: " + ex.Message, ex); } } public static Texture2D CaptureScreenshot() { Texture2D obj = ScreenCapture.CaptureScreenshotAsTexture(); if ((Object)(object)obj == (Object)null) { throw new Exception("Failed to capture screenshot - returned null texture"); } return obj; } public byte[] ProcessScreenshot(Texture2D screenshot) { return ProcessScreenshotForUpload(screenshot).Data; } public ScreenshotUploadData ProcessScreenshotForUpload(Texture2D screenshot) { int width = ((Texture)screenshot).width; int height = ((Texture)screenshot).height; byte[] array; string extension; string contentType; string text; if ((((long)width * (long)height >= 4000000) ? 1 : 0) == 1) { array = ImageConversion.EncodeToJPG(screenshot, 90); extension = "jpg"; contentType = "image/jpeg"; text = $"JPEG quality {90}"; } else { array = ImageConversion.EncodeToPNG(screenshot); extension = "png"; contentType = "image/png"; text = "PNG"; } Object.DestroyImmediate((Object)(object)screenshot); if (array == null || array.Length == 0) { throw new Exception("Failed to encode screenshot to " + text); } Debug.Log((object)($"Screenshot captured at {width}x{height} and encoded as {text} - " + $"{array.Length} bytes, uploading...")); return new ScreenshotUploadData(array, extension, contentType, text); } public async Task SendFileAsync(byte[] fileData, string filename, string? message = null, string contentType = "image/png") { if (fileData == null || fileData.Length == 0) { throw new ArgumentException("File data cannot be null or empty", "fileData"); } if (string.IsNullOrEmpty(filename)) { throw new ArgumentException("Filename cannot be null or empty", "filename"); } string boundary = "----formdata-discord-" + DateTime.Now.Ticks.ToString("x"); using MemoryStream memoryStream = new MemoryStream(); await WriteMultipartFormDataAsync(memoryStream, boundary, fileData, filename, message, contentType); byte[] formData = memoryStream.ToArray(); await SendMultipartPayloadAsync(formData, boundary); } private async Task SendPayloadAsync(string jsonPayload) { int timeoutSeconds; using CancellationTokenSource timeoutSource = CreateWebhookTimeoutSource(out timeoutSeconds); _ = 1; try { StringContent content = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); try { HttpResponseMessage response = await WebhookHttpClient.PostAsync(_webhookUri, (HttpContent)(object)content, timeoutSource.Token); try { string text = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { throw new Exception($"Discord webhook returned status: {(int)response.StatusCode} {response.StatusCode} - {text}"); } if (!string.IsNullOrEmpty(text)) { Debug.Log((object)("Discord response: " + text)); } } finally { ((IDisposable)response)?.Dispose(); } } finally { ((IDisposable)content)?.Dispose(); } } catch (OperationCanceledException innerException) when (timeoutSource.IsCancellationRequested) { throw new TimeoutException($"Discord webhook request timed out after {timeoutSeconds} seconds.", innerException); } catch (Exception ex) { throw new Exception("Error sending Discord webhook: " + ex.Message, ex); } } private async Task SendMultipartPayloadAsync(byte[] formData, string boundary) { int timeoutSeconds; using CancellationTokenSource timeoutSource = CreateWebhookTimeoutSource(out timeoutSeconds); _ = 1; try { ByteArrayContent content = new ByteArrayContent(formData); try { ((HttpContent)content).Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data; boundary=" + boundary); HttpResponseMessage response = await WebhookHttpClient.PostAsync(_webhookUri, (HttpContent)(object)content, timeoutSource.Token); try { string text = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { throw new Exception($"Discord webhook returned status: {(int)response.StatusCode} {response.StatusCode} - {text}"); } if (!string.IsNullOrEmpty(text)) { Debug.Log((object)("Discord file upload response: " + text)); } } finally { ((IDisposable)response)?.Dispose(); } } finally { ((IDisposable)content)?.Dispose(); } } catch (OperationCanceledException innerException) when (timeoutSource.IsCancellationRequested) { throw new TimeoutException($"Discord webhook file upload timed out after {timeoutSeconds} seconds for {formData.Length} bytes.", innerException); } catch (Exception ex) { throw new Exception("Error sending Discord webhook file: " + ex.Message, ex); } } private async Task WriteMultipartFormDataAsync(Stream stream, string boundary, byte[] fileData, string filename, string? message, string contentType) { string newLine = "\r\n"; byte[] boundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + newLine); await stream.WriteAsync(boundaryBytes, 0, boundaryBytes.Length); string s = "Content-Disposition: form-data; name=\"files[0]\"; filename=\"" + filename + "\"" + newLine + "Content-Type: " + contentType + newLine + newLine; byte[] bytes = Encoding.UTF8.GetBytes(s); await stream.WriteAsync(bytes, 0, bytes.Length); await stream.WriteAsync(fileData, 0, fileData.Length); byte[] newLineBytes = Encoding.UTF8.GetBytes(newLine); await stream.WriteAsync(newLineBytes, 0, newLineBytes.Length); if (!string.IsNullOrEmpty(message)) { await stream.WriteAsync(boundaryBytes, 0, boundaryBytes.Length); SimpleWebhookPayload simpleWebhookPayload = new SimpleWebhookPayload { content = message, username = _username, avatar_url = _avatarUrl }; string jsonPayload = JsonConvert.SerializeObject((object)simpleWebhookPayload); string s2 = "Content-Disposition: form-data; name=\"payload_json\"" + newLine + "Content-Type: application/json" + newLine + newLine; byte[] bytes2 = Encoding.UTF8.GetBytes(s2); await stream.WriteAsync(bytes2, 0, bytes2.Length); byte[] bytes3 = Encoding.UTF8.GetBytes(jsonPayload); await stream.WriteAsync(bytes3, 0, bytes3.Length); await stream.WriteAsync(newLineBytes, 0, newLineBytes.Length); } byte[] bytes4 = Encoding.UTF8.GetBytes("--" + boundary + "--" + newLine); await stream.WriteAsync(bytes4, 0, bytes4.Length); } private static HttpClient CreateHttpClient() { //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_0026: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; ServicePointManager.Expect100Continue = false; HttpClient val = new HttpClient { Timeout = Timeout.InfiniteTimeSpan }; val.DefaultRequestHeaders.UserAgent.ParseAdd("discord-screenshots"); return val; } private static CancellationTokenSource CreateWebhookTimeoutSource(out int timeoutSeconds) { timeoutSeconds = BepinexConfiguration.WebhookTimeoutSeconds.Value; return new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds)); } public static async Task SendQuickMessageAsync(string webhookUrl, string message, string? username = null, string? avatarUrl = null) { await new SimpleDiscordWebhook(webhookUrl, username, avatarUrl).SendMessageAsync(message); } public static void SendQuickMessage(string webhookUrl, string message, string? username = null, string? avatarUrl = null) { SendQuickMessageAsync(webhookUrl, message, username, avatarUrl).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter().GetResult(); } public static async Task SendQuickScreenshotAsync(string webhookUrl, string? message = null, string? username = null, string? avatarUrl = null, string? filename = null) { await new SimpleDiscordWebhook(webhookUrl, username, avatarUrl).SendScreenshotAsync(message, filename); } public static void SendQuickScreenshot(string webhookUrl, string? message = null, string? username = null, string? avatarUrl = null, string? filename = null) { SendQuickScreenshotAsync(webhookUrl, message, username, avatarUrl, filename).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter().GetResult(); } private static string NormalizeScreenshotFilename(string? filename, string extension) { if (string.IsNullOrEmpty(filename)) { return $"valheim_screenshot_{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.{extension}"; } string extension2 = Path.GetExtension(filename); if (string.IsNullOrEmpty(extension2)) { return filename + "." + extension; } if (!extension2.Equals(".png", StringComparison.OrdinalIgnoreCase) && !extension2.Equals(".jpg", StringComparison.OrdinalIgnoreCase) && !extension2.Equals(".jpeg", StringComparison.OrdinalIgnoreCase)) { return filename; } return Path.ChangeExtension(filename, extension) ?? (filename + "." + extension); } private static bool TryNormalizeWebhookUrl(string? webhookUrl, out Uri webhookUri, out string reason) { webhookUri = null; if (webhookUrl == null) { reason = "URL cannot be empty"; return false; } string text = webhookUrl.Trim(); if (text.Length == 0) { reason = "URL cannot be empty"; return false; } for (int i = 0; i < text.Length; i++) { if (char.IsControl(text[i])) { reason = "URL contains control characters"; return false; } } if (!Uri.TryCreate(text, UriKind.Absolute, out Uri result) || result == null) { reason = "URL must be an absolute HTTPS URL"; return false; } if (!string.Equals(result.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { reason = "URL must use HTTPS"; return false; } if (string.IsNullOrEmpty(result.Host)) { reason = "URL must include a host"; return false; } webhookUri = result; reason = string.Empty; return true; } private static string? NormalizeOptionalText(string? value) { if (value == null) { return null; } string text = value.Trim(); if (text.Length != 0) { return text; } return null; } } public sealed class ScreenshotUploadData { public byte[] Data { get; } public string Extension { get; } public string ContentType { get; } public string FormatName { get; } public ScreenshotUploadData(byte[] data, string extension, string contentType, string formatName) { Data = data; Extension = extension; ContentType = contentType; FormatName = formatName; } } internal enum ScreenshotEncoding { Png, Jpeg } internal class SimpleWebhookPayload { public string? content { get; set; } public string? username { get; set; } public string? avatar_url { get; set; } } [BepInPlugin("warpalicious.discordScreenshots", "discordScreenshots", "1.6.8")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class discordScreenshotsPlugin : BaseUnityPlugin { private const string ModName = "discordScreenshots"; private const string ModVersion = "1.6.8"; private const string Author = "warpalicious"; private const string ModGUID = "warpalicious.discordScreenshots"; private readonly Harmony HarmonyInstance = new Harmony("warpalicious.discordScreenshots"); public static readonly ManualLogSource TemplateLogger = Logger.CreateLogSource("discordScreenshots"); public static AssetBundle assetBundle; public void Awake() { Assembly executingAssembly = Assembly.GetExecutingAssembly(); HarmonyInstance.PatchAll(executingAssembly); BepinexConfiguration.GenerateConfigs(((BaseUnityPlugin)this).Config); } public static void LoadAssetBundle() { assetBundle = AssetUtils.LoadAssetBundleFromResources("discordscreenshots", Assembly.GetExecutingAssembly()); } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); } private void OnApplicationQuit() { PlayerDeathScreenshotPatch.UploadStoredDeathScreenshot("application quit", waitForUpload: true); } } } namespace discordScreenshots.Patches { [HarmonyPatch(typeof(Terminal), "InitTerminal")] public static class DiscordConsoleCommandPatch { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static ConsoleEvent <>9__0_0; public static ConsoleEvent <>9__0_1; public static ConsoleEvent <>9__0_2; internal void <Postfix>b__0_0(ConsoleEventArgs args) { <>c__DisplayClass0_0 CS$<>8__locals6 = new <>c__DisplayClass0_0(); if (args.Length < 2) { Terminal context = args.Context; if (context != null) { context.AddString("Usage: discord <message>"); } Terminal context2 = args.Context; if (context2 != null) { context2.AddString("Example: discord Hello from Valheim!"); } return; } CS$<>8__locals6.message = string.Join(" ", args.Args, 1, args.Args.Length - 1); if (string.IsNullOrWhiteSpace(CS$<>8__locals6.message)) { Terminal context3 = args.Context; if (context3 != null) { context3.AddString("Message cannot be empty"); } return; } CS$<>8__locals6.playerName = "Server"; if ((Object)(object)Player.m_localPlayer != (Object)null && !string.IsNullOrEmpty(Player.m_localPlayer.GetPlayerName())) { CS$<>8__locals6.playerName = Player.m_localPlayer.GetPlayerName(); } Terminal context4 = args.Context; if (context4 != null) { context4.AddString("Sending message to Discord..."); } Task.Run(async delegate { try { string formattedMessage = "\ud83d\udcac **" + CS$<>8__locals6.playerName + "**: " + CS$<>8__locals6.message; await SimpleDiscordWebhook.SendQuickMessageAsync(BepinexConfiguration.GetWebhookURL(), formattedMessage, "Valheim Console"); Debug.Log((object)("Discord message sent successfully: " + formattedMessage)); } catch (Exception ex) { Debug.LogError((object)("Failed to send Discord message: " + ex.Message)); } }); } internal void <Postfix>b__0_1(ConsoleEventArgs args) { <>c__DisplayClass0_1 CS$<>8__locals3 = new <>c__DisplayClass0_1(); Terminal context = args.Context; if (context != null) { context.AddString("Testing Discord webhook connection..."); } CS$<>8__locals3.playerName = "Server"; if ((Object)(object)Player.m_localPlayer != (Object)null && !string.IsNullOrEmpty(Player.m_localPlayer.GetPlayerName())) { CS$<>8__locals3.playerName = Player.m_localPlayer.GetPlayerName(); } Task.Run(async delegate { try { await SimpleDiscordWebhook.SendQuickMessageAsync(BepinexConfiguration.GetWebhookURL(), "\ud83e\uddea Discord webhook test from **" + CS$<>8__locals3.playerName + "** - Connection working!", "Valheim Test Bot"); Debug.Log((object)"Discord webhook test message sent successfully!"); } catch (Exception ex) { Debug.LogError((object)("Discord webhook test failed: " + ex.Message)); } }); } internal void <Postfix>b__0_2(ConsoleEventArgs args) { <>c__DisplayClass0_2 CS$<>8__locals18 = new <>c__DisplayClass0_2 { playerName = "Unknown Player" }; if ((Object)(object)Player.m_localPlayer != (Object)null && !string.IsNullOrEmpty(Player.m_localPlayer.GetPlayerName())) { CS$<>8__locals18.playerName = Player.m_localPlayer.GetPlayerName(); } CS$<>8__locals18.message = null; if (args.Length > 1) { CS$<>8__locals18.message = string.Join(" ", args.Args, 1, args.Args.Length - 1); } if (string.IsNullOrEmpty(CS$<>8__locals18.message)) { CS$<>8__locals18.message = "\ud83d\udcf8 **" + CS$<>8__locals18.playerName + "** took a screenshot!"; } Terminal context = args.Context; if (context != null) { context.AddString("Capturing screenshot..."); } try { CS$<>8__locals18.webhook = new SimpleDiscordWebhook(BepinexConfiguration.GetWebhookURL(), "Valheim Screenshots"); DateTime now = DateTime.Now; Texture2D val = ScreenCapture.CaptureScreenshotAsTexture(); if ((Object)(object)val == (Object)null) { throw new Exception("Failed to capture screenshot"); } CS$<>8__locals18.uploadData = CS$<>8__locals18.webhook.ProcessScreenshotForUpload(val); CS$<>8__locals18.filename = SimpleDiscordWebhook.CreateScreenshotFilename(CS$<>8__locals18.playerName + "_screenshot", now, CS$<>8__locals18.uploadData.Extension); Terminal context2 = args.Context; if (context2 != null) { context2.AddString("Screenshot captured, uploading to Discord..."); } Task.Run(async delegate { try { await CS$<>8__locals18.webhook.SendFileAsync(CS$<>8__locals18.uploadData.Data, CS$<>8__locals18.filename, CS$<>8__locals18.message, CS$<>8__locals18.uploadData.ContentType); Debug.Log((object)("Screenshot uploaded to Discord for " + CS$<>8__locals18.playerName)); } catch (Exception ex2) { Debug.LogError((object)("Failed to upload screenshot: " + ex2.Message)); } }); } catch (Exception ex) { Terminal context3 = args.Context; if (context3 != null) { context3.AddString("Error: " + ex.Message); } Debug.LogError((object)("Failed to capture screenshot: " + ex.Message)); } } } [CompilerGenerated] private sealed class <>c__DisplayClass0_0 { public string playerName; public string message; internal async Task <Postfix>b__3() { try { string formattedMessage = "\ud83d\udcac **" + playerName + "**: " + message; await SimpleDiscordWebhook.SendQuickMessageAsync(BepinexConfiguration.GetWebhookURL(), formattedMessage, "Valheim Console"); Debug.Log((object)("Discord message sent successfully: " + formattedMessage)); } catch (Exception ex) { Debug.LogError((object)("Failed to send Discord message: " + ex.Message)); } } } [CompilerGenerated] private sealed class <>c__DisplayClass0_1 { public string playerName; internal async Task <Postfix>b__4() { try { await SimpleDiscordWebhook.SendQuickMessageAsync(BepinexConfiguration.GetWebhookURL(), "\ud83e\uddea Discord webhook test from **" + playerName + "** - Connection working!", "Valheim Test Bot"); Debug.Log((object)"Discord webhook test message sent successfully!"); } catch (Exception ex) { Debug.LogError((object)("Discord webhook test failed: " + ex.Message)); } } } [CompilerGenerated] private sealed class <>c__DisplayClass0_2 { public string message; public string playerName; public SimpleDiscordWebhook webhook; public ScreenshotUploadData uploadData; public string filename; internal async Task <Postfix>b__5() { try { await webhook.SendFileAsync(uploadData.Data, filename, message, uploadData.ContentType); Debug.Log((object)("Screenshot uploaded to Discord for " + playerName)); } catch (Exception ex) { Debug.LogError((object)("Failed to upload screenshot: " + ex.Message)); } } } [HarmonyPostfix] private static void Postfix() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown object obj = <>c.<>9__0_0; if (obj == null) { ConsoleEvent val = delegate(ConsoleEventArgs args) { if (args.Length < 2) { Terminal context = args.Context; if (context != null) { context.AddString("Usage: discord <message>"); } Terminal context2 = args.Context; if (context2 != null) { context2.AddString("Example: discord Hello from Valheim!"); } } else { string message = string.Join(" ", args.Args, 1, args.Args.Length - 1); if (string.IsNullOrWhiteSpace(message)) { Terminal context3 = args.Context; if (context3 != null) { context3.AddString("Message cannot be empty"); } } else { string playerName = "Server"; if ((Object)(object)Player.m_localPlayer != (Object)null && !string.IsNullOrEmpty(Player.m_localPlayer.GetPlayerName())) { playerName = Player.m_localPlayer.GetPlayerName(); } Terminal context4 = args.Context; if (context4 != null) { context4.AddString("Sending message to Discord..."); } Task.Run(async delegate { try { string formattedMessage = "\ud83d\udcac **" + playerName + "**: " + message; await SimpleDiscordWebhook.SendQuickMessageAsync(BepinexConfiguration.GetWebhookURL(), formattedMessage, "Valheim Console"); Debug.Log((object)("Discord message sent successfully: " + formattedMessage)); } catch (Exception ex) { Debug.LogError((object)("Failed to send Discord message: " + ex.Message)); } }); } } }; <>c.<>9__0_0 = val; obj = (object)val; } new ConsoleCommand("discord", "sends a message to Discord webhook. Usage: discord <message>", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj2 = <>c.<>9__0_1; if (obj2 == null) { ConsoleEvent val2 = delegate(ConsoleEventArgs args) { Terminal context = args.Context; if (context != null) { context.AddString("Testing Discord webhook connection..."); } string playerName = "Server"; if ((Object)(object)Player.m_localPlayer != (Object)null && !string.IsNullOrEmpty(Player.m_localPlayer.GetPlayerName())) { playerName = Player.m_localPlayer.GetPlayerName(); } Task.Run(async delegate { try { await SimpleDiscordWebhook.SendQuickMessageAsync(BepinexConfiguration.GetWebhookURL(), "\ud83e\uddea Discord webhook test from **" + playerName + "** - Connection working!", "Valheim Test Bot"); Debug.Log((object)"Discord webhook test message sent successfully!"); } catch (Exception ex) { Debug.LogError((object)("Discord webhook test failed: " + ex.Message)); } }); }; <>c.<>9__0_1 = val2; obj2 = (object)val2; } new ConsoleCommand("discordtest", "tests the Discord webhook connection", (ConsoleEvent)obj2, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj3 = <>c.<>9__0_2; if (obj3 == null) { ConsoleEvent val3 = delegate(ConsoleEventArgs args) { string playerName = "Unknown Player"; if ((Object)(object)Player.m_localPlayer != (Object)null && !string.IsNullOrEmpty(Player.m_localPlayer.GetPlayerName())) { playerName = Player.m_localPlayer.GetPlayerName(); } string message = null; if (args.Length > 1) { message = string.Join(" ", args.Args, 1, args.Args.Length - 1); } if (string.IsNullOrEmpty(message)) { message = "\ud83d\udcf8 **" + playerName + "** took a screenshot!"; } Terminal context = args.Context; if (context != null) { context.AddString("Capturing screenshot..."); } try { SimpleDiscordWebhook webhook = new SimpleDiscordWebhook(BepinexConfiguration.GetWebhookURL(), "Valheim Screenshots"); DateTime now = DateTime.Now; Texture2D val4 = ScreenCapture.CaptureScreenshotAsTexture(); if ((Object)(object)val4 == (Object)null) { throw new Exception("Failed to capture screenshot"); } ScreenshotUploadData uploadData = webhook.ProcessScreenshotForUpload(val4); string filename = SimpleDiscordWebhook.CreateScreenshotFilename(playerName + "_screenshot", now, uploadData.Extension); Terminal context2 = args.Context; if (context2 != null) { context2.AddString("Screenshot captured, uploading to Discord..."); } Task.Run(async delegate { try { await webhook.SendFileAsync(uploadData.Data, filename, message, uploadData.ContentType); Debug.Log((object)("Screenshot uploaded to Discord for " + playerName)); } catch (Exception ex2) { Debug.LogError((object)("Failed to upload screenshot: " + ex2.Message)); } }); } catch (Exception ex) { Terminal context3 = args.Context; if (context3 != null) { context3.AddString("Error: " + ex.Message); } Debug.LogError((object)("Failed to capture screenshot: " + ex.Message)); } }; <>c.<>9__0_2 = val3; obj3 = (object)val3; } new ConsoleCommand("discordscreenshot", "captures and sends a screenshot to Discord", (ConsoleEvent)obj3, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); } } [HarmonyPatch(typeof(Player), "Update")] public static class HotkeyScreenshotPatch { [HarmonyPostfix] private static void Postfix(Player __instance) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) try { if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && Input.GetKeyDown(BepinexConfiguration.ScreenshotHotkey.Value)) { string text = __instance.GetPlayerName(); if (string.IsNullOrEmpty(text)) { text = "Unknown Player"; } Debug.Log((object)("HotkeyScreenshotPatch: " + text + " pressed screenshot hotkey")); string hotkeyScreenshotWebhookURL = BepinexConfiguration.GetHotkeyScreenshotWebhookURL(); bool num = !string.IsNullOrEmpty(hotkeyScreenshotWebhookURL); string webhookUrl = (num ? hotkeyScreenshotWebhookURL : BepinexConfiguration.GetWebhookURL()); string webhookUsername = (num ? BepinexConfiguration.GetHotkeyScreenshotWebhookUsername() : BepinexConfiguration.GetWebhookUsername()); string webhookAvatarUrl = (num ? BepinexConfiguration.GetHotkeyScreenshotWebhookAvatarURL() : BepinexConfiguration.GetWebhookAvatarURL()); string text2 = (num ? BepinexConfiguration.HotkeyScreenshotMessage.Value : "captured this screenshot!"); string screenshotMessage = "\ud83d\udcf8 **" + text + "** " + text2; string filename = SimpleDiscordWebhook.CreateScreenshotFilename(text + "_screenshot", DateTime.Now, "png"); SendHotkeyScreenshotAsync(webhookUrl, screenshotMessage, webhookUsername, webhookAvatarUrl, filename); } } catch (Exception ex) { Debug.LogError((object)("HotkeyScreenshotPatch: Error: " + ex.Message)); } } private static async Task SendHotkeyScreenshotAsync(string webhookUrl, string screenshotMessage, string webhookUsername, string webhookAvatarUrl, string filename) { try { await SimpleDiscordWebhook.SendQuickScreenshotAsync(webhookUrl, screenshotMessage, webhookUsername, webhookAvatarUrl, filename); } catch (Exception ex) { Debug.LogError((object)("HotkeyScreenshotPatch: Failed to upload screenshot: " + ex.Message)); } } } public static class PlayerDeathScreenshotPatch { internal static Texture2D? storedDeathScreenshot; internal static string? storedPlayerName; internal static DateTime storedDeathTime; internal static IEnumerator CaptureDeathScreenshotCoroutine(string playerName) { yield return (object)new WaitForSeconds(0.1f); storedDeathScreenshot = SimpleDiscordWebhook.CaptureScreenshot(); storedPlayerName = playerName; storedDeathTime = DateTime.Now; Debug.Log((object)("Death screenshot captured and stored for " + playerName)); } internal static void UploadStoredDeathScreenshot(string trigger, bool waitForUpload) { if ((Object)(object)storedDeathScreenshot == (Object)null) { Debug.Log((object)("Death screenshot upload skipped on " + trigger + ": no stored death screenshot found")); return; } Texture2D val = storedDeathScreenshot; string text = (string.IsNullOrEmpty(storedPlayerName) ? "Unknown Player" : storedPlayerName); DateTime timestamp = storedDeathTime; storedDeathScreenshot = null; storedPlayerName = null; try { SimpleDiscordWebhook webhook = new SimpleDiscordWebhook(BepinexConfiguration.GetWebhookURL(), BepinexConfiguration.GetWebhookUsername(), BepinexConfiguration.GetWebhookAvatarURL()); ScreenshotUploadData uploadData = webhook.ProcessScreenshotForUpload(val); string deathMessage = "**" + text + "** " + BepinexConfiguration.GetRandomDeathMessage(); string filename = SimpleDiscordWebhook.CreateScreenshotFilename(text + "_death", timestamp, uploadData.Extension); Task task = Task.Run(async delegate { await webhook.SendFileAsync(uploadData.Data, filename, deathMessage, uploadData.ContentType); }); if (waitForUpload) { task.GetAwaiter().GetResult(); Debug.Log((object)("Death screenshot uploaded successfully for " + text + " on " + trigger)); } else { LogUploadResultAsync(task, text, trigger); } } catch (Exception ex) { Debug.LogError((object)("Error processing stored death screenshot on " + trigger + ": " + ex.Message)); if ((Object)(object)val != (Object)null) { Object.DestroyImmediate((Object)(object)val); } } } private static async Task LogUploadResultAsync(Task uploadTask, string playerName, string trigger) { try { await uploadTask; Debug.Log((object)("Death screenshot uploaded successfully for " + playerName + " on " + trigger)); } catch (Exception ex) { Debug.LogError((object)("Error uploading death screenshot on " + trigger + ": " + ex.Message)); } } } [HarmonyPatch(typeof(Humanoid), "OnRagdollCreated")] public static class PlayerRagdollScreenshotPatch { [HarmonyPostfix] private static void Postfix(Humanoid __instance) { try { Player val = (Player)(object)((__instance is Player) ? __instance : null); if (val != null && !((Object)(object)val != (Object)(object)Player.m_localPlayer)) { string text = val.GetPlayerName(); if (string.IsNullOrEmpty(text)) { text = "Unknown Player"; } Debug.Log((object)("PlayerRagdollScreenshotPatch: " + text + " died - capturing screenshot")); ((MonoBehaviour)val).StartCoroutine(PlayerDeathScreenshotPatch.CaptureDeathScreenshotCoroutine(text)); } } catch (Exception ex) { Debug.LogError((object)("PlayerRagdollScreenshotPatch: Error: " + ex.Message)); } } } [HarmonyPatch(typeof(Player), "Awake")] public static class PlayerRespawnScreenshotPatch { [HarmonyPostfix] private static void Postfix(Player __instance) { try { Debug.Log((object)"PlayerRespawnScreenshotPatch: Awake"); Debug.Log((object)"PlayerRespawnScreenshotPatch: Local player confirmed"); if ((Object)(object)PlayerDeathScreenshotPatch.storedDeathScreenshot != (Object)null) { Debug.Log((object)("PlayerRespawnScreenshotPatch: Processing stored death screenshot for " + PlayerDeathScreenshotPatch.storedPlayerName)); PlayerDeathScreenshotPatch.UploadStoredDeathScreenshot("respawn", waitForUpload: false); } else { Debug.Log((object)"PlayerRespawnScreenshotPatch: No stored death screenshot found"); } } catch (Exception ex) { Debug.LogError((object)("PlayerRespawnScreenshotPatch: Error: " + ex.Message)); } } } [HarmonyPatch(typeof(Game), "Logout")] public static class GameLogoutDeathScreenshotPatch { [HarmonyPrefix] private static void Prefix() { try { PlayerDeathScreenshotPatch.UploadStoredDeathScreenshot("logout", waitForUpload: false); } catch (Exception ex) { Debug.LogError((object)("GameLogoutDeathScreenshotPatch: Error: " + ex.Message)); } } } }
plugins/DynamicStoragePiles/DynamicStoragePiles.dll
Decompiled 5 hours agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using DynamicStoragePiles.Compatibility; using HarmonyLib; using Jotunn; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("DynamicStoragePiles")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DynamicStoragePiles")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("e3243d22-4307-4008-ba36-9f326008cde5")] [assembly: AssemblyFileVersion("0.8.1")] [assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.8.1.0")] [module: UnverifiableCode] namespace DynamicStoragePiles { public static class ConfigSettings { public enum RecipeSetting { AllStoragePiles, OnlyDynamicStoragePiles, OnlyOriginalStoragePiles } private static ConfigFile config; public static ConfigEntry<bool> azuAutoStoreCompat; public static ConfigEntry<bool> azuAutoStoreItemWhitelist; public static ConfigEntry<bool> restrictDynamicPiles; public static ConfigEntry<RecipeSetting> VanillaRecipeSetting { get; private set; } public static ConfigEntry<RecipeSetting> IngotStacksRecipeSetting { get; private set; } public static ConfigEntry<RecipeSetting> StackedBarsRecipeSetting { get; private set; } public static ConfigEntry<RecipeSetting> MoreStacksRecipeSetting { get; private set; } public static ConfigEntry<RecipeSetting> RefinedStonePiecesSetting { get; private set; } public static void Init(ConfigFile configFile) { //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_0015: Expected O, but got Unknown //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Expected O, but got Unknown config = configFile; ConfigurationManagerAttributes val = new ConfigurationManagerAttributes { IsAdminOnly = true }; string text = "\nCheats or world modifiers can ignore this setting. Existing pieces in the world are not affected"; string text2 = "\nRequires a restart to take effect"; string text3 = "1 - General"; VanillaRecipeSetting = config.Bind<RecipeSetting>(text3, "Vanilla Stack Recipes", RecipeSetting.OnlyDynamicStoragePiles, "Sets which pieces are placeable." + text); VanillaRecipeSetting.SettingChanged += delegate { DynamicStoragePiles.UpdateAllRecipes(); }; restrictDynamicPiles = config.Bind<bool>(text3, "Restrict Container Item Type", true, new ConfigDescription("Only allows the respective items to be stored in stack piles, so wood piles only accept wood etc.\nSynced with server", (AcceptableValueBase)null, new object[1] { val })); text3 = "2.0 - Compatibility AzuAutoStore"; azuAutoStoreCompat = config.Bind<bool>(text3, "Enable Compatibility", true, "Enables compatibility with AzuAutoStore." + text2); azuAutoStoreItemWhitelist = config.Bind<bool>(text3, "Enable Item Whitelist", true, "Only allows the respective items to be stored in stack piles"); text3 = "2.1 - Compatibility IngotStacks"; IngotStacksRecipeSetting = config.Bind<RecipeSetting>(text3, "IngotStacks Stack Recipes", RecipeSetting.AllStoragePiles, "Sets which pieces are placeable." + text); IngotStacksRecipeSetting.SettingChanged += delegate { DynamicStoragePiles.UpdateAllRecipes(); }; text3 = "2.2 - Compatibility StackedBars"; StackedBarsRecipeSetting = config.Bind<RecipeSetting>(text3, "StackedBars Stack Recipes", RecipeSetting.AllStoragePiles, "Sets which pieces are placeable." + text); StackedBarsRecipeSetting.SettingChanged += delegate { DynamicStoragePiles.UpdateAllRecipes(); }; text3 = "2.3 - Compatibility MoreStacks"; MoreStacksRecipeSetting = config.Bind<RecipeSetting>(text3, "MoreStacks Stack Recipes", RecipeSetting.AllStoragePiles, "Sets which pieces are placeable." + text); MoreStacksRecipeSetting.SettingChanged += delegate { DynamicStoragePiles.UpdateAllRecipes(); }; text3 = "2.4 - Compatibility RefinedStonePieces"; RefinedStonePiecesSetting = config.Bind<RecipeSetting>(text3, "RefinedStonePieces Stack Recipes", RecipeSetting.AllStoragePiles, "Sets which pieces are placeable." + text); RefinedStonePiecesSetting.SettingChanged += delegate { DynamicStoragePiles.UpdateAllRecipes(); }; } public static bool IsEnabled(this ConfigEntry<RecipeSetting> configEntry, bool isOriginal) { if (isOriginal) { return configEntry.Value == RecipeSetting.AllStoragePiles || configEntry.Value == RecipeSetting.OnlyOriginalStoragePiles; } return configEntry.Value == RecipeSetting.AllStoragePiles || configEntry.Value == RecipeSetting.OnlyDynamicStoragePiles; } } [BepInPlugin("com.maxsch.valheim.DynamicStoragePiles", "DynamicStoragePiles", "0.8.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] internal class DynamicStoragePiles : BaseUnityPlugin { public const string PluginName = "DynamicStoragePiles"; public const string PluginGuid = "com.maxsch.valheim.DynamicStoragePiles"; public const string PluginVersion = "0.8.1"; public const string PLUGIN_MORESTACKS_GUID = "ujhik.MoreStacks"; public static Harmony harmony; private static AssetBundle assetBundle; private List<CustomPiece> renderSprites = new List<CustomPiece>(); public static Dictionary<string, string> allowedItemsByStack = new Dictionary<string, string>(); public static Dictionary<string, string> allowedItemsByContainer = new Dictionary<string, string>(); private static List<string> vanillaStacks = new List<string> { "wood_stack", "wood_fine_stack", "wood_core_stack", "wood_yggdrasil_stack", "blackwood_stack", "stone_pile", "coal_pile", "blackmarble_pile", "grausten_pile", "skull_pile", "treasure_stack", "bone_stack" }; private static List<string> dynamicStacks = new List<string>(); public static DynamicStoragePiles Instance { get; private set; } private void Awake() { //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Expected O, but got Unknown Instance = this; assetBundle = AssetUtils.LoadAssetBundleFromResources("containerstacks"); AddStackPiece("MS_container_wood_stack", "Wood"); AddStackPiece("MS_container_finewood_stack", "FineWood"); AddStackPiece("MS_container_corewood_stack", "RoundLog"); AddStackPiece("MS_container_yggdrasil_wood_stack", "YggdrasilWood"); AddStackPiece("MS_container_blackwood_stack", "Blackwood"); AddStackPiece("MS_container_stone_pile", "Stone"); AddStackPiece("MS_container_coal_pile", "Coal"); AddStackPiece("MS_container_blackmarble_pile", "BlackMarble"); AddStackPiece("MS_container_grausten_pile", "Grausten"); AddStackPiece("MS_container_skull_pile", "Charredskull"); AddStackPiece("MS_container_bone_stack", "BoneFragments"); AddStackPiece("MS_container_coin_pile", "Coins"); ConfigSettings.Init(((BaseUnityPlugin)this).Config); PrefabManager.OnPrefabsRegistered += OnPrefabsRegistered; PieceManager.OnPiecesRegistered += OnPiecesRegistered; harmony = new Harmony("com.maxsch.valheim.DynamicStoragePiles"); harmony.PatchAll(); } private void Start() { if (Chainloader.PluginInfos.ContainsKey("Azumatt.AzuAutoStore") && ConfigSettings.azuAutoStoreCompat.Value) { AzuAutoStore.Init(); } if (Chainloader.PluginInfos.ContainsKey("Richard.IngotStacks")) { IngotStacks.Init(); } if (Chainloader.PluginInfos.ContainsKey("Azumatt.StackedBars")) { StackedBars.Init(); } if (Chainloader.PluginInfos.ContainsKey("blacks7ar.RefinedStonePieces")) { RefinedStonePieces.Init(); } } public static void UpdateAllRecipes() { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { UpdateRecipes(vanillaStacks, dynamicStacks, ConfigSettings.VanillaRecipeSetting); UpdateRecipes(IngotStacks.ingotStacks, IngotStacks.dynamicIngotStacks, ConfigSettings.IngotStacksRecipeSetting); UpdateRecipes(StackedBars.stackedBars, StackedBars.dynamicStackedBars, ConfigSettings.StackedBarsRecipeSetting); UpdateRecipes(MoreStacks.staticStacks, MoreStacks.dynamicStacks, ConfigSettings.MoreStacksRecipeSetting); UpdateRecipes(RefinedStonePieces.staticStacks, RefinedStonePieces.dynamicStacks, ConfigSettings.RefinedStonePiecesSetting); if (Object.op_Implicit((Object)(object)Player.m_localPlayer)) { Player.m_localPlayer.UpdateAvailablePiecesList(); } } } private static void UpdateRecipes(List<string> originalStackNames, List<string> dynamicStackNames, ConfigEntry<ConfigSettings.RecipeSetting> config) { foreach (string originalStackName in originalStackNames) { EnablePieceRecipes(originalStackName, config.IsEnabled(isOriginal: true)); } foreach (string dynamicStackName in dynamicStackNames) { EnablePieceRecipes(dynamicStackName, config.IsEnabled(isOriginal: false)); } } public static void EnablePieceRecipes(string prefabName, bool enabled) { GameObject prefab = ZNetScene.instance.GetPrefab(prefabName); Piece val = default(Piece); if (Object.op_Implicit((Object)(object)prefab) && prefab.TryGetComponent<Piece>(ref val)) { val.m_enabled = enabled; } else { Logger.LogWarning((object)("Could not find Piece " + prefabName + " to toggle recipes")); } } private void AddStackPiece(string pieceName, string craftItem) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown CustomPiece val = new CustomPiece(assetBundle, pieceName, true, StackConfig(craftItem, 10)); renderSprites.Add(val); dynamicStacks.Add(pieceName); AddPiece(val, craftItem); } public void AddCompatPiece(GameObject prefab, string craftItem, int amount) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown CustomPiece piece = new CustomPiece(prefab, false, StackConfig(craftItem, amount)); AddPiece(piece, craftItem); } public void AddCompatPiece(GameObject prefab, string craftItem, int amount, bool addGraphics) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown CustomPiece val = new CustomPiece(prefab, true, StackConfig(craftItem, amount)); if (addGraphics) { renderSprites.Add(val); } AddPiece(val, craftItem); } private void AddPiece(CustomPiece piece, string craftItem) { PieceManager.Instance.AddPiece(piece); allowedItemsByStack.Add(((Object)piece.PiecePrefab).name, craftItem); allowedItemsByContainer.Add(piece.PiecePrefab.GetComponent<Container>().m_name, craftItem); } private void OnPrefabsRegistered() { if (Chainloader.PluginInfos.ContainsKey("ujhik.MoreStacks")) { MoreStacks.Init(); } } private void OnPiecesRegistered() { PieceManager.OnPiecesRegistered -= OnPiecesRegistered; foreach (CustomPiece renderSprite in renderSprites) { ((MonoBehaviour)this).StartCoroutine(RenderSprite(renderSprite)); } UpdateAllRecipes(); } private IEnumerator RenderSprite(CustomPiece piece) { yield return null; VisualStack[] visualStacks = ((Component)piece.Piece).GetComponentsInChildren<VisualStack>(); VisualStack[] array = visualStacks; foreach (VisualStack visualStack in array) { visualStack.SetVisualsActive(55f); } piece.Piece.m_icon = RenderManager.Instance.Render(new RenderRequest(piece.PiecePrefab) { Width = 64, Height = 64, Rotation = RenderManager.IsometricRotation * Quaternion.Euler(0f, -90f, 0f), UseCache = true, TargetPlugin = ((BaseUnityPlugin)this).Info.Metadata }); VisualStack[] array2 = visualStacks; foreach (VisualStack visualStack2 in array2) { visualStack2.SetVisualsActive(100f); } } private PieceConfig StackConfig(string item, int amount) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown PieceConfig val = new PieceConfig(); val.PieceTable = PieceTables.Hammer; val.Category = PieceCategories.Misc; val.AddRequirement(new RequirementConfig(item, amount, 0, true)); return val; } public static bool IsStackPiece(string pieceName, out string allowedItem) { return allowedItemsByStack.TryGetValue(pieceName, out allowedItem); } } public static class InventoryHelper { public static string PrefabName(this ItemData item) { if (Object.op_Implicit((Object)(object)item.m_dropPrefab)) { return ((Object)item.m_dropPrefab).name; } Logger.LogWarning((object)("Item has missing prefab " + item.m_shared.m_name)); return item.m_shared.m_name; } } public static class PieceHelper { public static GameObject PreparePiecePrefab(GameObject prefab, GameObject basePrefab, string nameToken) { Object.Destroy((Object)(object)prefab.GetComponent<Gibber>()); Object.Destroy((Object)(object)prefab.GetComponent<Collider>()); if (Object.op_Implicit((Object)(object)prefab.transform.Find("collider"))) { Object.Destroy((Object)(object)((Component)prefab.transform.Find("collider")).gameObject); } ZNetView component = prefab.GetComponent<ZNetView>(); component.m_persistent = true; if (!Object.op_Implicit((Object)(object)prefab.GetComponent<Piece>())) { ExposedGameObjectExtension.AddComponentCopy<Piece>(prefab, basePrefab.GetComponent<Piece>()); } if (!Object.op_Implicit((Object)(object)prefab.GetComponent<WearNTear>())) { ExposedGameObjectExtension.AddComponentCopy<WearNTear>(prefab, basePrefab.GetComponent<WearNTear>()); } Container val = prefab.AddComponent<Container>(); val.m_name = nameToken; val.m_width = 5; val.m_height = 2; VisualStack visualStack = prefab.AddComponent<VisualStack>(); MeshRenderer[] componentsInChildren = prefab.GetComponentsInChildren<MeshRenderer>(); foreach (MeshRenderer val2 in componentsInChildren) { if (!Object.op_Implicit((Object)(object)((Component)val2).gameObject.GetComponent<Collider>())) { ((Component)val2).gameObject.AddComponent<BoxCollider>(); } visualStack.stackMeshes.Add(((Component)val2).transform); } return prefab; } public static GameObject FindDestroyVFX(GameObject prefab, string vfxName) { WearNTear val = default(WearNTear); if (prefab.TryGetComponent<WearNTear>(ref val)) { EffectData[] effectPrefabs = val.m_destroyedEffect.m_effectPrefabs; foreach (EffectData val2 in effectPrefabs) { if (Object.op_Implicit((Object)(object)val2.m_prefab) && ((Object)val2.m_prefab).name == vfxName) { return val2.m_prefab; } } } return null; } public static AssetBundle GetAssetBundle(string bundleName) { foreach (AssetBundle allLoadedAssetBundle in AssetBundle.GetAllLoadedAssetBundles()) { if (((Object)allLoadedAssetBundle).name == bundleName) { return allLoadedAssetBundle; } } return null; } } [HarmonyPatch] internal static class RestrictContainers { private static string _loadingContainer; private static string _targetContainer; private static string _allowedItem; [HarmonyPrefix] [HarmonyPatch(typeof(InventoryGrid), "DropItem")] private static bool DropItemPrefix(InventoryGrid __instance, Inventory fromInventory, ItemData item, Vector2i pos) { //IL_001f: 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) if (!CanAddItem(__instance.m_inventory, item)) { return false; } ItemData itemAt = __instance.m_inventory.GetItemAt(pos.x, pos.y); if (itemAt != null) { return CanAddItem(fromInventory, itemAt); } return true; } private static bool CanAddItem(Inventory inventory, ItemData item) { if (inventory == null || item == null) { return false; } if (inventory.m_name == _loadingContainer) { return true; } if (IsRestrictedContainer(inventory.m_name, out var allowedItem)) { bool flag = item.PrefabName() == allowedItem; if (!flag) { string text = item.m_shared.m_name + " cannot be placed in " + inventory.m_name; Player localPlayer = Player.m_localPlayer; if (localPlayer != null) { ((Character)localPlayer).Message((MessageType)2, text, 0, (Sprite)null, false); } } return flag; } return true; } public static bool IsRestrictedContainer(string containerName, out string allowedItem) { if (!ConfigSettings.restrictDynamicPiles.Value) { allowedItem = null; return false; } return DynamicStoragePiles.allowedItemsByContainer.TryGetValue(containerName, out allowedItem); } [HarmonyPrefix] [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData) })] [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData), typeof(int), typeof(int), typeof(int), typeof(bool) })] [HarmonyPriority(800)] private static bool AddItemPrefix(Inventory __instance, ItemData item, ref bool __result) { if (!CanAddItem(__instance, item)) { __result = false; return __result; } return true; } [HarmonyPrefix] [HarmonyPatch(typeof(Inventory), "MoveItemToThis", new Type[] { typeof(Inventory), typeof(ItemData) })] [HarmonyPatch(typeof(Inventory), "MoveItemToThis", new Type[] { typeof(Inventory), typeof(ItemData), typeof(int), typeof(int), typeof(int) })] [HarmonyPriority(800)] private static bool MoveItemToThisPrefix(Inventory __instance, Inventory fromInventory, ItemData item) { if (__instance == null || fromInventory == null || item == null) { return false; } return CanAddItem(__instance, item); } [HarmonyPrefix] [HarmonyPatch(typeof(Inventory), "MoveAll", new Type[] { typeof(Inventory) })] [HarmonyPriority(800)] private static void MoveAllPrefix(Inventory __instance, Inventory fromInventory) { if (__instance != null && fromInventory != null && IsRestrictedContainer(__instance.m_name, out var allowedItem)) { _targetContainer = __instance.m_name; _allowedItem = allowedItem; } } [HarmonyPrefix] [HarmonyPatch(typeof(Inventory), "MoveAll", new Type[] { typeof(Inventory) })] [HarmonyPriority(800)] private static void MoveAllPostfix() { _targetContainer = null; _allowedItem = null; } [HarmonyPrefix] [HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[] { typeof(ItemData) })] [HarmonyPatch(typeof(Inventory), "RemoveItem", new Type[] { typeof(ItemData), typeof(int) })] [HarmonyPriority(800)] private static bool RemoveItemPrefix(Inventory __instance, ItemData item) { return ShouldRemoveItem(__instance, item); } [HarmonyPrefix] [HarmonyPatch(typeof(Inventory), "RemoveOneItem", new Type[] { typeof(ItemData) })] [HarmonyPriority(800)] private static bool RemoveOneItemPrefix(Inventory __instance, ItemData item) { return ShouldRemoveItem(__instance, item); } private static bool ShouldRemoveItem(Inventory __instance, ItemData item) { if (__instance == null || item == null) { return false; } bool flag = !string.IsNullOrEmpty(_targetContainer); bool flag2 = !string.IsNullOrEmpty(_allowedItem); if (flag && flag2) { return item.PrefabName() != _allowedItem; } return true; } [HarmonyPrefix] [HarmonyPatch(typeof(Inventory), "Load", new Type[] { typeof(ZPackage) })] [HarmonyPatch(typeof(Inventory), "Load", new Type[] { typeof(ZPackage), typeof(bool) })] private static void LoadPrefix(Inventory __instance) { if (__instance != null) { _loadingContainer = __instance.m_name; } } [HarmonyPostfix] [HarmonyPatch(typeof(Inventory), "Load", new Type[] { typeof(ZPackage) })] [HarmonyPatch(typeof(Inventory), "Load", new Type[] { typeof(ZPackage), typeof(bool) })] private static void LoadPostfix() { _loadingContainer = null; } } public class VisualStack : MonoBehaviour { public List<Transform> stackMeshes = new List<Transform>(); private Container container; private Inventory inventory; private void Start() { container = ((Component)this).GetComponentInParent<Container>(); if (Object.op_Implicit((Object)(object)container)) { inventory = container.GetInventory(); } if (inventory != null) { Inventory obj = inventory; obj.m_onChanged = (Action)Delegate.Combine(obj.m_onChanged, new Action(UpdateVisuals)); UpdateVisuals(); } } private void UpdateVisuals() { SetVisualsActive(inventory.SlotsUsedPercentage()); } public void SetVisualsActive(float fillPercentage) { float num = Mathf.Ceil(fillPercentage / 100f * (float)stackMeshes.Count); for (int i = 0; i < stackMeshes.Count; i++) { bool active = i == 0 || (float)i < num; ((Component)stackMeshes[i]).gameObject.SetActive(active); } } } } namespace DynamicStoragePiles.Patches { [HarmonyPatch] public class PlacementPatch { [HarmonyPatch(typeof(Player), "SetupPlacementGhost")] [HarmonyPostfix] public static void SetupPlacementGhostPatch(Player __instance) { if (Object.op_Implicit((Object)(object)__instance.m_placementGhost)) { VisualStack[] componentsInChildren = __instance.m_placementGhost.GetComponentsInChildren<VisualStack>(); foreach (VisualStack visualStack in componentsInChildren) { Object.Destroy((Object)(object)visualStack); } } } } } namespace DynamicStoragePiles.Compatibility { public static class AzuAutoStore { private static class AzuAutoStore_After_2_0_0 { [HarmonyPatch("AzuAutoStore.Util.Boxes, AzuAutoStore", "CanItemBeStored")] [HarmonyPostfix] private static void CanItemBeStoredPatch(string container, string prefab, ref bool __result) { if (__result && ConfigSettings.azuAutoStoreItemWhitelist.Value && DynamicStoragePiles.IsStackPiece(container, out var allowedItem) && prefab != allowedItem) { __result = false; } } } private static class AzuAutoStore_Before_2_0_0 { [HarmonyPatch("AzuAutoStore.Util.Functions, AzuAutoStore", "CheckDisallowedItems")] [HarmonyPostfix] private static void CheckDisallowedItemsPatch(Container container, ItemData item, ref bool __result) { if (!__result && ConfigSettings.azuAutoStoreItemWhitelist.Value && Object.op_Implicit((Object)(object)container) && item != null && Object.op_Implicit((Object)(object)item.m_dropPrefab)) { string prefabName = Utils.GetPrefabName(((Object)container).name); if (DynamicStoragePiles.IsStackPiece(prefabName, out var allowedItem) && ((Object)item.m_dropPrefab).name != allowedItem) { __result = true; } } } } public static void Init() { PluginInfo val = Chainloader.PluginInfos["Azumatt.AzuAutoStore"]; if (val.Metadata.Version >= new Version(2, 0, 0)) { DynamicStoragePiles.harmony.PatchAll(typeof(AzuAutoStore_After_2_0_0)); } else { DynamicStoragePiles.harmony.PatchAll(typeof(AzuAutoStore_Before_2_0_0)); } } } public static class IngotStacks { private static AssetBundle assetBundle; public static List<string> ingotStacks = new List<string>(); public static List<string> dynamicIngotStacks = new List<string>(); public static void Init() { assetBundle = PieceHelper.GetAssetBundle("stackedingots"); ConvertToPiece("ingot_copper_stack", "vfx_copper_stack_destroyed", "MS_IngotStacks_Copper", "Copper"); ConvertToPiece("ingot_tin_stack", "vfx_tin_stack_destroyed", "MS_IngotStacks_Tin", "Tin"); ConvertToPiece("ingot_bronze_stack", "vfx_bronze_stack_destroyed", "MS_IngotStacks_Bronze", "Bronze"); ConvertToPiece("ingot_iron_stack", "vfx_iron_stack_destroyed", "MS_IngotStacks_Iron", "Iron"); ConvertToPiece("ingot_silver_stack", "vfx_silver_stack_destroyed", "MS_IngotStacks_Silver", "Silver"); ConvertToPiece("ingot_blackmetal_stack", "vfx_blackmetal_stack_destroyed", "MS_IngotStacks_Blackmetal", "BlackMetal"); ConvertToPiece("ingot_flametal_stack", "vfx_flametal_stack_destroyed", "MS_IngotStacks_FlametalNew", "FlametalNew"); } public static void ConvertToPiece(string baseAssetName, string vfxName, string newPrefabName, string resource) { ingotStacks.Add(baseAssetName); dynamicIngotStacks.Add(newPrefabName); GameObject val = assetBundle.LoadAsset<GameObject>(baseAssetName); GameObject val2 = PieceHelper.FindDestroyVFX(val, vfxName); GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(newPrefabName, val2); prefab = PieceHelper.PreparePiecePrefab(prefab, val, "$" + baseAssetName); ((Object)prefab).name = newPrefabName; DynamicStoragePiles.Instance.AddCompatPiece(prefab, resource, 3); } } public static class MoreStacks { public static List<string> staticStacks = new List<string>(); public static List<string> dynamicStacks = new List<string>(); private static BaseUnityPlugin moreStacksInstance = null; private static Dictionary<string, string> vanillaNameToDynamicStorageNameMap = new Dictionary<string, string> { { "wood_fine_stack", "finewood_stack" }, { "wood_core_stack", "corewood_stack" }, { "wood_yggdrasil_stack", "yggdrasil_wood_stack" }, { "treasure_stack", "coin_pile" } }; public static void Init() { if (!Object.op_Implicit((Object)(object)moreStacksInstance) && Chainloader.PluginInfos.TryGetValue("ujhik.MoreStacks", out var value)) { moreStacksInstance = value.Instance; if (!Object.op_Implicit((Object)(object)moreStacksInstance)) { Logger.LogWarning((object)"Failed to cast mod instance for 'ujhik.MoreStacks'."); return; } } FieldInfo field = ((object)moreStacksInstance).GetType().GetField("stackInfoList", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { object value2 = field.GetValue(moreStacksInstance); if (!(value2 is IEnumerable enumerable)) { return; } { foreach (object item in enumerable) { Type type = item.GetType(); PropertyInfo property = type.GetProperty("idStackToDuplicate"); PropertyInfo property2 = type.GetProperty("idStackMaterial"); string stackToCloneId = property?.GetValue(item) as string; string materialPrefabId = property2?.GetValue(item) as string; ConvertToPiece(stackToCloneId, materialPrefabId); } return; } } Logger.LogWarning((object)"ujhik.MoreStacks: Failed to retrieve stackInfoList field via reflection, dynamic piles could not be generated"); } public static void ConvertToPiece(string stackToCloneId, string materialPrefabId) { //IL_00e3: Unknown result type (might be due to invalid IL or missing references) if (vanillaNameToDynamicStorageNameMap.TryGetValue(stackToCloneId, out var value)) { stackToCloneId = value; } string text = (string)((object)moreStacksInstance).GetType().GetMethod("getStackName", BindingFlags.Static | BindingFlags.Public)?.Invoke(moreStacksInstance, new object[1] { materialPrefabId }); string text2 = "MS_container_MoreStacks"; string text3 = text2 + "_" + materialPrefabId + "_pile"; string text4 = "MS_container_" + stackToCloneId; staticStacks.Add(text); dynamicStacks.Add(text3); GameObject prefab = PrefabManager.Instance.GetPrefab(text4); GameObject prefab2 = PrefabManager.Instance.GetPrefab(text); GameObject prefab3 = PrefabManager.Instance.GetPrefab(materialPrefabId); GameObject val = PrefabManager.Instance.CreateClonedPrefab(text3, prefab); Object.DestroyImmediate((Object)(object)val.GetComponent<Container>()); val.transform.localScale = prefab2.transform.localScale; string name = prefab2.GetComponent<Piece>().m_name; val = PieceHelper.PreparePiecePrefab(val, prefab, name); val.GetComponent<Piece>().m_name = name; Material sharedMaterial = ((Renderer)prefab2.GetComponentInChildren<MeshRenderer>()).sharedMaterial; MeshRenderer[] componentsInChildren = val.GetComponentsInChildren<MeshRenderer>(); foreach (MeshRenderer val2 in componentsInChildren) { ((Renderer)val2).sharedMaterial = sharedMaterial; } DynamicStoragePiles.Instance.AddCompatPiece(val, materialPrefabId, GetMaterialCostForPiece(materialPrefabId), addGraphics: true); } public static int GetMaterialCostForPiece(string materialPrefabId) { if (materialPrefabId.Contains("Ore") || materialPrefabId.Contains("Scrap")) { return 3; } return 10; } } public static class RefinedStonePieces { private static AssetBundle assetBundle; public static List<string> staticStacks = new List<string>(); public static List<string> dynamicStacks = new List<string>(); public static void Init() { assetBundle = PieceHelper.GetAssetBundle("refinedstonepieces"); ConvertRefinedStoneStackToPiece("BRP_RefinedStone_Stack", "MS_RefinedStonePieces_RefinedStone_Stack", "BRP_RefinedStone"); } public static void ConvertRefinedStoneStackToPiece(string baseAssetName, string newPrefabName, string resource) { staticStacks.Add(baseAssetName); dynamicStacks.Add(newPrefabName); GameObject val = assetBundle.LoadAsset<GameObject>(baseAssetName); GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(newPrefabName, val); prefab = PieceHelper.PreparePiecePrefab(prefab, val, "$brp_refinedstone_stack"); ((Object)prefab).name = newPrefabName; List<Transform> source = prefab.GetComponent<VisualStack>().stackMeshes.OrderBy((Transform t) => t.position.y).ToList(); IOrderedEnumerable<Transform> first = from t in source.Skip(0).Take(6) orderby t.position.z select t; IOrderedEnumerable<Transform> second = from t in source.Skip(6).Take(6) orderby t.position.x select t; IOrderedEnumerable<Transform> second2 = from t in source.Skip(12).Take(6) orderby t.position.z select t; prefab.GetComponent<VisualStack>().stackMeshes = first.Concat(second).Concat(second2).ToList(); DynamicStoragePiles.Instance.AddCompatPiece(prefab, resource, 10, addGraphics: true); } } public static class StackedBars { private static AssetBundle assetBundle; public static List<string> stackedBars = new List<string>(); public static List<string> dynamicStackedBars = new List<string>(); public static void Init() { assetBundle = PieceHelper.GetAssetBundle("stackedbars"); ConvertToPiece("stack_tinbars", "MS_StackedBars_Tin", "Tin"); ConvertToPiece("stack_copperbars", "MS_StackedBars_Copper", "Copper"); ConvertToPiece("stack_bronzebars", "MS_StackedBars_Bronze", "Bronze"); ConvertToPiece("stack_ironbars", "MS_StackedBars_Iron", "Iron"); ConvertToPiece("stack_silverbars", "MS_StackedBars_Silver", "Silver"); ConvertToPiece("stack_blackmetalbars", "MS_StackedBars_BlackMetal", "BlackMetal"); ConvertToPiece("stack_flametalbars", "MS_StackedBars_FlameMetalNew", "FlametalNew"); } public static void ConvertToPiece(string baseAssetName, string newPrefabName, string resource) { stackedBars.Add(baseAssetName); dynamicStackedBars.Add(newPrefabName); GameObject val = assetBundle.LoadAsset<GameObject>(baseAssetName); GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(newPrefabName, val); prefab = PieceHelper.PreparePiecePrefab(prefab, val, "$piece_" + baseAssetName); ((Object)prefab).name = newPrefabName; DynamicStoragePiles.Instance.AddCompatPiece(prefab, resource, 3); } } }
plugins/DynamicStoragePiles/DynamicStoragePiles.ExtraPiles.dll
Decompiled 5 hours agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using BepInEx; using DynamicStoragePiles; using Jotunn.Managers; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("DynamicStoragePiles.ExtraPiles")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("DynamicStoragePiles.ExtraPiles")] [assembly: AssemblyTitle("DynamicStoragePiles.ExtraPiles")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ExtraPiles { [BepInPlugin("hbk.DynamicStoragePiles.ExtraPiles", "DynamicStoragePiles ExtraPiles", "1.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class ExtraPilesPlugin : BaseUnityPlugin { private enum Kind { Bars, Mound, Planks } private struct Placement { public Vector3 Pos; public Quaternion Rot; } private class Part { public Mesh Mesh; public Material[] Materials; public Vector3 Pos; public Quaternion Rot; public Vector3 Scale; public string Name; } private const string BasePile = "MS_container_stone_pile"; private static readonly string[] Bars = new string[7] { "Copper", "Tin", "Bronze", "Iron", "Silver", "BlackMetal", "FlametalNew" }; private static readonly string[] Chunks = new string[3] { "Flint", "Obsidian", "Crystal" }; private const string Bark = "ElderBark"; private static readonly Dictionary<string, string> s_ourPiles = new Dictionary<string, string>(); private static readonly Dictionary<string, string> s_dspToVanilla = new Dictionary<string, string> { { "MS_container_wood_stack", "wood_stack" }, { "MS_container_finewood_stack", "wood_fine_stack" }, { "MS_container_corewood_stack", "wood_core_stack" }, { "MS_container_yggdrasil_wood_stack", "wood_yggdrasil_stack" }, { "MS_container_blackwood_stack", "blackwood_stack" }, { "MS_container_stone_pile", "stone_pile" }, { "MS_container_coal_pile", "coal_pile" }, { "MS_container_blackmarble_pile", "blackmarble_pile" }, { "MS_container_grausten_pile", "grausten_pile" }, { "MS_container_skull_pile", "skull_pile" }, { "MS_container_bone_stack", "bone_stack" }, { "MS_container_coin_pile", "treasure_stack" } }; private static ExtraPilesPlugin s_instance; private static bool s_done; private static Vector3 s_hollowLocal; private static Vector3 s_hollowUnit; private static readonly Dictionary<string, Sprite> s_vanillaStackIcon = new Dictionary<string, Sprite>(); private static Mesh SplitInnerOuter(Mesh src) { //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) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_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) //IL_004e: 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_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: 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_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: 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_015b: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: 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_01c1: 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_034f: Unknown result type (might be due to invalid IL or missing references) //IL_0356: Expected O, but got Unknown //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_025c: 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_0274: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_0283: 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_028c: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a4: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_0236: Unknown result type (might be due to invalid IL or missing references) //IL_023b: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Unknown result type (might be due to invalid IL or missing references) //IL_02c6: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)src) || !src.isReadable) { Debug.LogWarning((object)"[ExtraPiles] Uralte Rinde: model is not readable, cannot split inside/outside - using green tint"); return null; } Vector3[] vertices = src.vertices; Vector3[] normals = src.normals; if (vertices == null || vertices.Length == 0) { return null; } Bounds bounds = src.bounds; Vector3 center = ((Bounds)(ref bounds)).center; Vector3 size = ((Bounds)(ref bounds)).size; int num = 0; if (size.y < Get(size, num)) { num = 1; } if (size.z < Get(size, num)) { num = 2; } int i = (num + 1) % 3; int i2 = (num + 2) % 3; double num2 = 0.0; double[] array = new double[vertices.Length]; for (int j = 0; j < vertices.Length; j++) { float num3 = (Get(vertices[j], i) - Get(center, i)) / Math.Max(Get(size, i), 1E-05f); float num4 = (Get(vertices[j], i2) - Get(center, i2)) / Math.Max(Get(size, i2), 1E-05f); array[j] = Math.Sqrt(num3 * num3 + num4 * num4); num2 += array[j]; } num2 /= (double)vertices.Length; double num5 = 0.0; for (int k = 0; k < vertices.Length; k++) { num5 += (double)(Get(vertices[k], num) - Get(center, num)) * (array[k] - num2); } float num6 = ((num5 >= 0.0) ? 1f : (-1f)); s_hollowLocal = (Vector3)(num switch { 1 => new Vector3(0f, num6, 0f), 0 => new Vector3(num6, 0f, 0f), _ => new Vector3(0f, 0f, num6), }); List<int> list = new List<int>(); List<int> list2 = new List<int>(); for (int l = 0; l < src.subMeshCount; l++) { int[] triangles = src.GetTriangles(l); for (int m = 0; m + 2 < triangles.Length; m += 3) { Vector3 val = ((normals == null || normals.Length != vertices.Length) ? Vector3.Cross(vertices[triangles[m + 1]] - vertices[triangles[m]], vertices[triangles[m + 2]] - vertices[triangles[m]]) : (normals[triangles[m]] + normals[triangles[m + 1]] + normals[triangles[m + 2]])); float num7 = (float)Math.Sqrt(val.x * val.x + val.y * val.y + val.z * val.z); List<int> obj = ((num7 > 0f && Get(val, num) / num7 * num6 > 0.35f) ? list2 : list); obj.Add(triangles[m]); obj.Add(triangles[m + 1]); obj.Add(triangles[m + 2]); } } if (list2.Count == 0 || list.Count == 0) { Debug.LogWarning((object)"[ExtraPiles] Uralte Rinde: could not find inside/outside faces - using green tint"); return null; } Mesh val2 = new Mesh(); ((Object)val2).name = ((Object)src).name + "_mossy"; val2.vertices = vertices; if (normals != null && normals.Length == vertices.Length) { val2.normals = normals; } Vector2[] uv = src.uv; if (uv != null && uv.Length == vertices.Length) { val2.uv = uv; } Vector2[] uv2 = src.uv2; if (uv2 != null && uv2.Length == vertices.Length) { val2.uv2 = uv2; } Vector4[] tangents = src.tangents; if (tangents != null && tangents.Length == vertices.Length) { val2.tangents = tangents; } Color[] colors = src.colors; if (colors != null && colors.Length == vertices.Length) { val2.colors = colors; } val2.subMeshCount = 2; val2.SetTriangles(list.ToArray(), 0); val2.SetTriangles(list2.ToArray(), 1); val2.RecalculateBounds(); Debug.Log((object)("[ExtraPiles] Uralte Rinde: split model into " + list.Count / 3 + " outside and " + list2.Count / 3 + " inside faces")); return val2; } private static float Get(Vector3 v, int i) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) return i switch { 1 => v.y, 0 => v.x, _ => v.z, }; } private static Material MossyBark(Material[] original) { //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_018c: 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_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Expected O, but got Unknown string[] array = new string[3] { "SwampTree1_log", "SwampTree1_Stub", "swamptree1_log" }; foreach (string text in array) { GameObject prefab = PrefabManager.Instance.GetPrefab(text); if (!Object.op_Implicit((Object)(object)prefab)) { continue; } MeshRenderer[] componentsInChildren = prefab.GetComponentsInChildren<MeshRenderer>(true); foreach (MeshRenderer val in componentsInChildren) { if (((Renderer)val).sharedMaterials == null) { continue; } Material[] sharedMaterials = ((Renderer)val).sharedMaterials; foreach (Material val2 in sharedMaterials) { if (Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val2.shader)) { Debug.Log((object)("[ExtraPiles] candidate bark material from " + text + ": " + ((Object)val2).name + " | " + ((Object)val2.shader).name + " | " + (Object.op_Implicit((Object)(object)val2.mainTexture) ? ((Object)val2.mainTexture).name : "-"))); if (((Object)val2.shader).name == "Custom/Piece") { Debug.Log((object)("[ExtraPiles] Uralte Rinde uses material " + ((Object)val2).name + " from " + text)); return val2; } } } } } if (original == null || original.Length == 0 || !Object.op_Implicit((Object)(object)original[0])) { return null; } Material val3 = new Material(original[0]) { name = ((Object)original[0]).name + "_mossy", color = new Color { r = 0.4f, g = 0.62f, b = 0.25f, a = 1f } }; Debug.Log((object)"[ExtraPiles] Uralte Rinde: no swamp tree material found, using mossy tint"); return val3; } private static void Dump(Transform t, int depth) { //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: 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) StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("[ExtraPiles][dump] ").Append(new string(' ', depth * 2)).Append(((Object)((Component)t).gameObject).name) .Append(((Component)t).gameObject.activeSelf ? "" : " (inactive)") .Append(" :"); Component[] components = ((Component)t).gameObject.GetComponents<Component>(); foreach (Component val in components) { if (Object.op_Implicit((Object)(object)val)) { stringBuilder.Append(' ').Append(((object)val).GetType().Name); } } Debug.Log((object)stringBuilder.ToString()); Renderer[] components2 = ((Component)t).gameObject.GetComponents<Renderer>(); foreach (Renderer val2 in components2) { if (!Object.op_Implicit((Object)(object)val2) || val2.sharedMaterials == null) { continue; } Material[] sharedMaterials = val2.sharedMaterials; foreach (Material val3 in sharedMaterials) { if (!Object.op_Implicit((Object)(object)val3)) { Debug.Log((object)("[ExtraPiles][dump] " + new string(' ', depth * 2 + 2) + "material: <none>")); continue; } Debug.Log((object)("[ExtraPiles][dump] " + new string(' ', depth * 2 + 2) + "material: " + ((Object)val3).name + " | shader: " + (Object.op_Implicit((Object)(object)val3.shader) ? ((Object)val3.shader).name : "?") + " | tex: " + (Object.op_Implicit((Object)(object)val3.mainTexture) ? ((Object)val3.mainTexture).name : "-") + " | color: " + val3.color.r.ToString("0.00") + "," + val3.color.g.ToString("0.00") + "," + val3.color.b.ToString("0.00") + " | keywords: " + ((val3.shaderKeywords != null) ? string.Join(" ", val3.shaderKeywords) : "") + " | enabled: " + val2.enabled)); } } for (int k = 0; k < t.childCount; k++) { Dump(t.GetChild(k), depth + 1); } } private static bool IsLowerLod(string n) { int num = n.IndexOf("LOD", StringComparison.OrdinalIgnoreCase); if (num >= 0 && num + 3 < n.Length && char.IsDigit(n[num + 3])) { return n[num + 3] != '0'; } return false; } private void Awake() { s_instance = this; PrefabManager.OnVanillaPrefabsAvailable += Build; PieceManager.OnPiecesRegistered += OnPiecesRegistered; PrefabManager.OnPrefabsRegistered += OnPiecesRegistered; } private static void Build() { if (s_done) { return; } s_done = true; Type? type = Type.GetType("DynamicStoragePiles.DynamicStoragePiles, DynamicStoragePiles"); object obj = type?.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null); MethodInfo methodInfo = type?.GetMethod("AddCompatPiece", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[4] { typeof(GameObject), typeof(string), typeof(int), typeof(bool) }, null); if (obj == null || methodInfo == null) { Debug.LogWarning((object)"[ExtraPiles] DynamicStoragePiles not found, no extra piles created"); return; } int num = 0; string[] bars = Bars; foreach (string id in bars) { num += (Make(id, Kind.Bars, 3, "-Stapel", obj, methodInfo) ? 1 : 0); } bars = Chunks; foreach (string id2 in bars) { num += (Make(id2, Kind.Mound, 10, "-Haufen", obj, methodInfo) ? 1 : 0); } Debug.Log((object)("[ExtraPiles] created " + (num + (Make("ElderBark", Kind.Planks, 10, "-Stoß", obj, methodInfo) ? 1 : 0)) + " dynamic piles")); } private static bool Make(string id, Kind kind, int cost, string suffix, object instance, MethodInfo add) { //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_0061: Unknown result type (might be due to invalid IL or missing references) //IL_037e: Unknown result type (might be due to invalid IL or missing references) //IL_0380: Unknown result type (might be due to invalid IL or missing references) //IL_0382: 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_0391: Unknown result type (might be due to invalid IL or missing references) //IL_0393: Unknown result type (might be due to invalid IL or missing references) //IL_0395: 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_03a1: Unknown result type (might be due to invalid IL or missing references) //IL_03a6: Unknown result type (might be due to invalid IL or missing references) //IL_03c6: Unknown result type (might be due to invalid IL or missing references) //IL_03c8: Unknown result type (might be due to invalid IL or missing references) //IL_03bb: Unknown result type (might be due to invalid IL or missing references) //IL_03bd: Unknown result type (might be due to invalid IL or missing references) //IL_03af: 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_0128: 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_0132: 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_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_015e: 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_0168: Unknown result type (might be due to invalid IL or missing references) //IL_018b: 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_019e: 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_01a7: 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_01b8: 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_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: 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_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: 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_0205: Unknown result type (might be due to invalid IL or missing references) //IL_0207: Unknown result type (might be due to invalid IL or missing references) //IL_0209: 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_0304: 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_0310: Unknown result type (might be due to invalid IL or missing references) //IL_0315: 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_031f: Unknown result type (might be due to invalid IL or missing references) //IL_0530: Unknown result type (might be due to invalid IL or missing references) //IL_0537: Expected O, but got Unknown //IL_055f: Unknown result type (might be due to invalid IL or missing references) //IL_0579: Unknown result type (might be due to invalid IL or missing references) //IL_05a0: 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_05ad: Unknown result type (might be due to invalid IL or missing references) //IL_05c0: Unknown result type (might be due to invalid IL or missing references) //IL_05c8: Unknown result type (might be due to invalid IL or missing references) //IL_05d2: Unknown result type (might be due to invalid IL or missing references) //IL_05da: Unknown result type (might be due to invalid IL or missing references) //IL_05e4: Unknown result type (might be due to invalid IL or missing references) //IL_05ec: Unknown result type (might be due to invalid IL or missing references) //IL_05f6: Unknown result type (might be due to invalid IL or missing references) //IL_0608: Unknown result type (might be due to invalid IL or missing references) //IL_0627: Unknown result type (might be due to invalid IL or missing references) //IL_062c: Unknown result type (might be due to invalid IL or missing references) //IL_0630: Unknown result type (might be due to invalid IL or missing references) //IL_0641: Unknown result type (might be due to invalid IL or missing references) //IL_0646: 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) try { GameObject prefab = PrefabManager.Instance.GetPrefab("MS_container_stone_pile"); GameObject prefab2 = PrefabManager.Instance.GetPrefab(id); if (!Object.op_Implicit((Object)(object)prefab) || !Object.op_Implicit((Object)(object)prefab2)) { Debug.LogWarning((object)("[ExtraPiles] skipped " + id + ": prefab not found")); return false; } List<Part> list = new List<Part>(); Transform transform = prefab2.transform; Quaternion val = Quaternion.Inverse(transform.rotation); Vector3 val2 = default(Vector3); ((Vector3)(ref val2))..ctor(float.MaxValue, float.MaxValue, float.MaxValue); Vector3 val3 = default(Vector3); ((Vector3)(ref val3))..ctor(float.MinValue, float.MinValue, float.MinValue); MeshFilter[] componentsInChildren = prefab2.GetComponentsInChildren<MeshFilter>(true); Bounds bounds; foreach (MeshFilter val4 in componentsInChildren) { MeshRenderer component = ((Component)val4).GetComponent<MeshRenderer>(); if (Object.op_Implicit((Object)(object)val4.sharedMesh) && Object.op_Implicit((Object)(object)component) && ((Renderer)component).enabled && ((Component)val4).gameObject.activeSelf && !IsLowerLod(((Object)((Component)val4).gameObject).name)) { Part part = new Part { Mesh = val4.sharedMesh, Materials = ((Renderer)component).sharedMaterials, Pos = transform.InverseTransformPoint(((Component)val4).transform.position), Rot = val * ((Component)val4).transform.rotation, Scale = Div(((Component)val4).transform.lossyScale, transform.lossyScale), Name = ((Object)((Component)val4).gameObject).name }; list.Add(part); Vector3 pos = part.Pos; Quaternion rot = part.Rot; bounds = part.Mesh.bounds; Vector3 val5 = pos + rot * Vector3.Scale(((Bounds)(ref bounds)).center, part.Scale); Quaternion rot2 = part.Rot; bounds = part.Mesh.bounds; Vector3 val6 = RotatedExtents(rot2, Vector3.Scale(((Bounds)(ref bounds)).extents, part.Scale)); val2 = Vector3.Min(val2, val5 - val6); val3 = Vector3.Max(val3, val5 + val6); } } if (list.Count == 0) { Debug.LogWarning((object)("[ExtraPiles] skipped " + id + ": no model")); return false; } if (id == "ElderBark") { Material val7 = ((list[0].Materials != null && list[0].Materials.Length != 0) ? list[0].Materials[0] : null); Material val8 = MossyBark(list[0].Materials); foreach (Part item in list) { Mesh val9 = ((Object.op_Implicit((Object)(object)val7) && Object.op_Implicit((Object)(object)val8)) ? SplitInnerOuter(item.Mesh) : null); if (Object.op_Implicit((Object)(object)val9)) { item.Mesh = val9; item.Materials = (Material[])(object)new Material[2] { val7, val8 }; s_hollowUnit = item.Rot * Vector3.Scale(s_hollowLocal, item.Scale); } else if (Object.op_Implicit((Object)(object)val8)) { Material[] array = (Material[])(object)new Material[item.Materials.Length]; for (int j = 0; j < array.Length; j++) { array[j] = val8; } item.Materials = array; } } } Vector3 centre = (val2 + val3) * 0.5f; Vector3 ext = (val3 - val2) * 0.5f; List<Placement> list2 = kind switch { Kind.Planks => PlankLayout(ext, centre), Kind.Bars => BarLayout(ext, centre), _ => MoundLayout(ext, centre, id), }; ItemDrop component2 = prefab2.GetComponent<ItemDrop>(); string name = (Object.op_Implicit((Object)(object)component2) ? component2.m_itemData.m_shared.m_name : id) + suffix; Sprite val10 = ((Object.op_Implicit((Object)(object)component2) && component2.m_itemData.m_shared.m_icons != null && component2.m_itemData.m_shared.m_icons.Length != 0) ? component2.m_itemData.m_shared.m_icons[0] : null); GameObject val11 = PrefabManager.Instance.CreateClonedPrefab("MS_container_" + id + "_pile", prefab); val11.GetComponent<Piece>().m_name = name; if (Object.op_Implicit((Object)(object)val10)) { val11.GetComponent<Piece>().m_icon = val10; } val11.GetComponent<Container>().m_name = name; VisualStack[] componentsInChildren2 = val11.GetComponentsInChildren<VisualStack>(true); foreach (VisualStack val12 in componentsInChildren2) { Transform transform2 = ((Component)val12).transform; int layer = ((transform2.childCount > 0) ? ((Component)transform2.GetChild(0)).gameObject.layer : val11.layer); for (int num = transform2.childCount - 1; num >= 0; num--) { Object.DestroyImmediate((Object)(object)((Component)transform2.GetChild(num)).gameObject); } List<Transform> list3 = new List<Transform>(); for (int k = 0; k < list2.Count; k++) { GameObject val13 = new GameObject(id + "_" + k.ToString("00")); val13.layer = layer; val13.transform.SetParent(transform2, false); val13.transform.localPosition = list2[k].Pos; val13.transform.localRotation = list2[k].Rot; foreach (Part item2 in list) { GameObject val14 = new GameObject(item2.Name) { layer = layer }; val14.transform.SetParent(val13.transform, false); val14.transform.localPosition = item2.Pos; val14.transform.localRotation = item2.Rot; val14.transform.localScale = item2.Scale; val14.AddComponent<MeshFilter>().sharedMesh = item2.Mesh; ((Renderer)val14.AddComponent<MeshRenderer>()).sharedMaterials = item2.Materials; BoxCollider obj = val14.AddComponent<BoxCollider>(); bounds = item2.Mesh.bounds; obj.center = ((Bounds)(ref bounds)).center; bounds = item2.Mesh.bounds; obj.size = ((Bounds)(ref bounds)).size; } list3.Add(val13.transform); } val12.stackMeshes = list3; } add.Invoke(instance, new object[4] { val11, id, cost, false }); s_ourPiles["MS_container_" + id + "_pile"] = id; Debug.Log((object)("[ExtraPiles] created pile for " + id + " (" + list2.Count + " pieces, model parts: " + string.Join(", ", list.ConvertAll((Part p) => p.Name)) + ")")); return true; } catch (Exception ex) { Debug.LogWarning((object)("[ExtraPiles] failed to create pile for " + id + ": " + ex)); return false; } } private static void OnPiecesRegistered() { HideVanillaStacks(); if (Object.op_Implicit((Object)(object)s_instance)) { ((MonoBehaviour)s_instance).StartCoroutine(FixIconsLater()); } } private static void HideVanillaStacks() { if (!Object.op_Implicit((Object)(object)ZNetScene.instance)) { return; } HashSet<string> hashSet = new HashSet<string>(s_ourPiles.Values); foreach (GameObject prefab in ZNetScene.instance.m_prefabs) { if (!Object.op_Implicit((Object)(object)prefab) || s_ourPiles.ContainsKey(((Object)prefab).name) || ((Object)prefab).name.StartsWith("MS_")) { continue; } Piece component = prefab.GetComponent<Piece>(); if (!Object.op_Implicit((Object)(object)component) || component.m_resources == null || component.m_resources.Length != 1) { continue; } Requirement val = component.m_resources[0]; if (val == null || !Object.op_Implicit((Object)(object)val.m_resItem) || val.m_amount < 20) { continue; } string name = ((Object)((Component)val.m_resItem).gameObject).name; if (hashSet.Contains(name)) { if (Object.op_Implicit((Object)(object)component.m_icon) && !s_vanillaStackIcon.ContainsKey(name)) { s_vanillaStackIcon[name] = component.m_icon; } if (component.m_enabled) { component.m_enabled = false; Debug.Log((object)("[ExtraPiles] hid vanilla stack " + ((Object)prefab).name + " (" + val.m_amount + "x " + name + ")")); } } } } private static IEnumerator FixIconsLater() { for (int i = 0; i < 5; i++) { yield return null; } if (!Object.op_Implicit((Object)(object)ZNetScene.instance)) { yield break; } foreach (KeyValuePair<string, string> item in s_dspToVanilla) { GameObject prefab = ZNetScene.instance.GetPrefab(item.Key); GameObject prefab2 = ZNetScene.instance.GetPrefab(item.Value); Piece val = (Object.op_Implicit((Object)(object)prefab) ? prefab.GetComponent<Piece>() : null); Piece val2 = (Object.op_Implicit((Object)(object)prefab2) ? prefab2.GetComponent<Piece>() : null); if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val2.m_icon)) { val.m_icon = val2.m_icon; } } foreach (KeyValuePair<string, string> s_ourPile in s_ourPiles) { GameObject prefab3 = ZNetScene.instance.GetPrefab(s_ourPile.Key); Piece val3 = (Object.op_Implicit((Object)(object)prefab3) ? prefab3.GetComponent<Piece>() : null); if (Object.op_Implicit((Object)(object)val3) && s_vanillaStackIcon.TryGetValue(s_ourPile.Value, out var value) && Object.op_Implicit((Object)(object)value)) { val3.m_icon = value; } } if (Object.op_Implicit((Object)(object)Player.m_localPlayer)) { typeof(Player).GetMethod("UpdateAvailablePiecesList", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.Invoke(Player.m_localPlayer, null); } } private static List<Placement> PlankLayout(Vector3 ext, Vector3 centre) { //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_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) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //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_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) float length; float width; float height; Quaternion val = Align(ext, out length, out width, out height); if ((val * s_hollowUnit).y < 0f) { val = Quaternion.Euler(180f, 0f, 0f) * val; } List<Placement> list = new List<Placement>(); for (int i = 0; i < 6; i++) { float num = (float)i * (height + 0.01f) + height * 0.5f; for (int j = 0; j < 3; j++) { float num2 = (float)(j - 1) * (width + 0.01f) + ((i % 2 == 0) ? 0f : ((width + 0.01f) * 0.15f)); list.Add(new Placement { Pos = new Vector3(0f, num, num2) - val * centre, Rot = val }); } } return list; } private static Quaternion Align(Vector3 ext, out float length, out float width, out float height) { //IL_0008: 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_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0045: 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_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) Vector3[] array = (Vector3[])(object)new Vector3[3] { Vector3.right, Vector3.up, Vector3.forward }; float[] array2 = new float[3] { ext.x, ext.y, ext.z }; int num = 0; int num2 = 0; for (int i = 1; i < 3; i++) { if (array2[i] > array2[num]) { num = i; } if (array2[i] < array2[num2]) { num2 = i; } } if (num == num2) { num2 = (num + 1) % 3; } int num3 = 3 - num - num2; length = array2[num] * 2f; width = array2[num3] * 2f; height = array2[num2] * 2f; return Quaternion.Inverse(Quaternion.LookRotation(array[num3], array[num2])); } private static List<Placement> BarLayout(Vector3 ext, Vector3 centre) { //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_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0031: 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_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_009e: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: 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_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) float length; float width; float height; Quaternion val = Align(ext, out length, out width, out height); List<Placement> list = new List<Placement>(); for (int i = 0; i < 8; i++) { Quaternion val2 = ((i % 2 == 0) ? Quaternion.identity : Quaternion.Euler(0f, 90f, 0f)) * val; float num = (float)i * (height + 0.005f) + height * 0.5f; for (int j = 0; j < 2; j++) { float num2 = ((j == 0) ? (-1f) : 1f) * (width * 0.5f + 0.005f); Vector3 val3 = ((i % 2 == 0) ? new Vector3(0f, num, num2) : new Vector3(num2, num, 0f)); list.Add(new Placement { Pos = val3 - val2 * centre, Rot = val2 }); } } return list; } private static List<Placement> MoundLayout(Vector3 ext, Vector3 centre, string id) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: 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) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: 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_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) float num = Math.Max(ext.x, ext.z) * 2f * 0.75f; float num2 = ext.y * 2f * 0.7f; Random random = new Random(StableHash(id)); List<Placement> list = new List<Placement>(); int num3 = 0; int num4 = 3; Vector3 val2 = default(Vector3); while (num4 >= 1) { float num5 = (float)(-(num4 - 1)) * num * 0.5f; for (int i = 0; i < num4; i++) { for (int j = 0; j < num4; j++) { Quaternion val = Quaternion.Euler(0f, (float)(random.NextDouble() * 360.0), 0f); float num6 = (float)(random.NextDouble() - 0.5) * num * 0.2f; float num7 = (float)(random.NextDouble() - 0.5) * num * 0.2f; ((Vector3)(ref val2))..ctor(num5 + (float)i * num + num6, (float)num3 * num2 + ext.y, num5 + (float)j * num + num7); list.Add(new Placement { Pos = val2 - val * centre, Rot = val }); } } num4--; num3++; } return list; } private static Vector3 RotatedExtents(Quaternion q, Vector3 e) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_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_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002d: 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_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: 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_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_005f: 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_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: 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_00bd: Unknown result type (might be due to invalid IL or missing references) Vector3 val = q * new Vector3(e.x, 0f, 0f); Vector3 val2 = q * new Vector3(0f, e.y, 0f); Vector3 val3 = q * new Vector3(0f, 0f, e.z); return new Vector3(Math.Abs(val.x) + Math.Abs(val2.x) + Math.Abs(val3.x), Math.Abs(val.y) + Math.Abs(val2.y) + Math.Abs(val3.y), Math.Abs(val.z) + Math.Abs(val2.z) + Math.Abs(val3.z)); } private static Vector3 Div(Vector3 a, Vector3 b) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: 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_0022: 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_003d: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: 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_005f: 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_0066: Unknown result type (might be due to invalid IL or missing references) return new Vector3((b.x != 0f) ? (a.x / b.x) : a.x, (b.y != 0f) ? (a.y / b.y) : a.y, (b.z != 0f) ? (a.z / b.z) : a.z); } private static int StableHash(string s) { int num = 23; foreach (char c in s) { num = num * 31 + c; } return num; } } }
plugins/HBK-HBKHEIM/AAA_Crafting-2.1.11/AzuAntiArthriticCrafting.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using AzuAntiArthriticCrafting; using AzuAntiArthriticCrafting.Compatibility; using AzuAntiArthriticCrafting.Compatibility.AzuCraftyBoxes; using AzuAntiArthriticCrafting.Compatibility.CraftFromContainers; using AzuAntiArthriticCrafting.Compatibility.OdinsCraftyBoxes; using AzuAntiArthriticCrafting.Compatibility.TillValhalla; using AzuAntiArthriticCrafting.Handlers; using AzuAntiArthriticCrafting.Patches; using AzuAntiArthriticCrafting.Patches.Filtering; using AzuAntiArthriticCrafting.RecipeTracking; using AzuAntiArthriticCrafting.RecipeTracking.Favoriting; using AzuAntiArthriticCrafting.Utilities; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Jewelcrafting; using LocalizationManager; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.UI; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.ObjectPool; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.BufferedDeserialization; using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators; using YamlDotNet.Serialization.Callbacks; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("AzuAntiArthriticCrafting")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Azumatt")] [assembly: AssemblyProduct("AzuAntiArthriticCrafting")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")] [assembly: AssemblyFileVersion("2.1.11")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.1.11.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; } } } [RequireComponent(typeof(Image))] public class PointerHandler : MonoBehaviour, IPointerDownHandler, IEventSystemHandler, IPointerClickHandler { private Button _button; private Graphic _graphic; private void Awake() { //IL_0039: 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_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) _button = ((Component)this).GetComponent<Button>(); _graphic = (Graphic)(((object)((Component)this).GetComponent<Graphic>()) ?? ((object)((Component)this).gameObject.AddComponent<Image>())); _graphic.raycastTarget = true; if (_graphic.color.a == 0f) { Color color = _graphic.color; color.a = 0.001f; _graphic.color = color; } } private void OnEnable() { if ((Object)(object)_button != (Object)null) { FavoriteManager._filterRowButtons.Add(_button); } } private void OnDisable() { if ((Object)(object)_button != (Object)null) { FavoriteManager._filterRowButtons.Remove(_button); } } public void OnPointerDown(PointerEventData e) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 if ((int)e.button == 1) { HandleRightClick(e); } } public void OnPointerClick(PointerEventData e) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 if ((int)e.button == 1) { HandleRightClick(e); } } private void HandleRightClick(PointerEventData e) { ((AbstractEventData)e).Use(); foreach (Button filterRowButton in FavoriteManager._filterRowButtons) { if ((Object)(object)filterRowButton == (Object)null || !((Behaviour)filterRowButton).isActiveAndEnabled) { continue; } Transform val = ((Component)filterRowButton).transform.Find("Glow"); if (!Object.op_Implicit((Object)(object)val)) { continue; } bool activeSelf = ((Component)val).gameObject.activeSelf; if ((Object)(object)((Component)filterRowButton).gameObject == (Object)(object)((Component)this).gameObject) { if (!activeSelf) { ((UnityEvent)filterRowButton.onClick).Invoke(); } } else if (activeSelf) { ((UnityEvent)filterRowButton.onClick).Invoke(); } } } } [HarmonyPatch(typeof(Hud), "Awake")] internal static class HudAwakePatchAddTutOverlay { private static void Postfix(Hud __instance) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) GameObject obj = GameObject.Find("TutorialOverlay"); if ((Object)(object)((obj != null) ? obj.gameObject : null) == (Object)null) { GameObject val = new GameObject("TutorialOverlay"); val.transform.SetParent(GameObject.Find("_GameMain/LoadingGUI/PixelFix/IngameGui/Tutorial/").transform, false); val.AddComponent<TutorialOverlay>(); } } } public class TutorialOverlay : MonoBehaviour { [Serializable] public class TutorialStep { public string title; public string description; public TutorialTargetType targetType; } public enum TutorialTargetType { CraftingPanel, RecipeTrackerIcon, Grid, CraftAmountInput, CraftAmountMinus, CraftAmountPlus, MaxAmountText, FilterRow, AdvFilters, SearchAndPagination } public RectTransform? targetUIElement; public Color overlayColor = new Color(0f, 0f, 0f, 0.95f); private Image overlayImage; private Material overlayMaterial; private GameObject tutorialTextPanel; private int currentStep; internal bool tutorialActive; private static readonly string TutorialKey = "AAA_HasSeenCraftingTutorial"; internal static TutorialOverlay instance = null; private readonly TutorialStep[] tutorialSteps = new TutorialStep[6] { new TutorialStep { title = "$aaa_tutorial_welcome", description = "$aaa_welcome_message", targetType = TutorialTargetType.CraftingPanel }, new TutorialStep { title = "$aaa_craftinggrid_title", description = "$aaa_craftinggrid_message", targetType = TutorialTargetType.Grid }, new TutorialStep { title = "$aaa_searchfilters_title", description = "$aaa_searchfilters_message", targetType = TutorialTargetType.SearchAndPagination }, new TutorialStep { title = "$aaa_recipetracker_title", description = "$aaa_recipetracker_message", targetType = TutorialTargetType.RecipeTrackerIcon }, new TutorialStep { title = "$aaa_multicrafting_title", description = "$aaa_multicrafting_message", targetType = TutorialTargetType.CraftAmountInput }, new TutorialStep { title = "$aaa_multicrafting_title", description = "$aaa_multicrafting_message", targetType = TutorialTargetType.CraftAmountInput } }; private void OnEnable() { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected O, but got Unknown //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_009a: 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_00b4: Expected O, but got Unknown //IL_00c0: 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_0024: 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) Canvas val = ((Component)((Component)this).transform.parent).GetComponent<Canvas>(); if ((Object)(object)val == (Object)null) { GameObject val2 = new GameObject("TutorialOverlayCanvas"); val = val2.AddComponent<Canvas>(); val.renderMode = (RenderMode)0; val2.AddComponent<CanvasScaler>(); val2.AddComponent<GraphicRaycaster>(); val.sortingOrder = 99999; } GameObject val3 = new GameObject("TutorialOverlayImage"); val3.transform.SetParent(((Component)val).transform, false); overlayImage = val3.AddComponent<Image>(); RectTransform component = val3.GetComponent<RectTransform>(); component.anchorMin = Vector2.zero; component.anchorMax = Vector2.one; component.offsetMin = Vector2.zero; component.offsetMax = Vector2.zero; overlayMaterial = new Material(AzuAntiArthriticCraftingPlugin.overlayShader); overlayMaterial.SetColor("_Color", overlayColor); ((Graphic)overlayImage).material = overlayMaterial; ((Graphic)overlayImage).raycastTarget = false; instance = this; CreateTutorialTextPanel(((Component)val).transform); ((Behaviour)overlayImage).enabled = false; tutorialTextPanel.SetActive(false); } private void UpdateHole() { //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_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0094: 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_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) if (!InventoryGui.IsVisible()) { ((Behaviour)overlayImage).enabled = false; return; } Rect worldRect = UiFinder.GetWorldRect(targetUIElement); bool flag = ((Rect)(ref worldRect)).width > 1f && ((Rect)(ref worldRect)).height > 1f; ((Behaviour)overlayImage).enabled = flag; if (flag) { float num = Screen.width; float num2 = Screen.height; Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(((Rect)(ref worldRect)).xMin / num, ((Rect)(ref worldRect)).yMin / num2); Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor(((Rect)(ref worldRect)).xMax / num, ((Rect)(ref worldRect)).yMax / num2); Vector2 val3 = (val + val2) * 0.5f; Vector2 val4 = val2 - val; val4.x = Mathf.Clamp01(val4.x); val4.y = Mathf.Clamp01(val4.y); val3.x = Mathf.Clamp01(val3.x); val3.y = Mathf.Clamp01(val3.y); overlayMaterial.SetVector("_HoleRect", new Vector4(val3.x, val3.y, val4.x, val4.y)); } } private void CreateTutorialTextPanel(Transform canvasTransform) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Expected O, but got Unknown //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_018c: 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_01c1: Expected O, but got Unknown //IL_0280: Unknown result type (might be due to invalid IL or missing references) tutorialTextPanel = new GameObject("TutorialTextPanel", new Type[2] { typeof(RectTransform), typeof(Image) }); tutorialTextPanel.transform.SetParent(canvasTransform, false); ((Graphic)tutorialTextPanel.GetComponent<Image>()).color = new Color(0.1f, 0.08f, 0.06f, 0.95f); tutorialTextPanel.transform.SetParent(canvasTransform, false); tutorialTextPanel.transform.SetAsLastSibling(); if (!Object.op_Implicit((Object)(object)tutorialTextPanel.GetComponent<GraphicRaycaster>())) { tutorialTextPanel.AddComponent<GraphicRaycaster>(); } RectTransform component = tutorialTextPanel.GetComponent<RectTransform>(); component.anchorMin = new Vector2(0.25f, 0.08f); component.anchorMax = new Vector2(0.75f, 0.32f); component.offsetMin = Vector2.zero; component.offsetMax = Vector2.zero; VerticalLayoutGroup val = tutorialTextPanel.GetComponent<VerticalLayoutGroup>(); if (!Object.op_Implicit((Object)(object)val)) { val = tutorialTextPanel.AddComponent<VerticalLayoutGroup>(); } ((HorizontalOrVerticalLayoutGroup)val).spacing = 8f; ((LayoutGroup)val).padding = new RectOffset(20, 20, 16, 16); ((HorizontalOrVerticalLayoutGroup)val).childControlWidth = true; ((HorizontalOrVerticalLayoutGroup)val).childControlHeight = true; ((LayoutGroup)val).childAlignment = (TextAnchor)4; CreateTutorialText("TitleText", "", 20, (FontStyles)1, new Color(1f, 0.85f, 0.5f)); CreateTutorialText("DescriptionText", "", 16, (FontStyles)0, new Color(0.9f, 0.88f, 0.82f)); GameObject val2 = new GameObject("ButtonContainer", new Type[2] { typeof(RectTransform), typeof(HorizontalLayoutGroup) }); val2.transform.SetParent(tutorialTextPanel.transform, false); HorizontalLayoutGroup component2 = val2.GetComponent<HorizontalLayoutGroup>(); ((HorizontalOrVerticalLayoutGroup)component2).spacing = 12f; ((LayoutGroup)component2).childAlignment = (TextAnchor)4; ((HorizontalOrVerticalLayoutGroup)component2).childControlWidth = false; ((HorizontalOrVerticalLayoutGroup)component2).childControlHeight = false; CreateVanillaButton(val2.transform, "PrevButton", "$aaa_btn_prev", delegate { PreviousStep(); }); CreateVanillaButton(val2.transform, "NextButton", "$aaa_btn_next", delegate { NextStep(); }); CreateVanillaButton(val2.transform, "SkipButton", "$aaa_btn_skip", delegate { EndTutorial(skipped: true); }); CreateTutorialText("StepCounter", "", 13, (FontStyles)0, new Color(0.6f, 0.55f, 0.45f)); } private void CreateVanillaButton(Transform parent, string name, string text, Action onClick) { //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Expected O, but got Unknown //IL_00fa: Unknown result type (might be due to invalid IL or missing references) Button val = InventoryGui.instance?.m_craftButton; if (!((Object)(object)val == (Object)null)) { GameObject val2 = Object.Instantiate<GameObject>(((Component)val).gameObject, parent); ((Object)val2).name = name; MaxCraftAmount maxCraftAmount = default(MaxCraftAmount); if (val2.TryGetComponent<MaxCraftAmount>(ref maxCraftAmount)) { Object.DestroyImmediate((Object)(object)maxCraftAmount); } Transform val3 = val2.transform.Find("AAAMaxCraftAmountText"); if (Object.op_Implicit((Object)(object)val3)) { Object.DestroyImmediate((Object)(object)((Component)val3).gameObject); } UIGamePad val4 = default(UIGamePad); if (val2.TryGetComponent<UIGamePad>(ref val4)) { Object.Destroy((Object)(object)val4); } LayoutGroup[] components = val2.GetComponents<LayoutGroup>(); for (int i = 0; i < components.Length; i++) { Object.Destroy((Object)(object)components[i]); } ContentSizeFitter component = val2.GetComponent<ContentSizeFitter>(); if (Object.op_Implicit((Object)(object)component)) { Object.Destroy((Object)(object)component); } Button component2 = val2.GetComponent<Button>(); ((UnityEventBase)component2.onClick).RemoveAllListeners(); ((UnityEvent)component2.onClick).AddListener((UnityAction)delegate { onClick?.Invoke(); }); val2.GetComponent<RectTransform>().sizeDelta = new Vector2(90f, 35f); TMP_Text componentInChildren = val2.GetComponentInChildren<TMP_Text>(); if (Object.op_Implicit((Object)(object)componentInChildren)) { componentInChildren.text = Localization.instance.Localize(text); componentInChildren.fontSize = 14f; } } } private void CreateTutorialText(string name, string text, int fontSize, FontStyles fontStyle, Color color) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) }); val.transform.SetParent(tutorialTextPanel.transform, false); val.SetActive(false); TextMeshProUGUI val2 = val.AddComponent<TextMeshProUGUI>(); ((TMP_Text)val2).text = text; if ((Object)(object)InventoryGui.instance != (Object)null) { ((TMP_Text)val2).font = InventoryGui.instance.m_armor.font; } else { ((TMP_Text)val2).font = ResolveSafeFont() ?? TMP_Settings.defaultFontAsset; if ((Object)(object)((TMP_Text)val2).font == (Object)null) { AzuAntiArthriticCraftingPlugin.AntiArthriticCraftingLogger.LogWarning((object)"Warning: No TMP font available for tutorial text!"); ((TMP_Text)val2).font = TMP_Settings.defaultFontAsset; } } ((TMP_Text)val2).fontSize = fontSize; ((TMP_Text)val2).fontStyle = fontStyle; ((Graphic)val2).color = color; ((TMP_Text)val2).alignment = (TextAlignmentOptions)257; ((Graphic)val2).raycastTarget = false; ((TMP_Text)val2).enableWordWrapping = true; ((Component)val2).gameObject.SetActive(true); } private static TMP_FontAsset ResolveSafeFont() { InventoryGui val = InventoryGui.instance; if ((Object)(object)val != (Object)null && Object.op_Implicit((Object)(object)val.m_armor) && Object.op_Implicit((Object)(object)val.m_armor.font)) { return val.m_armor.font; } if (Object.op_Implicit((Object)(object)TMP_Settings.defaultFontAsset)) { return TMP_Settings.defaultFontAsset; } return Resources.FindObjectsOfTypeAll<TMP_FontAsset>().FirstOrDefault(); } public static void StartCraftingTutorial() { if (!((Object)(object)instance == (Object)null) && PlayerPrefs.GetInt(TutorialKey, 0) != 1) { instance.StartTutorial(); } } public static void StartCraftingTutorialForced() { if (!((Object)(object)instance == (Object)null)) { instance.StartTutorial(); } } private void StartTutorial() { currentStep = 0; tutorialActive = true; UpdateTutorialStep(); } private void UpdateTutorialStep() { if (currentStep >= tutorialSteps.Length) { return; } TutorialStep tutorialStep = tutorialSteps[currentStep]; SetTargetForStep(tutorialStep.targetType); Transform val = tutorialTextPanel.transform.Find("TitleText"); if ((Object)(object)val != (Object)null) { ((TMP_Text)((Component)val).GetComponent<TextMeshProUGUI>()).text = Localization.instance.Localize(tutorialStep.title); } Transform val2 = tutorialTextPanel.transform.Find("DescriptionText"); if ((Object)(object)val2 != (Object)null) { ((TMP_Text)((Component)val2).GetComponent<TextMeshProUGUI>()).text = Localization.instance.Localize(tutorialStep.description); } Transform val3 = tutorialTextPanel.transform.Find("StepCounter"); if ((Object)(object)val3 != (Object)null) { ((TMP_Text)((Component)val3).GetComponent<TextMeshProUGUI>()).text = string.Format(Localization.instance.Localize("$aaa_stepcounter"), currentStep + 1, tutorialSteps.Length); } Transform val4 = tutorialTextPanel.transform.Find("ButtonContainer"); if ((Object)(object)val4 != (Object)null) { Transform val5 = val4.Find("PrevButton"); if ((Object)(object)val5 != (Object)null) { ((Selectable)((Component)val5).GetComponent<Button>()).interactable = currentStep > 0; } } UpdateHole(); ((Behaviour)overlayImage).enabled = true; tutorialTextPanel.SetActive(true); } private void SetTargetForStep(TutorialTargetType targetType) { RectTransform val = null; switch (targetType) { case TutorialTargetType.CraftingPanel: val = UiFinder.TryMany("_GameMain/LoadingGUI/PixelFix/IngameGui/Inventory_screen/root/Crafting/", "Crafting"); break; case TutorialTargetType.RecipeTrackerIcon: val = (RectTransform)(Object.op_Implicit((Object)(object)InventoryGui.instance) ? ((object)/*isinst with value type is only supported in some contexts*/) : ((object)UiFinder.TryMany("_GameMain/LoadingGUI/PixelFix/IngameGui/Inventory_screen/root/Crafting/Decription/_GameMain/LoadingGUI/PixelFix/IngameGui/Inventory_screen/root/Crafting/Decription/Icon"))); break; case TutorialTargetType.AdvFilters: if (Object.op_Implicit((Object)(object)FavoriteManager._rightFilterRow)) { val = ((Component)FavoriteManager._rightFilterRow).GetComponent<RectTransform>(); } if (!Object.op_Implicit((Object)(object)val)) { val = UiFinder.TryMany("AAA_FilterRow"); } break; case TutorialTargetType.CraftAmountInput: val = UiFinder.TryMany("AAA_AmountInput"); break; case TutorialTargetType.CraftAmountMinus: val = UiFinder.TryMany("AAA_AmountMinus"); break; case TutorialTargetType.CraftAmountPlus: val = UiFinder.TryMany("AAA_AmountPlus"); break; case TutorialTargetType.MaxAmountText: val = UiFinder.TryMany("AAAMaxCraftAmountText"); if (!Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)InventoryGui.instance) && Object.op_Implicit((Object)(object)InventoryGui.instance.m_craftButton)) { val = ((Component)InventoryGui.instance.m_craftButton).GetComponent<RectTransform>(); } break; case TutorialTargetType.Grid: val = UiFinder.TryMany("RecipeList/Recipes", "_GameMain/LoadingGUI/PixelFix/IngameGui/Inventory_screen/root/Crafting/RecipeList/Recipes"); break; case TutorialTargetType.FilterRow: val = UiFinder.TryMany("AAA_FilterRow"); break; case TutorialTargetType.SearchAndPagination: if (Object.op_Implicit((Object)(object)PaginatorPatches.CraftingWindowPaginator)) { val = PaginatorPatches.CraftingWindowPaginator.GetComponent<RectTransform>(); } if (!Object.op_Implicit((Object)(object)val)) { val = UiFinder.TryMany("Pagination_Horizontal(Clone)", "Pagination_Horizontal"); } break; } targetUIElement = val; } private void NextStep() { currentStep++; if (currentStep >= tutorialSteps.Length) { EndTutorial(skipped: false); } else { UpdateTutorialStep(); } } private void PreviousStep() { if (currentStep > 0) { currentStep--; UpdateTutorialStep(); } } private void EndTutorial(bool skipped) { tutorialActive = false; ((Behaviour)overlayImage).enabled = false; tutorialTextPanel.SetActive(false); Time.timeScale = 1f; PlayerPrefs.SetInt(TutorialKey, 1); PlayerPrefs.Save(); } private void Update() { if (tutorialActive) { if (Input.GetKeyDown((KeyCode)27)) { EndTutorial(skipped: true); } if (currentStep < tutorialSteps.Length) { UpdateHole(); } } } public static void ResetTutorial() { PlayerPrefs.DeleteKey(TutorialKey); } } public sealed class VariantTag : MonoBehaviour { public int Variant; } [HarmonyPatch(typeof(ObjectDB), "Awake")] internal static class AddVariantsToObjectDBAwakePatch { [HarmonyPriority(0)] private static void Postfix(ObjectDB __instance) { List<GameObject> items = __instance.m_items; if (items == null || __instance.m_recipes == null) { return; } List<Recipe> list = new List<Recipe>(); foreach (GameObject item in items) { ItemDrop drop = (Object.op_Implicit((Object)(object)item) ? item.GetComponent<ItemDrop>() : null); SharedData val = ((!Object.op_Implicit((Object)(object)drop)) ? null : drop.m_itemData?.m_shared); if (val == null) { continue; } int variants = val.m_variants; if (variants <= 1) { continue; } Recipe val2 = ((IEnumerable<Recipe>)__instance.m_recipes).FirstOrDefault((Func<Recipe, bool>)delegate(Recipe r) { if (Object.op_Implicit((Object)(object)r) && (Object)(object)r.m_item == (Object)(object)drop && !r.m_noCraftOnlyUpgrade) { Requirement[] resources = r.m_resources; if (resources != null) { return resources.Length > 0; } return false; } return false; }); if (!Object.op_Implicit((Object)(object)val2) || (Object)(object)val2.m_item == (Object)null || (Object)(object)val2.m_item.m_itemData.GetIcon() == (Object)null || val2.m_item.m_itemData == null || val2.m_item.m_itemData.m_shared == null) { continue; } for (int num = 1; num < variants; num++) { Sprite[] array = val2.m_item?.m_itemData?.m_shared?.m_icons; if (array != null && num < array.Length && (Object)(object)array[num] != (Object)null) { CreateVariantRecipe(val2, num, out Recipe clone); list.Add(clone); } } } if (list.Count > 0) { list.Sort(delegate(Recipe a, Recipe b) { Utilities.TryGetVariantFromRecipeName(((Object)a).name, out var variant); Utilities.TryGetVariantFromRecipeName(((Object)b).name, out var variant2); return variant.CompareTo(variant2); }); __instance.m_recipes.AddRange(list); __instance.UpdateRegisters(); } } public static void CreateVariantRecipe(Recipe recipe, int variant, out Recipe clone) { clone = Object.Instantiate<Recipe>(recipe); ((Object)clone).name = $"{((Object)recipe).name}_var{variant}"; } } [HarmonyPatch(typeof(InventoryGui), "SetRecipe")] internal static class SetRecipe_ApplyVariantFromName { private static void Postfix(InventoryGui __instance, int index, ref bool center) { //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) if (index < 0 || index >= __instance.m_availableRecipes.Count) { return; } RecipeDataPair val = __instance.m_availableRecipes[index]; Recipe recipe = ((RecipeDataPair)(ref val)).Recipe; if (!Object.op_Implicit((Object)(object)recipe) || !Utilities.TryGetVariantFromRecipeName(((Object)recipe).name, out var variant)) { return; } __instance.m_selectedVariant = variant; TMP_Text recipeName = __instance.m_recipeName; if (Object.op_Implicit((Object)(object)recipeName)) { string text = recipeName.text; int num = text.IndexOf(" #", StringComparison.Ordinal); if (num >= 0) { text = text.Substring(0, num); } recipeName.text = $"{text} #{variant + 1}"; } if (Object.op_Implicit((Object)(object)DescriptionExpander.scrollRect)) { DescriptionExpander.scrollRect.verticalNormalizedPosition = 1f; } center = false; } } [HarmonyPatch(typeof(InventoryGui), "AddRecipeToList")] internal static class AddRecipeToList_VariantIcon { [ThreadStatic] private static int _prevCount; [ThreadStatic] private static bool _wasCraftTab; private static bool Prefix(InventoryGui __instance, Player player, Recipe recipe, ItemData item, bool canCraft) { _wasCraftTab = __instance.InCraftTab(); _prevCount = __instance.m_availableRecipes?.Count ?? 0; if (!_wasCraftTab && item != null && Utilities.TryGetVariantFromRecipeName(((Object)recipe).name, out var _)) { return false; } return true; } private static void Postfix(InventoryGui __instance, Player player, Recipe recipe, ItemData item, bool canCraft) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0077: 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) List<RecipeDataPair> availableRecipes = __instance.m_availableRecipes; if (availableRecipes == null || availableRecipes.Count == 0) { return; } int prevCount = _prevCount; if (prevCount < 0 || prevCount >= availableRecipes.Count) { return; } RecipeDataPair val = availableRecipes[prevCount]; if (!Object.op_Implicit((Object)(object)((RecipeDataPair)(ref val)).Recipe) || (Object)(object)((RecipeDataPair)(ref val)).Recipe != (Object)(object)recipe) { bool flag = false; for (int num = availableRecipes.Count - 1; num >= 0; num--) { RecipeDataPair val2 = availableRecipes[num]; if ((Object)(object)((RecipeDataPair)(ref val2)).Recipe == (Object)(object)recipe) { val = availableRecipes[num]; prevCount = num; flag = true; break; } } if (!flag) { return; } } GameObject interfaceElement = ((RecipeDataPair)(ref val)).InterfaceElement; if (!Object.op_Implicit((Object)(object)interfaceElement)) { return; } Transform val3 = interfaceElement.transform.Find("icon"); if (!Object.op_Implicit((Object)(object)val3)) { return; } Image component = ((Component)val3).GetComponent<Image>(); if (!Object.op_Implicit((Object)(object)component)) { return; } int variant = 0; Sprite[] array = null; if (_wasCraftTab) { if (!Utilities.TryGetVariantFromRecipeName(((Object)recipe).name, out variant)) { return; } array = ((!Object.op_Implicit((Object)(object)recipe.m_item)) ? null : recipe.m_item.m_itemData?.m_shared)?.m_icons; } else { if (item == null) { return; } array = item.m_shared?.m_icons; variant = Mathf.Clamp(item.m_variant, 0, ((array == null) ? 1 : array.Length) - 1); } if (array == null || variant < 0 || variant >= array.Length || (Object)(object)array[variant] == (Object)null) { return; } component.sprite = array[variant]; (interfaceElement.GetComponent<VariantTag>() ?? interfaceElement.AddComponent<VariantTag>()).Variant = variant; Transform val4 = interfaceElement.transform.Find("name"); if (!Object.op_Implicit((Object)(object)val4)) { return; } TextMeshProUGUI component2 = ((Component)val4).GetComponent<TextMeshProUGUI>(); if (Object.op_Implicit((Object)(object)component2)) { string text = ((TMP_Text)component2).text; int num2 = text.IndexOf(" #", StringComparison.Ordinal); if (num2 >= 0) { text = text.Substring(0, num2); } ((TMP_Text)component2).text = $"{text} #{variant + 1}"; } } } [HarmonyPatch(typeof(InventoryGui), "DoCrafting")] public static class InventoryGui_DoCrafting_Patch { public static bool callingDoCrafting = false; public static int cachedMaxSockets = 3; public static int cachedLimitNumberOfSockets = 0; public static int[] cachedSocketLimits; public static void Prefix(InventoryGui __instance, Player player) { callingDoCrafting = true; } } [HarmonyPatch(typeof(InventoryGui), "UpdateRecipe")] internal static class InventoryGuiUpdateRecipePatch { private static void Postfix(InventoryGui __instance, Player player) { if (!InventoryGui_DoCrafting_Patch.callingDoCrafting) { return; } int num = HaveRequirementItemsTranspiler.GetCurrentCraftAmount() - 1; if (!__instance.InCraftTab() && !__instance.InUpradeTab() && API.IsLoaded() && API.IsLoaded()) { Transform val = Utils.FindChild(((Component)__instance.m_tabUpgrade).transform.parent, "UPGRADE(Clone)", (IterativeSearchType)0); if ((Object)(object)val != (Object)null && ((Component)val).gameObject.activeSelf) { AzuAntiArthriticCraftingPlugin.AntiArthriticCraftingLogger.LogDebug((object)"Upgrade tab is active, setting desired amount to respect socket limits."); num = 0; } } for (int i = 0; i < num; i++) { InventoryGui_DoCrafting_Patch.callingDoCrafting = false; __instance.DoCrafting(player); } InventoryGui_DoCrafting_Patch.callingDoCrafting = false; } } public static class RecipeNameHelper { private static readonly Regex TagRegex = new Regex("<.*?>", RegexOptions.Compiled); public static string GetCleanName(Recipe r) { string text = r?.m_item?.m_itemData?.m_shared?.m_name ?? ""; if (string.IsNullOrWhiteSpace(text)) { return ""; } return Regex.Replace(new string((from c in TagRegex.Replace(text, "").Replace("$", "").Normalize(NormalizationForm.FormKD) where !char.IsControl(c) select c).ToArray()), "\\s+", " ").Trim().ToLowerInvariant(); } public static string CleanString(string raw) { if (string.IsNullOrWhiteSpace(raw)) { return ""; } return Regex.Replace(new string((from c in TagRegex.Replace(raw, "").Normalize(NormalizationForm.FormKD) where !char.IsControl(c) select c).ToArray()), "\\s+", " ").Trim().ToLowerInvariant(); } } internal static class UiFinder { public static bool TryFindRect(string pathOrName, out RectTransform rt) { rt = null; GameObject val = GameObject.Find(pathOrName); if (Object.op_Implicit((Object)(object)val) && val.TryGetComponent<RectTransform>(ref rt)) { return true; } if (Object.op_Implicit((Object)(object)val)) { rt = val.GetComponent<RectTransform>(); if (Object.op_Implicit((Object)(object)rt)) { return true; } } RectTransform[] source = Resources.FindObjectsOfTypeAll<RectTransform>(); rt = ((IEnumerable<RectTransform>)source).FirstOrDefault((Func<RectTransform, bool>)((RectTransform r) => Object.op_Implicit((Object)(object)r) && ((Object)r).name == pathOrName)); return (Object)(object)rt != (Object)null; } public static RectTransform TryMany(params string[] candidates) { for (int i = 0; i < candidates.Length; i++) { if (TryFindRect(candidates[i], out RectTransform rt)) { return rt; } } return null; } public static Rect GetWorldRect(RectTransform target) { //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)target)) { return Rect.zero; } Vector3[] array = (Vector3[])(object)new Vector3[4]; target.GetWorldCorners(array); float num = Mathf.Min(Mathf.Min(array[0].x, array[1].x), Mathf.Min(array[2].x, array[3].x)); float num2 = Mathf.Max(Mathf.Max(array[0].x, array[1].x), Mathf.Max(array[2].x, array[3].x)); float num3 = Mathf.Min(Mathf.Min(array[0].y, array[1].y), Mathf.Min(array[2].y, array[3].y)); float num4 = Mathf.Max(Mathf.Max(array[0].y, array[1].y), Mathf.Max(array[2].y, array[3].y)); return Rect.MinMaxRect(num, num3, num2, num4); } } namespace LocalizationManager { [PublicAPI] public class Localizer { private static readonly Dictionary<string, Dictionary<string, Func<string>>> PlaceholderProcessors; private static readonly Dictionary<string, Dictionary<string, string>> loadedTexts; private static readonly ConditionalWeakTable<Localization, string> localizationLanguage; private static readonly List<WeakReference<Localization>> localizationObjects; private static BaseUnityPlugin? _plugin; private static readonly List<string> fileExtensions; private static BaseUnityPlugin plugin { get { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown if (_plugin == null) { IEnumerable<TypeInfo> source; try { source = Assembly.GetExecutingAssembly().DefinedTypes.ToList(); } catch (ReflectionTypeLoadException ex) { source = from t in ex.Types where t != null select t.GetTypeInfo(); } _plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First((TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); } return _plugin; } } private static void UpdatePlaceholderText(Localization localization, string key) { localizationLanguage.TryGetValue(localization, out string value); string text = loadedTexts[value][key]; if (PlaceholderProcessors.TryGetValue(key, out Dictionary<string, Func<string>> value2)) { text = value2.Aggregate(text, (string current, KeyValuePair<string, Func<string>> kv) => current.Replace("{" + kv.Key + "}", kv.Value())); } localization.AddWord(key, text); } public static void AddPlaceholder<T>(string key, string placeholder, ConfigEntry<T> config, Func<T, string>? convertConfigValue = null) where T : notnull { if (convertConfigValue == null) { convertConfigValue = (T val) => val.ToString(); } if (!PlaceholderProcessors.ContainsKey(key)) { PlaceholderProcessors[key] = new Dictionary<string, Func<string>>(); } config.SettingChanged += delegate { UpdatePlaceholder(); }; if (loadedTexts.ContainsKey(Localization.instance.GetSelectedLanguage())) { UpdatePlaceholder(); } void UpdatePlaceholder() { PlaceholderProcessors[key][placeholder] = () => convertConfigValue(config.Value); UpdatePlaceholderText(Localization.instance, key); } } public static void AddText(string key, string text) { List<WeakReference<Localization>> list = new List<WeakReference<Localization>>(); foreach (WeakReference<Localization> localizationObject in localizationObjects) { if (localizationObject.TryGetTarget(out var target)) { Dictionary<string, string> dictionary = loadedTexts[localizationLanguage.GetOrCreateValue(target)]; if (!target.m_translations.ContainsKey(key)) { dictionary[key] = text; target.AddWord(key, text); } } else { list.Add(localizationObject); } } foreach (WeakReference<Localization> item in list) { localizationObjects.Remove(item); } } public static void Load() { _ = plugin; } public static void LoadLocalizationLater(Localization __instance) { LoadLocalization(Localization.instance, __instance.GetSelectedLanguage()); } private static void LoadLocalization(Localization __instance, string language) { if (!localizationLanguage.Remove(__instance)) { localizationObjects.Add(new WeakReference<Localization>(__instance)); } localizationLanguage.Add(__instance, language); Dictionary<string, string> dictionary = new Dictionary<string, string>(); foreach (string item in from f in Directory.GetFiles(Path.GetDirectoryName(Paths.PluginPath), plugin.Info.Metadata.Name + ".*", SearchOption.AllDirectories) where fileExtensions.IndexOf(Path.GetExtension(f)) >= 0 select f) { string text = Path.GetFileNameWithoutExtension(item).Split(new char[1] { '.' })[1]; if (dictionary.ContainsKey(text)) { Debug.LogWarning((object)("Duplicate key " + text + " found for " + plugin.Info.Metadata.Name + ". The duplicate file found at " + item + " will be skipped.")); } else { dictionary[text] = item; } } byte[] array = LoadTranslationFromAssembly("English"); if (array == null) { throw new Exception("Found no English localizations in mod " + plugin.Info.Metadata.Name + ". Expected an embedded resource translations/English.json or translations/English.yml."); } Dictionary<string, string> dictionary2 = new DeserializerBuilder().IgnoreFields().Build().Deserialize<Dictionary<string, string>>(Encoding.UTF8.GetString(array)); if (dictionary2 == null) { throw new Exception("Localization for mod " + plugin.Info.Metadata.Name + " failed: Localization file was empty."); } string text2 = null; if (language != "English") { if (dictionary.TryGetValue(language, out var value)) { text2 = File.ReadAllText(value); } else { byte[] array2 = LoadTranslationFromAssembly(language); if (array2 != null) { text2 = Encoding.UTF8.GetString(array2); } } } if (text2 == null && dictionary.TryGetValue("English", out var value2)) { text2 = File.ReadAllText(value2); } if (text2 != null) { foreach (KeyValuePair<string, string> item2 in new DeserializerBuilder().IgnoreFields().Build().Deserialize<Dictionary<string, string>>(text2) ?? new Dictionary<string, string>()) { dictionary2[item2.Key] = item2.Value; } } loadedTexts[language] = dictionary2; foreach (KeyValuePair<string, string> item3 in dictionary2) { UpdatePlaceholderText(__instance, item3.Key); } } static Localizer() { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Expected O, but got Unknown PlaceholderProcessors = new Dictionary<string, Dictionary<string, Func<string>>>(); loadedTexts = new Dictionary<string, Dictionary<string, string>>(); localizationLanguage = new ConditionalWeakTable<Localization, string>(); localizationObjects = new List<WeakReference<Localization>>(); fileExtensions = new List<string> { ".json", ".yml" }; Harmony val = new Harmony("org.bepinex.helpers.LocalizationManager"); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Localizer), "LoadLocalization", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "SetupGui", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Localizer), "LoadLocalizationLater", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } private static byte[]? LoadTranslationFromAssembly(string language) { foreach (string fileExtension in fileExtensions) { byte[] array = ReadEmbeddedFileBytes("translations." + language + fileExtension); if (array != null) { return array; } } return null; } public static byte[]? ReadEmbeddedFileBytes(string resourceFileName, Assembly? containingAssembly = null) { using MemoryStream memoryStream = new MemoryStream(); if ((object)containingAssembly == null) { containingAssembly = Assembly.GetCallingAssembly(); } string text = containingAssembly.GetManifestResourceNames().FirstOrDefault((string str) => str.EndsWith(resourceFileName, StringComparison.Ordinal)); if (text != null) { containingAssembly.GetManifestResourceStream(text)?.CopyTo(memoryStream); } return (memoryStream.Length == 0L) ? null : memoryStream.ToArray(); } } } namespace AzuAntiArthriticCrafting { public class FavoriteStarHider : MonoBehaviour { private void Update() { if (!((Object)(object)InventoryGui.instance == (Object)null)) { if (!InventoryGui.instance.InCraftTab() || AzuAntiArthriticCraftingPlugin.FavoritingSystem.IsOff()) { ((Component)this).gameObject.SetActive(false); } else { ((Component)this).gameObject.SetActive(true); } } } } public class MaxCraftAmount : MonoBehaviour { internal const string objectName = "AAAMaxCraftAmountText"; private Recipe? _lastRecipe; private TextMeshProUGUI _maxCraftAmountText; public static bool InventoryChanged; private void Awake() { //IL_00d9: 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_010f: 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) GameObject gameObject = ((Component)this).gameObject; Transform val = gameObject.transform.Find("Text"); if ((Object)(object)val == (Object)null) { AzuAntiArthriticCraftingPlugin.AntiArthriticCraftingLogger.LogWarning((object)("Could not find 'Text' child object under " + ((Object)gameObject).name)); return; } TextMeshProUGUI component = ((Component)val).GetComponent<TextMeshProUGUI>(); if ((Object)(object)component == (Object)null) { AzuAntiArthriticCraftingPlugin.AntiArthriticCraftingLogger.LogWarning((object)("Could not find TextMeshProUGUI component on 'Text' child object under " + ((Object)gameObject).name)); return; } GameObject val2 = Object.Instantiate<GameObject>(((Component)component).gameObject, gameObject.transform, true); ((Object)val2).name = "AAAMaxCraftAmountText"; _maxCraftAmountText = val2.GetComponent<TextMeshProUGUI>(); ((TMP_Text)_maxCraftAmountText).text = string.Empty; ((TMP_Text)_maxCraftAmountText).font = ((TMP_Text)component).font; ((TMP_Text)_maxCraftAmountText).fontSize = 20f; ((TMP_Text)_maxCraftAmountText).fontSizeMax = 20f; ((TMP_Text)_maxCraftAmountText).fontStyle = ((TMP_Text)component).fontStyle; ((Graphic)_maxCraftAmountText).color = ((Graphic)component).color; ((TMP_Text)_maxCraftAmountText).alignment = (TextAlignmentOptions)514; ((TMP_Text)_maxCraftAmountText).rectTransform.sizeDelta = Vector2.zero; ((TMP_Text)_maxCraftAmountText).rectTransform.anchoredPosition = new Vector2(0f, -35f); _lastRecipe = null; } private void Update() { if (AzuAntiArthriticCraftingPlugin.ShowMaxCraftAmountToggle == null || AzuAntiArthriticCraftingPlugin.ShowMaxCraftAmountToggle.IsOff()) { if ((Object)(object)_maxCraftAmountText != (Object)null && ((Component)_maxCraftAmountText).gameObject.activeSelf) { ((Component)_maxCraftAmountText).gameObject.SetActive(false); } return; } if ((Object)(object)_maxCraftAmountText != (Object)null && !((Component)_maxCraftAmountText).gameObject.activeSelf) { ((Component)_maxCraftAmountText).gameObject.SetActive(true); } if ((Object)(object)InventoryGui.instance == (Object)null) { return; } if (!InventoryGui.instance.InCraftTab() && !InventoryGui.instance.InUpradeTab()) { if ((Object)(object)_maxCraftAmountText != (Object)null && ((Component)_maxCraftAmountText).gameObject.activeSelf) { ((Component)_maxCraftAmountText).gameObject.SetActive(false); } return; } Recipe recipe = ((RecipeDataPair)(ref InventoryGui.instance.m_selectedRecipe)).Recipe; if (!((Object)(object)_lastRecipe != (Object)(object)recipe) && !InventoryChanged) { return; } if ((Object)(object)_maxCraftAmountText != (Object)null) { if ((Object)(object)Player.m_localPlayer != (Object)null && Player.m_localPlayer.NoCostCheat()) { ((TMP_Text)_maxCraftAmountText).text = Localization.instance.Localize("$aaa_maxcraftamount: ∞"); } else { int maxAmountCached = AAACraft.GetMaxAmountCached(); ((TMP_Text)_maxCraftAmountText).text = Localization.instance.Localize("$aaa_maxcraftamount: " + maxAmountCached.ToString(CultureInfo.InvariantCulture)); } } _lastRecipe = recipe; InventoryChanged = false; } } [HarmonyPatch(typeof(Inventory), "Changed")] internal static class InventoryChangedPatch { private static void Postfix(Inventory __instance) { if (__instance.m_onChanged != null) { MaxCraftAmount.InventoryChanged = true; } } } public class NoCostReqHandler : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler, IPointerClickHandler { private bool isHovering; internal Requirement m_requirement; public void OnPointerEnter(PointerEventData eventData) { isHovering = true; } public void OnPointerExit(PointerEventData eventData) { isHovering = false; } public void OnPointerClick(PointerEventData eventData) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //IL_00c8: Unknown result type (might be due to invalid IL or missing references) if ((int)eventData.button == 1 && isHovering) { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null) && m_requirement != null && (localPlayer.NoCostCheat() || ZoneSystem.instance.GetGlobalKey((GlobalKeys)25)) && ZNet.instance.LocalPlayerIsAdminOrHost()) { int num = m_requirement.m_amount * HaveRequirementItemsTranspiler.GetCurrentCraftAmount(); Vector2i val = default(Vector2i); ((Vector2i)(ref val))..ctor(-1, -1); long playerID = localPlayer.GetPlayerID(); string playerName = localPlayer.GetPlayerName(); ((Humanoid)localPlayer).GetInventory().AddItem(((Object)((Component)m_requirement.m_resItem).gameObject).name, num, m_requirement.m_resItem.m_itemData.m_quality, m_requirement.m_resItem.m_itemData.m_variant, playerID, playerName, val, false, false, true); } } } } public class ScrollableInputField : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler, IPointerExitHandler, ISelectHandler, IDeselectHandler { public TMP_InputField inputField; public static ScrollableInputField instance; internal bool isHovering; private float gamepadScrollCooldown = 0.1f; private float lastGamepadScrollTime; private ButtonSfx? buttonSound; private void Awake() { instance = this; inputField = ((Component)this).GetComponent<TMP_InputField>(); if (Object.op_Implicit((Object)(object)InventoryGui.instance)) { buttonSound = ((Component)InventoryGui.instance.m_tabCraft).GetComponent<ButtonSfx>(); } } private void Update() { //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)InventoryGui.instance == (Object)null) { return; } InventoryGui.instance.m_multiCrafting = false; InventoryGui.instance.m_multiCraftAmount = 1; if (!isHovering) { return; } float time = Time.time; float num = Input.GetAxis("Mouse ScrollWheel"); if (ZInput.IsGamepadActive() && time - lastGamepadScrollTime >= gamepadScrollCooldown) { if (ZInput.GetButton("JoyCamZoomIn") || ZInput.GetButton("Forward")) { num += 0.1f; lastGamepadScrollTime = time; } else if (ZInput.GetButton("JoyCamZoomOut") || ZInput.GetButton("Backward")) { num -= 0.1f; lastGamepadScrollTime = time; } } if (Mathf.Abs(num) < float.Epsilon) { return; } int maxAmountCached = AAACraft.GetMaxAmountCached(); bool flag = (ZInput.IsGamepadActive() && ZInput.GetButton("JoyAltKeys") && !Hud.InRadial()) || AzuAntiArthriticCraftingPlugin.IncrementalModifier.Value.IsKeyHeld(); bool num2 = AzuAntiArthriticCraftingPlugin.MaxCraftModifier.Value.IsKeyHeld() || (ZInput.IsGamepadActive() && ZInput.GetButton("JoyRStick") && !Hud.InRadial()); int num3 = 1; if (!int.TryParse(inputField.text, out var result)) { result = 1; } int num4 = (int)Mathf.Sign(num); if (num2) { result = ((num4 <= 0) ? 1 : maxAmountCached); result = Mathf.Clamp(result, 1, Mathf.Max(1, 100)); buttonSound.OnClick(); inputField.text = result.ToString(CultureInfo.InvariantCulture); return; } if (flag) { num3 = Mathf.Max(1, AzuAntiArthriticCraftingPlugin.IncrementalAmount.Value); result = ((num4 <= 0) ? ((result <= num3) ? 1 : (result - num3)) : ((result == 1) ? num3 : (result + num3))); } else { result += num4; } result = Mathf.Clamp(result, 1, Mathf.Max(1, 100)); if (Object.op_Implicit((Object)(object)InventoryGui.instance)) { buttonSound.OnClick(); ItemData itemData = ((RecipeDataPair)(ref InventoryGui.instance.m_selectedRecipe)).ItemData; if (itemData != null) { int maxQuality = itemData.m_shared.m_maxQuality; int quality = itemData.m_quality; if (maxQuality > 0) { result = Mathf.Clamp(result, 1, maxQuality - quality); } } } inputField.text = result.ToString(CultureInfo.InvariantCulture); InventoryGui obj = InventoryGui.instance; Recipe val = ((obj != null) ? ((RecipeDataPair)(ref obj.m_selectedRecipe)).Recipe : null); if ((Object)(object)val != (Object)null) { InventoryGui obj2 = InventoryGui.instance; ItemData val2 = ((obj2 != null) ? ((RecipeDataPair)(ref obj2.m_selectedRecipe)).ItemData : null); int num5 = ((val2 == null) ? 1 : (val2.m_quality + 1)); if ((Object)(object)Player.m_localPlayer != (Object)null && Player.m_localPlayer.HaveRequirementItems(val, false, num5, 1)) { ((Selectable)InventoryGui.instance.m_craftButton).interactable = true; } } } public void OnPointerEnter(PointerEventData eventData) { TurnOnHover(); } public void OnPointerExit(PointerEventData eventData) { TurnOffHover(); } public void OnSelect(BaseEventData eventData) { TurnOnHover(); } public void OnDeselect(BaseEventData eventData) { TurnOffHover(); } public static void TurnOffHover() { instance.isHovering = false; } public static void TurnOnHover() { instance.isHovering = true; } internal int GetMaxCraftAmount() { return AzuAntiArthriticCrafting.Utilities.Utilities.CalculateMaxCraftAmount(); } } [BepInPlugin("Azumatt.AzuAntiArthriticCrafting", "AzuAntiArthriticCrafting", "2.1.11")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class AzuAntiArthriticCraftingPlugin : BaseUnityPlugin { public enum Toggle { On = 1, Off = 0 } public enum GridSize { Default, Medium, Large } private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [UsedImplicitly] public string? Category; [UsedImplicitly] public Action<ConfigEntryBase>? CustomDrawer; } private class AcceptableShortcuts : AcceptableValueBase { public AcceptableShortcuts() : base(typeof(KeyboardShortcut)) { } public override object Clamp(object value) { return value; } public override bool IsValid(object value) { return true; } public override string ToDescriptionString() { return "# Acceptable values: " + string.Join(", ", UnityInput.Current.SupportedKeyCodes); } } internal const string ModName = "AzuAntiArthriticCrafting"; internal const string ModVersion = "2.1.11"; internal const string Author = "Azumatt"; private const string ModGUID = "Azumatt.AzuAntiArthriticCrafting"; private static string ConfigFileName = "Azumatt.AzuAntiArthriticCrafting.cfg"; private static string ConfigFileFullPath; internal static AzuAntiArthriticCraftingPlugin instance; internal static string ConnectionError; internal static bool CfcLoaded; internal static readonly Harmony harmony; internal static AssetBundle? Asset; internal static AssetBundle? Asset2; internal static AssetBundle? ShaderAssetBundle; internal static Shader? overlayShader; public static readonly ManualLogSource AntiArthriticCraftingLogger; private static readonly ConfigSync ConfigSync; public static GameObject RecipeTrackerUIPrefab; public static BaseUnityPlugin RandyInstance; private static ConfigEntry<Toggle> _serverConfigLocked; public static ConfigEntry<Toggle> ResetCraftingValueOnRecChange; public static ConfigEntry<Toggle> VanillaLike; public static ConfigEntry<GridSize> GridSizeOption; public static ConfigEntry<Toggle> Paginator; public static ConfigEntry<Toggle> FavoritingSystem; public static ConfigEntry<int> IncrementalAmount; public static ConfigEntry<Toggle> ShowMaxCraftAmountToggle; public static ConfigEntry<Toggle> configNoCostLimitRecipesToStation; public static ConfigEntry<Toggle> configNoCostRespectStationLevel; public static ConfigEntry<Toggle> OverrideCraftingDuration; public static ConfigEntry<float> CraftingDuration; public static ConfigEntry<string> RequirementTextFormatting; public static ConfigEntry<string> InputEnabledText; public static ConfigEntry<string> InputDisabledText; public static ConfigEntry<Color> InputTextColor; public static ConfigEntry<KeyboardShortcut> MinusKeybind; public static ConfigEntry<KeyboardShortcut> ToggleUIKeyBind; public static ConfigEntry<KeyboardShortcut> MaxCraftModifier; public static ConfigEntry<KeyboardShortcut> IncrementalModifier; public static ConfigEntry<KeyboardShortcut> FavoriteToggle; public static ConfigEntry<Color> HeaderGlowColor; public static ConfigEntry<Color> HeaderBraidColor; public static ConfigEntry<Color> RecipeContainerBackgroundColor; public static ConfigEntry<Color> ItemNameColor; public static ConfigEntry<Color> RecipeNameColorComplete; public static ConfigEntry<Color> RecipeNameColorInComplete; public static ConfigEntry<Color> RecipeCompleteColor; public static ConfigEntry<Color> RecipeIncompleteRightColor; public static ConfigEntry<Color> RecipeIncompleteLeftColor; public static ConfigEntry<Vector2> RecipeTrackerPanelScale; public static ConfigEntry<float> RecipeTrackerItemNameMin; public static ConfigEntry<float> RecipeTrackerItemNameMax; public static ConfigEntry<float> RecipeTrackerReqNameMin; public static ConfigEntry<float> RecipeTrackerReqNameMax; public static ConfigEntry<Vector2> RecipeTrackerPanelPosition; public static (Vector2 CellSize, Vector2 Spacing, int Columns, int PerPage, int IconSize, int FilterBtnSize) GetGridPreset(GridSize size) { //IL_0014: 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_0041: 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_006e: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) return size switch { GridSize.Medium => (CellSize: new Vector2(65f, 62f), Spacing: new Vector2(5f, 5f), Columns: 4, PerPage: 24, IconSize: 55, FilterBtnSize: 35), GridSize.Large => (CellSize: new Vector2(88f, 76f), Spacing: new Vector2(5f, 5f), Columns: 3, PerPage: 15, IconSize: 65, FilterBtnSize: 35), _ => (CellSize: new Vector2(51f, 51f), Spacing: new Vector2(5f, 7f), Columns: 5, PerPage: 35, IconSize: 43, FilterBtnSize: 35), }; } public void Awake() { //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Expected O, but got Unknown //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_01fc: Expected O, but got Unknown //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_0245: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Expected O, but got Unknown //IL_0293: Unknown result type (might be due to invalid IL or missing references) //IL_02c6: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: 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_0341: Unknown result type (might be due to invalid IL or missing references) //IL_036b: 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_0386: Expected O, but got Unknown //IL_03d3: Unknown result type (might be due to invalid IL or missing references) //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03ee: Expected O, but got Unknown //IL_0412: Unknown result type (might be due to invalid IL or missing references) //IL_0422: Unknown result type (might be due to invalid IL or missing references) //IL_042d: Expected O, but got Unknown //IL_0451: Unknown result type (might be due to invalid IL or missing references) //IL_0461: Unknown result type (might be due to invalid IL or missing references) //IL_046c: Expected O, but got Unknown //IL_0490: Unknown result type (might be due to invalid IL or missing references) //IL_04a0: Unknown result type (might be due to invalid IL or missing references) //IL_04ab: Expected O, but got Unknown //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_04d6: Expected O, but got Unknown //IL_04fa: Unknown result type (might be due to invalid IL or missing references) //IL_050a: Unknown result type (might be due to invalid IL or missing references) //IL_0515: Expected O, but got Unknown //IL_0539: Unknown result type (might be due to invalid IL or missing references) //IL_0549: Unknown result type (might be due to invalid IL or missing references) //IL_0554: Expected O, but got Unknown //IL_0578: 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_0593: Expected O, but got Unknown //IL_05a3: Unknown result type (might be due to invalid IL or missing references) //IL_05b3: Unknown result type (might be due to invalid IL or missing references) //IL_05be: Expected O, but got Unknown //IL_05d8: Unknown result type (might be due to invalid IL or missing references) //IL_05e8: Unknown result type (might be due to invalid IL or missing references) //IL_05f3: Expected O, but got Unknown //IL_0613: Unknown result type (might be due to invalid IL or missing references) //IL_061e: Expected O, but got Unknown //IL_063e: Unknown result type (might be due to invalid IL or missing references) //IL_0649: Expected O, but got Unknown //IL_0669: Unknown result type (might be due to invalid IL or missing references) //IL_0674: Expected O, but got Unknown //IL_0694: Unknown result type (might be due to invalid IL or missing references) //IL_069f: Expected O, but got Unknown instance = this; Localizer.Load(); _serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only."); ConfigSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked); VanillaLike = config("1 - General", "Vanilla-Like", Toggle.Off, "", synchronizedSetting: false); GridSizeOption = config("1 - General", "Grid Size", GridSize.Default, "Controls recipe icon size, grid cell size, columns, and items-per-page. Only takes effect when Vanilla-Like is Off.", synchronizedSetting: false); VanillaLike.SettingChanged += delegate { AzuAntiArthriticCrafting.Utilities.Utilities.SetGrid(); }; GridSizeOption.SettingChanged += delegate { AzuAntiArthriticCrafting.Utilities.Utilities.SetGrid(); if (Object.op_Implicit((Object)(object)InventoryGui.instance)) { InventoryGui.instance.UpdateCraftingPanel(false); } }; ResetCraftingValueOnRecChange = config("1 - Crafting Tweaks", "Reset Crafting Value", Toggle.On, "If enabled, the crafting amount will be reset when the recipe is changed and when crafting completes. If disabled, the crafting amount will not be reset and will keep your previous amount"); Paginator = config("1 - Crafting Tweaks", "Paginator", Toggle.On, "If enabled, the paginator will be enabled. If disabled, the paginator will be disabled", synchronizedSetting: false); Paginator.SettingChanged += delegate { if ((Object)(object)PaginatorPatches.CraftingWindowPaginator != (Object)null) { PaginatorPatches.CraftingWindowPaginator.gameObject.SetActive(Paginator.IsOn()); } else { AzuAntiArthriticCrafting.Utilities.Utilities.CreatePaginator(InventoryGui.instance); if (PaginatorPatches.CraftingWindowPaginator != null) { PaginatorPatches.CraftingWindowPaginator.gameObject.SetActive(Paginator.IsOn()); } } }; FavoritingSystem = config("1 - Crafting Tweaks", "Favorting System", Toggle.On, "If enabled, the favorite toggle buttons and stars will be enabled allowing you to filter by favorites. If disabled, the favorite toggle button and stars will be disabled. Requires restart (or logout!)", synchronizedSetting: false); IncrementalAmount = config("1 - Crafting Tweaks", "Incremental Amount", 10, "The amount to increase by when your Incremental Modifier key is held down.", synchronizedSetting: false); ShowMaxCraftAmountToggle = config("1 - Crafting Tweaks", "Show Max Craft Amount", Toggle.On, "Toggle the display of the max craft amount text in the crafting UI.", synchronizedSetting: false); configNoCostLimitRecipesToStation = config("1 - Crafting Tweaks", "Limit recipes to station with nocost mode", Toggle.Off, "When nocost mode is active, only show recipes craftable at your current crafting station."); configNoCostRespectStationLevel = config("1 - Crafting Tweaks", "Respect station level with nocost mode", Toggle.Off, "When limiting recipes to station, also require the station's upgrade level."); OverrideCraftingDuration = config("2 - Game", "Override Crafting Speed", Toggle.Off, new ConfigDescription("If enabled, the crafting speed will be overridden by the value set in Crafting Speed. If disabled, the crafting speed will be vanilla and multiplied by the amounts you wish to craft. Default is off.", (AcceptableValueBase)null, Array.Empty<object>())); CraftingDuration = config("2 - Game", "Crafting Speed", 2f, new ConfigDescription("Change the speed at which it takes to craft items. Override Crafting Speed option must be on for this to take effect. This value is in seconds. To craft faster, make this value smaller. To craft slower, make this value larger. Default is 2 seconds.", (AcceptableValueBase)null, Array.Empty<object>())); InputTextColor = config<Color>("3 - Input Tweaks", "Input Text Color", new Color(1f, 61f / 85f, 49f / 136f, 1f), new ConfigDescription("Change the placeholder text for the input field. Default is \"Enter Amount...\"", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = 2 } }), synchronizedSetting: false); InputTextColor.SettingChanged += delegate { //IL_002b: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)InventoryGui.instance == (Object)null) && !((Object)(object)AAACraft.inputAmount == (Object)null)) { ((Graphic)AAACraft.inputAmount.textComponent).color = InputTextColor.Value; } }; MinusKeybind = config<KeyboardShortcut>("4 - Keys", "Show Minus Button", new KeyboardShortcut((KeyCode)306, Array.Empty<KeyCode>()), "The key to hold down to show the minus button instead of the plus when hovering recipe icons in the crafting menu. [Default: LeftControl]", synchronizedSetting: false); ToggleUIKeyBind = config<KeyboardShortcut>("4 - Keys", "Toggle RecipeUI", new KeyboardShortcut((KeyCode)304, (KeyCode[])(object)new KeyCode[1] { (KeyCode)280 }), "The key to toggle the RecipeUI. [Default: LeftShift + PageUp]", synchronizedSetting: false); MaxCraftModifier = config<KeyboardShortcut>("4 - Keys", "Max Craft Modifier", new KeyboardShortcut((KeyCode)306, Array.Empty<KeyCode>()), "The key that, when held down and using the scrollwheel over the input box, will make it jump to the max amount you can craft", synchronizedSetting: false); IncrementalModifier = config<KeyboardShortcut>("4 - Keys", "Incremental Modifier", new KeyboardShortcut((KeyCode)304, Array.Empty<KeyCode>()), "The key that, when held down and using the scrollwheel over the input box, will make it increase by your defined amount [Default: 10] in the Incremental Amount configuration option.", synchronizedSetting: false); FavoriteToggle = config<KeyboardShortcut>("4 - Keys", "Favorite Toggle", new KeyboardShortcut((KeyCode)102, Array.Empty<KeyCode>()), "Key to toggle the favorite filter (star button) on and off. [Default: F]", synchronizedSetting: false); RecipeTrackerPanelPosition = config<Vector2>("5 - Recipe Tracker (Position)", "Recipe Tracker Position", new Vector2(783f, 265f), new ConfigDescription("Change the anchored position of the recipe tracker panel. Default is 816, 184.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); RecipeTrackerPanelPosition.SettingChanged += delegate { //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)HudAwakePatch.RecipeTrackerUI == (Object)null)) { ((Component)HudAwakePatch.RecipeTrackerUI).GetComponent<RectTransform>().anchoredPosition = RecipeTrackerPanelPosition.Value; } }; HeaderGlowColor = config<Color>("5 - Recipe Tracker (Color)", "Header Glow Color", new Color(0.58f, 0.235f, 0.19f, 1f), new ConfigDescription("Change the color of the header glow. Default is dark red.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); HeaderBraidColor = config<Color>("5 - Recipe Tracker (Color)", "Header Braid Color", new Color(1f, 0.717f, 0.356f, 1f), new ConfigDescription("Change the color of the header braid (decoration). Default is mustard yellow.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); RecipeContainerBackgroundColor = config<Color>("5 - Recipe Tracker (Color)", "Recipe Container Background Color", new Color(0f, 0f, 0f, 0.5f), new ConfigDescription("Change the color of the recipe container background. Default is semi-transparent black.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); ItemNameColor = config<Color>("5 - Recipe Tracker (Color)", "Item Name Color (Color)", new Color(1f, 61f / 85f, 49f / 136f, 1f), new ConfigDescription("Change the color of the item name. Default is yellow.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); RecipeNameColorComplete = config<Color>("5 - Recipe Tracker (Color)", "Recipe Complete Name Color", Color.white, new ConfigDescription("Change the color of the item name. Default is yellow.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); RecipeNameColorInComplete = config<Color>("5 - Recipe Tracker (Color)", "Recipe Incomplete Name Color", new Color(1f, 1f, 1f, 0.192f), new ConfigDescription("Change the color of the item name. Default is yellow.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); RecipeCompleteColor = config<Color>("5 - Recipe Tracker (Color)", "Recipe Complete Color", new Color(0f, 1f, 0.44f, 0.37f), new ConfigDescription("Change the color of the text when the requirement is met. Default is green.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); RecipeIncompleteRightColor = config<Color>("5 - Recipe Tracker (Color)", "Recipe Incomplete Right Color", new Color(1f, 0.31f, 0f, 1f), new ConfigDescription("Change the color of the text when the requirement is not met. Default is red.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); RecipeIncompleteLeftColor = config<Color>("5 - Recipe Tracker (Color)", "Recipe Incomplete Left Color", Color.white, new ConfigDescription("Change the color of the text when the requirement is not met. Default is red.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); RecipeTrackerPanelScale = config<Vector2>("5 - Recipe Tracker (Sizes)", "Recipe Tracker Panel Scale", new Vector2(0.75f, 0.75f), new ConfigDescription("Change the scale of the recipe tracker panel. Default is 1.0f.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); RecipeTrackerItemNameMin = config("5 - Recipe Tracker (Sizes)", "Recipe Tracker Item Name Min", 12f, new ConfigDescription("Change the minimum size of the recipe tracker item name. Default is 12.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); RecipeTrackerItemNameMax = config("5 - Recipe Tracker (Sizes)", "Recipe Tracker Item Name Max", 20f, new ConfigDescription("Change the maximum size of the recipe tracker item name. Default is 20.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); RecipeTrackerReqNameMin = config("5 - Recipe Tracker (Sizes)", "Recipe Tracker Req Name Min", 12f, new ConfigDescription("Change the minimum size of the recipe tracker requirement name. Default is 12.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); RecipeTrackerReqNameMax = config("5 - Recipe Tracker (Sizes)", "Recipe Tracker Req Name Max", 20f, new ConfigDescription("Change the maximum size of the recipe tracker requirement name. Default is 20.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); RecipeTrackerPanelScale.SettingChanged += delegate { UpdateAllRecipesOnChange(); }; RecipeTrackerItemNameMin.SettingChanged += delegate { UpdateAllRecipesOnChange(); }; RecipeTrackerItemNameMax.SettingChanged += delegate { UpdateAllRecipesOnChange(); }; RecipeTrackerReqNameMin.SettingChanged += delegate { UpdateAllRecipesOnChange(); }; RecipeTrackerReqNameMax.SettingChanged += delegate { UpdateAllRecipesOnChange(); }; HeaderGlowColor.SettingChanged += delegate { UpdateAllRecipesOnChange(); }; HeaderBraidColor.SettingChanged += delegate { UpdateAllRecipesOnChange(); }; RecipeContainerBackgroundColor.SettingChanged += delegate { UpdateAllRecipesOnChange(); }; ItemNameColor.SettingChanged += delegate { UpdateAllRecipesOnChange(); }; RecipeNameColorComplete.SettingChanged += delegate { UpdateAllRecipesOnChange(); }; RecipeNameColorInComplete.SettingChanged += delegate { UpdateAllRecipesOnChange(); }; RecipeCompleteColor.SettingChanged += delegate { UpdateAllRecipesOnChange(); }; RecipeIncompleteRightColor.SettingChanged += delegate { UpdateAllRecipesOnChange(); }; RecipeIncompleteLeftColor.SettingChanged += delegate { UpdateAllRecipesOnChange(); }; CleanupOldConfigEntries(); LoadAssets(); Assembly executingAssembly = Assembly.GetExecutingAssembly(); harmony.PatchAll(executingAssembly); SetupWatcher(); } private static AssetBundle? GetAssetBundleFromResources(string filename) { try { Assembly executingAssembly = Assembly.GetExecutingAssembly(); string[] manifestResourceNames = executingAssembly.GetManifestResourceNames(); AntiArthriticCraftingLogger.LogIfBuildDebug("Checking for " + filename + "\nAvailable resources: " + string.Join(", ", manifestResourceNames)); string text = manifestResourceNames.SingleOrDefault((string str) => str.EndsWith(filename, StringComparison.OrdinalIgnoreCase)); if (text == null) { AntiArthriticCraftingLogger.LogError((object)("Resource '" + filename + "' not found in embedded resources.")); throw new InvalidOperationException("Resource '" + filename + "' not found."); } using Stream stream = executingAssembly.GetManifestResourceStream(text); if (stream != null) { AntiArthriticCraftingLogger.LogIfBuildDebug("Successfully loaded resource: " + text); return AssetBundle.LoadFromStream(stream); } AntiArthriticCraftingLogger.LogError((object)("Failed to load asset bundle stream for resource: " + text)); throw new InvalidOperationException("Failed to load asset bundle stream for resource: " + text); } catch (Exception ex) { AntiArthriticCraftingLogger.LogError((object)("Error loading AssetBundle '" + filename + "': " + ex.Message)); throw; } } private static byte[] ReadEmbeddedFileBytes(string name) { try { using MemoryStream memoryStream = new MemoryStream(); string name2 = Assembly.GetExecutingAssembly().GetName().Name + "." + name; using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name2); if (stream == null) { AntiArthriticCraftingLogger.LogError((object)("Embedded file '" + name + "' not found.")); throw new InvalidOperationException("Embedded file '" + name + "' not found."); } stream.CopyTo(memoryStream); AntiArthriticCraftingLogger.LogIfBuildDebug("Successfully read embedded file: " + name); return memoryStream.ToArray(); } catch (Exception ex) { AntiArthriticCraftingLogger.LogError((object)("Error reading embedded file '" + name + "': " + ex.Message)); throw; } } internal static Sprite loadSprite(string name, bool isEmbed = false) { //IL_002c: 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) Texture2D val = loadTexture(name, isEmbed); if (!((Object)(object)val != (Object)null)) { return null; } return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), Vector2.zero); } internal static Texture2D loadTexture(string name, bool isEmbed = false) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown Texture2D val = new Texture2D(0, 0); if (isEmbed) { ImageConversion.LoadImage(val, ReadEmbeddedFileBytes("assets." + name)); } else { string directoryName = Path.GetDirectoryName(Paths.ConfigPath); if (directoryName == null) { return val; } List<string> list = Directory.GetFiles(directoryName, "AAA_favorite.png", SearchOption.AllDirectories).OrderBy(Path.GetFileName).ToList(); try { byte[] array = File.ReadAllBytes(list.Find((string x) => x.Contains(name))); ImageConversion.LoadImage(val, array); } catch (Exception arg) { AntiArthriticCraftingLogger.LogWarning((object)$"The file {name} couldn't be found in the directory path {directoryName}. Please make sure you are naming the file AAA_favorite.png and it is located somewhere in the BepInEx/config folder.\n{arg}"); val = null; } } return val; } public void UpdateAllRecipesOnChange() { if (!((Object)(object)RecipeTrackerUIPrefab == (Object)null)) { RecipeTrackerUI.Instance.UpdateAllRecipes(); } } public static void LoadAssets() { Asset = GetAssetBundleFromResources("paginator"); Asset2 = GetAssetBundleFromResources("aaarecipetracker"); ShaderAssetBundle = GetAssetBundleFromResources("aaa_shader"); if ((Object)(object)ShaderAssetBundle != (Object)null) { AssetBundle? shaderAssetBundle = ShaderAssetBundle; overlayShader = ((shaderAssetBundle != null) ? shaderAssetBundle.LoadAsset<Shader>("OverlayWithHole") : null); if ((Object)(object)overlayShader != (Object)null) { AntiArthriticCraftingLogger.LogIfBuildDebug("Successfully loaded overlay shader"); ShaderAssetBundle.Unload(false); } else { AntiArthriticCraftingLogger.LogError((object)"Failed to load overlay shader"); } } } private void CleanupOldConfigEntries() { if (!(AccessTools.Property(((object)((BaseUnityPlugin)this).Config).GetType(), "OrphanedEntries")?.GetValue(((BaseUnityPlugin)this).Config) is IDictionary dictionary)) { return; } List<object> list = new List<object>(); foreach (DictionaryEntry item in dictionary) { AntiArthriticCraftingLogger.LogDebug((object)$"Removing orphaned config: {item.Key} = {item.Value}"); list.Add(item.Key); } foreach (object item2 in list) { dictionary.Remove(item2); } ((BaseUnityPlugin)this).Config.Save(); ((BaseUnityPlugin)this).Config.Reload(); } private void Start() { AssetLoadTracker.MapPrefabsToBundles(); AssetLoadTracker.MapBundlesToAssemblies(); if (API.IsLoaded()) { API.OnItemBreak(AzuAntiArthriticCrafting.Utilities.Utilities.OnItemBreak); } Chainloader.PluginInfos.TryGetValue("Azumatt.AzuCraftyBoxes", out var value); Chainloader.PluginInfos.TryGetValue("aedenthorn.CraftFromContainers", out var value2); Chainloader.PluginInfos.TryGetValue("com.odinplusqol.mod", out var value3); Chainloader.PluginInfos.TryGetValue("kwilson.TillValhalla", out var value4); Chainloader.PluginInfos.TryGetValue("randyknapp.mods.improvedbuildhud", out var value5); Chainloader.PluginInfos.TryGetValue("shudnal.MyLittleUI", out var value6); Chainloader.PluginInfos.TryGetValue("ZenDragon.ZenUI", out var value7); if (value != null && Object.op_Implicit((Object)(object)value.Instance)) { CfcLoaded = true; AzuCraftyBoxes.Init(value); } if (value3 != null && Object.op_Implicit((Object)(object)value3.Instance)) { CfcLoaded = true; } if (value2 != null && Object.op_Implicit((Object)(object)value2.Instance)) { CfcLoaded = true; } if (value4 != null && Object.op_Implicit((Object)(object)value4.Instance)) { CfcLoaded = true; } if (value5 != null && Object.op_Implicit((Object)(object)value5.Instance)) { RandyInstance = value5.Instance; } if (value6 != null && Object.op_Implicit((Object)(object)value6.Instance)) { ConfigEntry<bool> val = default(ConfigEntry<bool>); if (value6.Instance.Config.TryGetEntry<bool>("Item - Available resources amount", "Multicraft", ref val) && val.Value) { val.Value = false; } ConfigEntry<bool> val2 = default(ConfigEntry<bool>); if (value6.Instance.Config.TryGetEntry<bool>("Item - Crafting - Filter", "Enabled", ref val2) && val2.Value) { val2.Value = false; } value6.Instance.Config.Save(); } if (value7 != null && (Object)(object)value7.Instance != (Object)null) { bool flag = default(bool); foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in ((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)value7.Instance.Config).Where((KeyValuePair<ConfigDefinition, ConfigEntryBase> entry) => entry.Key.Section == "Crafting Panel" && entry.Value.SettingType == typeof(bool)).ToList()) { object boxedValue = item.Value.BoxedValue; int num; if (boxedValue is bool) { flag = (bool)boxedValue; num = 1; } else { num = 0; } if (((uint)num & (flag ? 1u : 0u)) != 0) { item.Value.BoxedValue = false; } } value7.Instance.Config.Save(); } if (RnR.IsLoaded()) { RnR.Init(); } } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); } private void SetupWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private void ReadConfigValues(object sender, FileSystemEventArgs e) { if (!File.Exists(ConfigFileFullPath)) { return; } try { AntiArthriticCraftingLogger.LogDebug((object)"ReadConfigValues called"); ((BaseUnityPlugin)this).Config.Reload(); } catch { AntiArthriticCraftingLogger.LogError((object)("There was an issue loading your " + ConfigFileName)); AntiArthriticCraftingLogger.LogError((object)"Please check your config entries for spelling and format!"); } } private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val); ConfigSync.AddConfigEntry<T>(val2).SynchronizedConfig = synchronizedSetting; return val2; } private ConfigEntry<T> config<T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting); } static AzuAntiArthriticCraftingPlugin() { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName; instance = null; ConnectionError = ""; harmony = new Harmony("Azumatt.AzuAntiArthriticCrafting"); Asset = null; Asset2 = null; ShaderAssetBundle = null; overlayShader = null; AntiArthriticCraftingLogger = Logger.CreateLogSource("AzuAntiArthriticCrafting"); ConfigSync = new ConfigSync("Azumatt.AzuAntiArthriticCrafting") { DisplayName = "AzuAntiArthriticCrafting", CurrentVersion = "2.1.11", MinimumRequiredVersion = "2.1.11" }; RecipeTrackerUIPrefab = null; RandyInstance = null; _serverConfigLocked = null; ResetCraftingValueOnRecChange = null; VanillaLike = null; GridSizeOption = null; Paginator = null; FavoritingSystem = null; IncrementalAmount = null; ShowMaxCraftAmountToggle = null; configNoCostLimitRecipesToStation = null; configNoCostRespectStationLevel = null; OverrideCraftingDuration = null; CraftingDuration = null; RequirementTextFormatting = null; InputEnabledText = null; InputDisabledText = null; InputTextColor = null; MinusKeybind = null; ToggleUIKeyBind = null; MaxCraftModifier = null; IncrementalModifier = null; FavoriteToggle = null; HeaderGlowColor = null; HeaderBraidColor = null; RecipeContainerBackgroundColor = null; ItemNameColor = null; RecipeNameColorComplete = null; RecipeNameColorInComplete = null; RecipeCompleteColor = null; RecipeIncompleteRightColor = null; RecipeIncompleteLeftColor = null; RecipeTrackerPanelScale = null; RecipeTrackerItemNameMin = null; RecipeTrackerItemNameMax = null; RecipeTrackerReqNameMin = null; RecipeTrackerReqNameMax = null; RecipeTrackerPanelPosition = null; } } public static class KeyboardExtensions { public static bool IsKeyDown(this KeyboardShortcut shortcut) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKeyDown(((KeyboardShortcut)(ref shortcut)).MainKey)) { return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey); } return false; } public static bool IsKeyHeld(this KeyboardShortcut shortcut) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKey(((KeyboardShortcut)(ref shortcut)).MainKey)) { return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey); } return false; } } public static class LoggingExtensions { public static void LogIfBuildDebug(this ManualLogSource logger, string message) { } public static void LogErrorIfBuildDebug(this ManualLogSource logger, string message) { } } public static class ToggleExtensions { public static bool IsOn(this ConfigEntry<AzuAntiArthriticCraftingPlugin.Toggle> toggle) { return toggle.Value == AzuAntiArthriticCraftingPlugin.Toggle.On; } public static bool IsOff(this ConfigEntry<AzuAntiArthriticCraftingPlugin.Toggle> toggle) { return toggle.Value == AzuAntiArthriticCraftingPlugin.Toggle.Off; } } } namespace AzuAntiArthriticCrafting.Utilities { public class AssetLoadTracker { private static readonly Dictionary<string, string> PrefabToBundleMapping = new Dictionary<string, string>(); private static readonly Dictionary<string, Assembly> BundleToAssemblyMapping = new Dictionary<string, Assembly>(); internal static void MapPrefabsToBundles() { foreach (AssetBundle allLoadedAssetBundle in AssetBundle.GetAllLoadedAssetBundles()) { foreach (string item in from name in allLoadedAssetBundle.GetAllAssetNames() where name.EndsWith(".prefab") select name) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(item); PrefabToBundleMapping[fileNameWithoutExtension] = ((Object)allLoadedAssetBundle).name; AzuAntiArthriticCraftingPlugin.AntiArthriticCraftingLogger.LogErrorIfBuildDebug("Mapped original name " + item + " [" + fileNameWithoutExtension + "] to " + ((Object)allLoadedAssetBundle).name); } } } internal static void MapBundlesToAssemblies() { List<Assembly> list = Chainloader.PluginInfos.Select((KeyValuePair<string, PluginInfo> keyValuePair) => ((object)keyValuePair.Value.Instance).GetType().Assembly).ToList(); foreach (string bundleName in PrefabToBundleMapping.Values.Distinct()) { foreach (Assembly item in list) { try { if (item.GetManifestResourceNames().Any((string resourceName) => resourceName.EndsWith(bundleName))) { BundleToAssemblyMapping[bundleName] = item; break; } } catch (Exception arg) { AzuAntiArthriticCraftingPlugin.AntiArthriticCraftingLogger.LogError((object)$"Error while getting manifest resource names for assembly {item.GetName().Name}: {arg}"); } } } } public static Assembly? GetAssemblyForPrefab(string prefabName) { if (PrefabToBundleMapping.TryGetValue(prefabName, out string value) && BundleToAssemblyMapping.TryGetValue(value, out Assembly value2)) { return value2; } return null; } public static string GetBundleForPrefab(string prefabName) { if (!PrefabToBundleMapping.TryGetValue(prefabName, out string value)) { return ""; } return value; } } public class DragWindowCntrl : MonoBehaviour, IBeginDragHandler, IEventSystemHandler, IDragHandler, IEndDragHandler { private RectTransform _window; private Vector2 _delta; public static void ApplyDragWindowCntrl(GameObject go) { go.AddComponent<DragWindowCntrl>(); } private void Awake() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown _window = (RectTransform)((Component)this).transform; } private void Start() { //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_0011: Unknown result type (might be due to invalid IL or missing references) Vector2 value = AzuAntiArthriticCraftingPlugin.RecipeTrackerPanelPosition.Value; _window.anchoredPosition = value; } public void OnBeginDrag(PointerEventData eventData) { //IL_0011: 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_002c: 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_0036: Unknown result type (might be due to invalid IL or missing references) Transform parent = ((Transform)_window).parent; Vector2 val = default(Vector2); RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)(object)((parent is RectTransform) ? parent : null), eventData.position, eventData.pressEventCamera, ref val); _delta = val - _window.anchoredPosition; } public void OnDrag(PointerEventData eventData) { //IL_0011: 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_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) Transform parent = ((Transform)_window).parent; Vector2 val = default(Vector2); if (RectTransformUtility.ScreenPointToLocalPointInRectangle((RectTransform)(object)((parent is RectTransform) ? parent : null), eventData.position, eventData.pressEventCamera, ref val)) { Vector2 anchoredPosition = val - _delta; _window.anchoredPosition = anchoredPosition; } } public void OnEndDrag(PointerEventData eventData) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) AzuAntiArthriticCraftingPlugin.RecipeTrackerPanelPosition.Value = _window.anchoredPosition; } public void ResetToDefaultPosition() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) _window.anchoredPosition = AzuAntiArthriticCraftingPlugin.RecipeTrackerPanelPosition.Value; } } public abstract class Utilities { private static string _name = ""; internal static readonly Dictionary<string, Sprite> SpriteCache = new Dictionary<string, Sprite>(); public static string Name { get { return _name; } set { if (!(Name == value)) { _name = value; UnityEvent onRecipeChange = InventoryGuiShowCraftingPanelPatch.OnRecipeChange; if (onRecipeChange != null) { onRecipeChange.Invoke(); } ClearRequirements(); } } } public static void AddToUIGroupHandlers(UIGroupHandler newGroup) { if (!((Object)(object)InventoryGui.instance == (Object)null) && !((Object)(object)newGroup == (Object)null)) { UIGroupHandler[] uiGroups = InventoryGui.instance.m_uiGroups; UIGroupHandler[] array = (UIGroupHandler[])(object)new UIGroupHandler[uiGroups.Length + 1]; Array.Copy(uiGroups, array, uiGroups.Length); array[uiGroups.Length] = newGroup; InventoryGui.instance.m_uiGroups = array; Debug.Log((object)$"Successfully added a new UIGroupHandler. Total count: {array.Length}"); } } public static void AddCompToRequirement(Transform elementRoot, Requirement requirement) { NoCostReqHandler component = ((Component)elementRoot).GetComponent<NoCostReqHandler>(); if ((Object)(object)component == (Object)null) { component = ((Component)elementRoot).gameObject.AddComponent<NoCostReqHandler>(); component.m_requirement = requirement; } else { component.m_requirement = requirement; } } public static void ResetAacCrafting() { } public static void CancelCrafting() { InventoryGuiShowCraftingPanelPatch.WasCrafting = false; if (Object.op_Implicit((Object)(object)InventoryGui.instance) && InventoryGui.instance.InCraftTab()) { if (AzuAntiArthriticCraftingPlugin.ResetCraftingValueOnRecChange.IsOff()) { InventoryGuiShowCraftingPanelPatch.OnCraftAmountChanged(InventoryGui.instance, AAACraft.inputAmount.text); } UnblockInput(); } } public static bool OnItemBreak(ItemData? containerItem) { CancelCrafting(); return true; } public static void OnCraftButtonPressed() { StartCraftingLogic(); BlockInput(upgradeTab: false); } public static void OnCraftCancelledButtonPressed() { CancelCrafting(); } public static void TabCraftPressed() { UnblockInput(); ResetAacCrafting(); } public static void UpgradeTabPressed() { BlockInput(upgradeTab: true); ResetAacCrafting(); } public static void StartCraftingLogic() { if (InventoryGuiShowCraftingPanelPatch.CurrentCraftAmount <= 0) { AAACraft.inputAmount.text = ""; CancelCrafting(); } else { InventoryGuiShowCraftingPanelPatch.WasCrafting = true; InventoryGuiShowCraftingPanelPatch.WaitUpdates = 5; } } public static void BlockInput(bool upgradeTab) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) InputField val = (((Object)(object)AAACraft.inputAmount != (Object)null) ? ((Component)AAACraft.inputAmount).GetComponent<InputField>() : null); if (!((Object)(object)val == (Object)null)) { ((Selectable)val).interactable = false; ((Behaviour)val).enabled = false; if (upgradeTab) { InventoryGuiShowCraftingPanelPatch.aacParent.SetActive(false); } else { UpdatePlaceholder(val, AzuAntiArthriticCraftingPlugin.InputDisabledText.Value, Color.red); } } } public static void UnblockInput() { //IL_0049: Unknown result type (might be due to invalid IL or missing references) InputField val = (((Object)(object)AAACraft.inputAmount != (Object)null) ? ((Component)AAACraft.inputAmount).GetComponent<InputField>() : null); if (!((Object)(object)val == (Object)null)) { InventoryGuiShowCraftingPanelPatch.aacParent.SetActive(true); ((Selectable)val).interactable = true; ((Behaviour)val).enabled = true; UpdatePlaceholder(val, AzuAntiArthriticCraft
plugins/HBK-HBKHEIM/Belts-1.1.7/Belts.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using ItemManager; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using SoftReferenceableAssets; using Soldiers.Patches; using StatusEffectManager; using TMPro; using UnityEngine; using UnityEngine.UI; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.BufferedDeserialization; using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; [assembly: ComVisible(false)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Guid("E0E2F92E-557C-4A05-9D89-AA92A0BD75C4")] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyFileVersion("1.1.6")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("coemt")] [assembly: AssemblyProduct("Belts")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: AssemblyTitle("Belts")] [assembly: AssemblyDescription("")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.6.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<005d9fd9-3987-4a0c-afdb-b6483ef039b9>Embedded] internal sealed class <005d9fd9-3987-4a0c-afdb-b6483ef039b9>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [<005d9fd9-3987-4a0c-afdb-b6483ef039b9>Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class <ceb323af-b840-4258-961e-1c015a8e52db>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <ceb323af-b840-4258-961e-1c015a8e52db>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <ceb323af-b840-4258-961e-1c015a8e52db>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [<005d9fd9-3987-4a0c-afdb-b6483ef039b9>Embedded] [CompilerGenerated] internal sealed class <09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContextAttribute : Attribute { public readonly byte Flag; public <09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace Soldiers.Patches { public class SE_ModifyStats : StatusEffect { public float Health; public float Stamina; private float maxClampValue = 999f; private static float _baseEitr; private static float _origHealth; private static float _origStamina; [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] public override void Setup(Character character) { Player val = (Player)(object)((character is Player) ? character : null); if ((Object)(object)val != (Object)null) { if (_origHealth != 0f) { _origHealth = val.m_baseHP; } if (_origStamina != 0f) { _origStamina = val.m_baseStamina; } val.m_baseHP += Health; val.m_baseStamina += Stamina; } ((StatusEffect)this).Setup(character); } public override void Stop() { Character character = base.m_character; Player val = (Player)(object)((character is Player) ? character : null); if ((Object)(object)val != (Object)null) { val.m_baseHP = Mathf.Clamp(val.m_baseHP - Health, _origHealth, maxClampValue); val.m_baseStamina = Mathf.Clamp(val.m_baseStamina - Stamina, _origStamina, maxClampValue); } ((StatusEffect)this).Stop(); } } } namespace Belts { [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] [BepInPlugin("coemt.Belts", "Belts", "1.1.6")] public class BeltsPlugin : BaseUnityPlugin { [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] public enum Toggle { On = 1, Off = 0 } [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order = null; [UsedImplicitly] public bool? Browsable = null; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] [UsedImplicitly] public string Category = null; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(new byte[] { 2, 1 })] [UsedImplicitly] public Action<ConfigEntryBase> CustomDrawer = null; } [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] private class AcceptableShortcuts : AcceptableValueBase { public AcceptableShortcuts() : base(typeof(KeyboardShortcut)) { } public override object Clamp(object value) { return value; } public override bool IsValid(object value) { return true; } public override string ToDescriptionString() { return "# Acceptable values: " + string.Join(", ", UnityInput.Current.SupportedKeyCodes); } } internal const string ModName = "Belts"; internal const string ModVersion = "1.1.6"; internal const string Author = "coemt"; private const string ModGUID = "coemt.Belts"; private static string ConfigFileName = "coemt.Belts.cfg"; private static string ConfigFileFullPath; internal static string ConnectionError; private readonly Harmony _harmony = new Harmony("coemt.Belts"); public static readonly ManualLogSource BeltsLogger; private static readonly ConfigSync ConfigSync; public Texture2D tex = null; private static ConfigEntry<Toggle> _serverConfigLocked; public void Awake() { bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; _serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only."); ConfigSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked); CustomSE customSE = new CustomSE("CoemtsClasp"); CustomSE customSE2 = new CustomSE("Hermods"); CustomSE customSE3 = new CustomSE("MuninsCrest"); CustomSE customSE4 = new CustomSE("AskvinBelt"); Item item = new Item("belts", "OdinsBuckle"); item.Name.English("Odin's Buckle").German("Odins Schnalle"); item.Description.English("A sturdy belt").German("Ein robuster Gürtel."); item.Crafting.Add(CraftingTable.Disabled, 1); item.Trade.Price = 500u; item.Trade.Stack = 1u; item.Trade.Trader = Trader.Haldor; Item item2 = new Item("belts", "Hermods"); item2.Name.English("Hermod's Girdle").German("Hermods Gurt"); item2.Description.English("A forgotten gear found on his journey to Hel, just keep it.").German("Eine vergessene Ausrüstung, gefunden auf seiner Reise nach Hel. Behalte sie einfach."); item2.Crafting.Add(CraftingTable.Disabled, 1); item2.Trade.Price = 1000u; item2.Trade.Stack = 1u; item2.Trade.Trader = Trader.Haldor; Item item3 = new Item("belts", "MuninsCrest"); item3.Name.English("Munnin's Crest").German("Munins Wappen"); item3.Description.English("The spirit of Hugin's brother was sealed within this crest. Glide lightly and illuminate your path.").German("Der Geist von Hugins Bruder wurde in diesem Wappen versiegelt. Gleite sanft und erleuchte deinen Weg."); item3.Crafting.Add(CraftingTable.Disabled, 4); item3.RequiredItems.Add("YagluthDrop", 2); item3.RequiredItems.Add("ScaleHide", 2); item3.RequiredItems.Add("Carapace", 1); item3.Trade.Price = 1750u; item3.Trade.Stack = 1u; item3.Trade.Trader = Trader.Hildir; Item item4 = new Item("belts", "AskvinBelt"); item4.Name.English("Askvin Belt").German("Askvin-Gürtel"); item4.Description.English("Smooth and scaly, providing you less resistance in the wind").German("Glatt und schuppig, bietet dir weniger Widerstand im Wind."); item4.Crafting.Add(CraftingTable.Disabled, 5); item4.RequiredItems.Add("AskHide", 10); item4.RequiredItems.Add("Eitr", 5); item4.RequiredItems.Add("Feathers", 15); item4.Trade.Price = 2500u; item4.Trade.Stack = 1u; item4.Trade.Trader = Trader.Hildir; Item item5 = new Item("belts", "EirsSash"); item5.Name.English("Eir's Sash"); item5.Name.Portuguese_Brazilian("Cinta de Eir"); item5.Name.German("Eirs Gürtel"); item5.Name.Chinese("艾尔的腰带"); item5.Name.Spanish("Faja de Eir"); item5.Description.English("Even the maidens of Lyfjaberg are astonished by the power of this sash."); item5.Description.Portuguese_Brazilian("Até as donzelas de Lyfjaberg se impressionam com o poder dessa cinta."); item5.Description.German("Sogar die Jungfrauen von Lyfjaberg sind von der Kraft dieses Gürtels erstaunt."); item5.Description.Chinese("就连Lyfjaberg的少女们也对这条腰带的力量感到惊讶。"); item5.Description.Spanish("Incluso las doncellas de Lyfjaberg están asombradas por el poder de esta faja."); item5.Crafting.Add(CraftingTable.Disabled, 1); item5.Trade.Price = 1000u; item5.Trade.Stack = 1u; item5.Trade.Trader = Trader.Hildir; SetupBelt_ModifyStatsBy(item5.Prefab, 25f, 20f); new ItemManager.LocalizeKey("$se_belts_coemtsclasp").English("Odin's Buckle").German("Odins Schnalle"); item.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_equipStatusEffect.m_name = "$se_belts_coemtsclasp"; new ItemManager.LocalizeKey("$se_belts_coemtsclasp_tooltip").English("Fits tightly around your waist and offers a sneaky bonus").German("Sitzt eng um deine Taille und bietet einen heimlichen Bonus."); item.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_equipStatusEffect.m_tooltip = "$se_belts_coemtsclasp_tooltip"; new ItemManager.LocalizeKey("$se_belts_hermods").English("Hermod's Girdle").German("Hermods Gurt"); item2.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_equipStatusEffect.m_name = "$se_belts_hermods"; new ItemManager.LocalizeKey("$se_belts_muninscrest").English("Munin's Crest").German("Munins Wappen"); item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_equipStatusEffect.m_name = "$se_belts_muninscrest"; new ItemManager.LocalizeKey("$se_belts_muninscrest_tooltip").English("Nearly the power of flight bestowed upon you").German("Fast die Kraft des Fliegens wird dir verliehen."); item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_equipStatusEffect.m_tooltip = "$se_belts_muninscrest_tooltip"; new ItemManager.LocalizeKey("$se_belts_askvinbelt").English("Askvin Belt").German("Askvin-Gürtel"); item4.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_equipStatusEffect.m_name = "$se_belts_askvinbelt"; new ItemManager.LocalizeKey("$se_belts_askvinbelt_tooltip").English("A powerful force seems to be at your back").German("Eine mächtige Kraft scheint dir Rückenwind zu geben."); item4.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_equipStatusEffect.m_tooltip = "$se_belts_askvinbelt_tooltip"; new ItemManager.LocalizeKey("$se_belts_eirssash").English("Eir's Sash").German("Eirs Gürtel"); new ItemManager.LocalizeKey("$se_belts_eirssash_tooltip").English("+25 Health\n+20 Stamina").German("+25 Lebenspunkte\n+20 Ausdauer"); StatusEffect equipStatusEffect = item4.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_equipStatusEffect; SE_Stats val = (SE_Stats)(object)((equipStatusEffect is SE_Stats) ? equipStatusEffect : null); if (val != null) { val.m_windMovementModifier = 0.5f; } Assembly executingAssembly = Assembly.GetExecutingAssembly(); _harmony.PatchAll(executingAssembly); SetupWatcher(); if (saveOnConfigSet) { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; ((BaseUnityPlugin)this).Config.Save(); } } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); } public static void SetupBelt_ModifyStatsBy(GameObject prefab, float health = 0f, float stamina = 0f, float eitr = 0f) { ItemDrop component = prefab.GetComponent<ItemDrop>(); ItemData val = (((Object)(object)component != (Object)null) ? component.m_itemData : null); if (val == null) { throw new ArgumentNullException("prefab"); } ItemData val2 = val; SE_ModifyStats sE_ModifyStats = ScriptableObject.CreateInstance<SE_ModifyStats>(); if (!((Object)(object)sE_ModifyStats == (Object)null)) { ((Object)sE_ModifyStats).name = "BeltModifyStats"; ((StatusEffect)sE_ModifyStats).m_name = "$se_belts_eirssash"; ((StatusEffect)sE_ModifyStats).m_icon = val2.GetIcon(); ((StatusEffect)sE_ModifyStats).m_tooltip = "$se_belts_eirssash_tooltip"; sE_ModifyStats.Health = health; sE_ModifyStats.Stamina = stamina; val2.m_shared.m_equipStatusEffect = (StatusEffect)(object)sE_ModifyStats; } } private void SetupWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private void ReadConfigValues(object sender, FileSystemEventArgs e) { if (!File.Exists(ConfigFileFullPath)) { return; } try { BeltsLogger.LogDebug((object)"ReadConfigValues called"); ((BaseUnityPlugin)this).Config.Reload(); } catch { BeltsLogger.LogError((object)("There was an issue loading your " + ConfigFileName)); BeltsLogger.LogError((object)"Please check your config entries for spelling and format!"); } } private ConfigEntry<T> config<[<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val); SyncedConfigEntry<T> syncedConfigEntry = ConfigSync.AddConfigEntry<T>(val2); syncedConfigEntry.SynchronizedConfig = synchronizedSetting; return val2; } private ConfigEntry<T> config<[<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting); } static BeltsPlugin() { string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName; ConnectionError = ""; BeltsLogger = Logger.CreateLogSource("Belts"); ConfigSync = new ConfigSync("coemt.Belts") { DisplayName = "Belts", CurrentVersion = "1.1.6", MinimumRequiredVersion = "1.1.6" }; _serverConfigLocked = null; } } public static class KeyboardExtensions { public static bool IsKeyDown(this KeyboardShortcut shortcut) { //IL_0003: 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) return (int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKeyDown(((KeyboardShortcut)(ref shortcut)).MainKey) && ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey); } public static bool IsKeyHeld(this KeyboardShortcut shortcut) { //IL_0003: 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) return (int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKey(((KeyboardShortcut)(ref shortcut)).MainKey) && ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey); } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] public static class RegisterAndCheckVersion { [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] private static void Prefix(ZNetPeer peer, ref ZNet __instance) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown BeltsPlugin.BeltsLogger.LogDebug((object)"Registering version RPC handler"); peer.m_rpc.Register<ZPackage>("Belts_VersionCheck", (Action<ZRpc, ZPackage>)RpcHandlers.RPC_Belts_Version); BeltsPlugin.BeltsLogger.LogDebug((object)"Invoking version check"); ZPackage val = new ZPackage(); val.Write("1.1.6"); peer.m_rpc.Invoke("Belts_VersionCheck", new object[1] { val }); } } [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] public static class VerifyClient { private static bool Prefix(ZRpc rpc, ZPackage pkg, ref ZNet __instance) { if (!__instance.IsServer() || RpcHandlers.ValidatedPeers.Contains(rpc)) { return true; } BeltsPlugin.BeltsLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") never sent version or couldn't due to previous disconnect, disconnecting")); rpc.Invoke("Error", new object[1] { 3 }); return false; } private static void Postfix(ZNet __instance) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "BeltsRequestAdminSync", new object[1] { (object)new ZPackage() }); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] public class ShowConnectionError { [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] private static void Postfix(FejdStartup __instance) { if (__instance.m_connectionFailedPanel.activeSelf) { __instance.m_connectionFailedError.fontSizeMax = 25f; __instance.m_connectionFailedError.fontSizeMin = 15f; TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + BeltsPlugin.ConnectionError; } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] public static class RemoveDisconnectedPeerFromVerified { [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] private static void Prefix(ZNetPeer peer, ref ZNet __instance) { if (__instance.IsServer()) { BeltsPlugin.BeltsLogger.LogInfo((object)("Peer (" + peer.m_rpc.m_socket.GetHostName() + ") disconnected, removing from validated list")); RpcHandlers.ValidatedPeers.Remove(peer.m_rpc); } } } [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] public static class RpcHandlers { public static readonly List<ZRpc> ValidatedPeers = new List<ZRpc>(); public static void RPC_Belts_Version(ZRpc rpc, ZPackage pkg) { string text = pkg.ReadString(); BeltsPlugin.BeltsLogger.LogInfo((object)("Version check, local: 1.1.6, remote: " + text)); if (text != "1.1.6") { BeltsPlugin.ConnectionError = "Belts Installed: 1.1.6\n Needed: " + text; if (ZNet.instance.IsServer()) { BeltsPlugin.BeltsLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") has incompatible version, disconnecting...")); rpc.Invoke("Error", new object[1] { 3 }); } } else if (!ZNet.instance.IsServer()) { BeltsPlugin.BeltsLogger.LogInfo((object)"Received same version from server!"); } else { BeltsPlugin.BeltsLogger.LogInfo((object)("Adding peer (" + rpc.m_socket.GetHostName() + ") to validated list")); ValidatedPeers.Add(rpc); } } } } namespace StatusEffectManager { [PublicAPI] [Description("The ItemDrop effect to apply the status effect")] public enum EffectType { Equip, Attack, Consume, Set } public struct SE_Item { [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(1)] public StatusEffect Effect; public EffectType Type; } [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] [PublicAPI] public class CustomSE { private static readonly List<CustomSE> RegisteredEffects = new List<CustomSE>(); private static readonly Dictionary<StatusEffect, CustomSE> CustomEffectMap = new Dictionary<StatusEffect, CustomSE>(); internal static readonly List<StatusEffect> CustomSEs = new List<StatusEffect>(); internal static readonly Dictionary<SE_Item, string> AddToPrefabs = new Dictionary<SE_Item, string>(); [Description("Instance of the StatusEffect.")] public readonly StatusEffect Effect; public EffectType Type; private string _folderName = "icons"; private AssetBundle _assetBundle = null; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] [Description("Sets the icon for the StatusEffect. Must be 64x64")] public Sprite IconSprite = null; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private string IconName = null; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private LocalizeKey _name; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private static Localization _english; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private static BaseUnityPlugin _plugin; private static bool hasConfigSync = true; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private static object _configSync; [Description("Sets the icon for the StatusEffect. Must be 64x64")] [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] public string Icon { [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(2)] get { return IconName; } [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(2)] set { IconName = value; IconSprite = ((IconName == null) ? null : loadSprite(IconName)); Effect.m_icon = IconSprite; } } [Description("Sets the in-game name for the StatusEffect")] public LocalizeKey Name { get { LocalizeKey name = _name; if (name != null) { return name; } StatusEffect effect = Effect; if (effect.m_name.StartsWith("$")) { _name = new LocalizeKey(effect.m_name); } else { string text = "$statuseffect_" + ((Object)Effect).name.Replace(" ", "_"); _name = new LocalizeKey(text).English(effect.m_name); effect.m_name = text; } return _name; } } private static Localization english { get { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown if (_english == null) { _english = new Localization(); _english.SetupLanguage("English"); } return _english; } } private static BaseUnityPlugin plugin { get { //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Expected O, but got Unknown if (_plugin == null) { IEnumerable<TypeInfo> source; try { source = Assembly.GetExecutingAssembly().DefinedTypes.ToList(); } catch (ReflectionTypeLoadException ex) { source = from t in ex.Types where t != null select t.GetTypeInfo(); } _plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); } return _plugin; } } [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private static object configSync { [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(2)] get { if (_configSync == null && hasConfigSync) { Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync"); if ((object)type != null) { _configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " ItemManager"); type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString()); type.GetProperty("IsLocked").SetValue(_configSync, true); } else { hasConfigSync = false; } } return _configSync; } } public CustomSE(string assetBundleFileName, string customEffectName, string folderName = "assets") : this(EffectManager.RegisterAssetBundle(assetBundleFileName, folderName), customEffectName) { } public CustomSE(AssetBundle bundle, string customEffectName) { Effect = EffectManager.RegisterCustomSE(bundle, customEffectName); RegisteredEffects.Add(this); CustomEffectMap[Effect] = this; } public CustomSE(string customEffectName) { Effect = ScriptableObject.CreateInstance<StatusEffect>(); EffectManager.RegisterCustomSE(Effect, customEffectName); RegisteredEffects.Add(this); CustomEffectMap[Effect] = this; } [return: <ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private byte[] ReadEmbeddedFileBytes(string name) { using MemoryStream memoryStream = new MemoryStream(); Stream manifestResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + ((_folderName == "") ? "" : ".") + _folderName + "." + name); if (manifestResourceStream == null) { return null; } manifestResourceStream.CopyTo(memoryStream); return memoryStream.ToArray(); } [return: <ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private Texture2D loadTexture(string name) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown byte[] array = ReadEmbeddedFileBytes(name); if (array != null) { Texture2D val = new Texture2D(0, 0); ImageConversion.LoadImage(val, array); return val; } return null; } private Sprite loadSprite(string name) { //IL_0027: 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) Texture2D val = loadTexture(name); if (val != null) { return Sprite.Create(val, new Rect(0f, 0f, 64f, 64f), Vector2.zero); } AssetBundle assetBundle = _assetBundle; Sprite val2 = ((assetBundle != null) ? assetBundle.LoadAsset<Sprite>(name) : null); if (val2 != null) { return val2; } throw new FileNotFoundException("Could not find a file named " + name + " for the effect icon"); } public void AddSEToPrefab(CustomSE customSE, string prefabName) { SE_Item key = new SE_Item { Effect = customSE.Effect, Type = customSE.Type }; AddToPrefabs.Add(key, prefabName); } private static ConfigEntry<T> config<[<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] T>(string group, string name, T value, ConfigDescription description) { ConfigEntry<T> val = plugin.Config.Bind<T>(group, name, value, description); configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T)) .Invoke(configSync, new object[1] { val }); return val; } private static ConfigEntry<T> config<[<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] T>(string group, string name, T value, string description) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())); } } [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] [PublicAPI] public class LocalizeKey { public readonly string Key; public LocalizeKey(string key) { Key = key.Replace("$", ""); } public LocalizeKey English(string key) { return addForLang("English", key); } public LocalizeKey Swedish(string key) { return addForLang("Swedish", key); } public LocalizeKey French(string key) { return addForLang("French", key); } public LocalizeKey Italian(string key) { return addForLang("Italian", key); } public LocalizeKey German(string key) { return addForLang("German", key); } public LocalizeKey Spanish(string key) { return addForLang("Spanish", key); } public LocalizeKey Russian(string key) { return addForLang("Russian", key); } public LocalizeKey Romanian(string key) { return addForLang("Romanian", key); } public LocalizeKey Bulgarian(string key) { return addForLang("Bulgarian", key); } public LocalizeKey Macedonian(string key) { return addForLang("Macedonian", key); } public LocalizeKey Finnish(string key) { return addForLang("Finnish", key); } public LocalizeKey Danish(string key) { return addForLang("Danish", key); } public LocalizeKey Norwegian(string key) { return addForLang("Norwegian", key); } public LocalizeKey Icelandic(string key) { return addForLang("Icelandic", key); } public LocalizeKey Turkish(string key) { return addForLang("Turkish", key); } public LocalizeKey Lithuanian(string key) { return addForLang("Lithuanian", key); } public LocalizeKey Czech(string key) { return addForLang("Czech", key); } public LocalizeKey Hungarian(string key) { return addForLang("Hungarian", key); } public LocalizeKey Slovak(string key) { return addForLang("Slovak", key); } public LocalizeKey Polish(string key) { return addForLang("Polish", key); } public LocalizeKey Dutch(string key) { return addForLang("Dutch", key); } public LocalizeKey Portuguese_European(string key) { return addForLang("Portuguese_European", key); } public LocalizeKey Portuguese_Brazilian(string key) { return addForLang("Portuguese_Brazilian", key); } public LocalizeKey Chinese(string key) { return addForLang("Chinese", key); } public LocalizeKey Japanese(string key) { return addForLang("Japanese", key); } public LocalizeKey Korean(string key) { return addForLang("Korean", key); } public LocalizeKey Hindi(string key) { return addForLang("Hindi", key); } public LocalizeKey Thai(string key) { return addForLang("Thai", key); } public LocalizeKey Abenaki(string key) { return addForLang("Abenaki", key); } public LocalizeKey Croatian(string key) { return addForLang("Croatian", key); } public LocalizeKey Georgian(string key) { return addForLang("Georgian", key); } public LocalizeKey Greek(string key) { return addForLang("Greek", key); } public LocalizeKey Serbian(string key) { return addForLang("Serbian", key); } public LocalizeKey Ukrainian(string key) { return addForLang("Ukrainian", key); } private LocalizeKey addForLang(string lang, string value) { if (Localization.instance.GetSelectedLanguage() == lang) { Localization.instance.AddWord(Key, value); } else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key)) { Localization.instance.AddWord(Key, value); } return this; } } [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] public static class EffectManager { [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] private struct BundleId { [UsedImplicitly] public string assetBundleFileName; [UsedImplicitly] public string folderName; } private static readonly Dictionary<BundleId, AssetBundle> bundleCache; static EffectManager() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown bundleCache = new Dictionary<BundleId, AssetBundle>(); Harmony val = new Harmony("org.bepinex.helpers.StatusEffectManager"); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(EffectManager), "Patch_ObjectDBInit", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNetScene), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(EffectManager), "Patch_ZNetSceneAwake", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static AssetBundle RegisterAssetBundle(string assetBundleFileName, string folderName = "assets") { BundleId key = new BundleId { assetBundleFileName = assetBundleFileName, folderName = folderName }; if (!bundleCache.TryGetValue(key, out var value)) { Dictionary<BundleId, AssetBundle> dictionary = bundleCache; AssetBundle? obj = ((IEnumerable<AssetBundle>)Resources.FindObjectsOfTypeAll<AssetBundle>()).FirstOrDefault((Func<AssetBundle, bool>)([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (AssetBundle a) => ((Object)a).name == assetBundleFileName)) ?? AssetBundle.LoadFromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + ((folderName == "") ? "" : ".") + folderName + "." + assetBundleFileName)); AssetBundle result = obj; dictionary[key] = obj; return result; } return value; } public static StatusEffect RegisterCustomSE(string assetBundleFileName, string customEffectName, string folderName = "assets") { return RegisterCustomSE(RegisterAssetBundle(assetBundleFileName, folderName), customEffectName); } public static StatusEffect RegisterCustomSE(AssetBundle assets, string customEffectName) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown StatusEffect val = (StatusEffect)assets.LoadAsset<ScriptableObject>(customEffectName); CustomSE.CustomSEs.Add(val); return val; } public static StatusEffect RegisterCustomSE(StatusEffect customSE, string customEffectName) { ((Object)customSE).name = customEffectName; CustomSE.CustomSEs.Add(customSE); return customSE; } [HarmonyPriority(700)] private static void Patch_ObjectDBInit(ObjectDB __instance) { foreach (StatusEffect customSE in CustomSE.CustomSEs) { if (!__instance.m_StatusEffects.Contains(customSE)) { __instance.m_StatusEffects.Add(customSE); } } __instance.UpdateRegisters(); } [HarmonyPriority(700)] private static void Patch_ZNetSceneAwake(ZNetScene __instance) { foreach (KeyValuePair<SE_Item, string> addToPrefab in CustomSE.AddToPrefabs) { try { GameObject prefab = __instance.GetPrefab(addToPrefab.Value); ItemDrop val = (Object.op_Implicit((Object)(object)prefab) ? prefab.GetComponent<ItemDrop>() : prefab.GetComponentInChildren<ItemDrop>()); Aoe val2 = (Object.op_Implicit((Object)(object)prefab) ? prefab.GetComponent<Aoe>() : prefab.GetComponentInChildren<Aoe>()); EffectArea val3 = (Object.op_Implicit((Object)(object)prefab) ? prefab.GetComponent<EffectArea>() : prefab.GetComponentInChildren<EffectArea>()); if (Object.op_Implicit((Object)(object)val)) { switch (addToPrefab.Key.Type) { case EffectType.Equip: val.m_itemData.m_shared.m_equipStatusEffect = addToPrefab.Key.Effect; break; case EffectType.Attack: val.m_itemData.m_shared.m_attackStatusEffect = addToPrefab.Key.Effect; break; case EffectType.Consume: val.m_itemData.m_shared.m_consumeStatusEffect = addToPrefab.Key.Effect; break; case EffectType.Set: val.m_itemData.m_shared.m_setSize = 1; val.m_itemData.m_shared.m_setName = ((Object)addToPrefab.Key.Effect).name; val.m_itemData.m_shared.m_setStatusEffect = addToPrefab.Key.Effect; break; default: throw new ArgumentOutOfRangeException(); } } else if (Object.op_Implicit((Object)(object)val2)) { val2.m_statusEffect = ((Object)addToPrefab.Key.Effect).name; } else if (Object.op_Implicit((Object)(object)val3)) { val3.m_statusEffect = ((Object)addToPrefab.Key.Effect).name; } else { Debug.LogWarning((object)("The prefab '" + ((Object)prefab).name + "' does not have an ItemDrop, AOE, or EffectArea component. Cannot add the StatusEffect to the prefab.")); } } catch (Exception arg) { Debug.LogWarning((object)$"BROKE : {arg}"); } } } } } namespace SkillManager { [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] [PublicAPI] public class Skill { [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] public static class LocalizationCache { private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>(); internal static void LocalizationPostfix(Localization __instance, string language) { string key = localizations.FirstOrDefault([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (KeyValuePair<string, Localization> l) => l.Value == __instance).Key; if (key != null) { localizations.Remove(key); } if (!localizations.ContainsKey(language)) { localizations.Add(language, __instance); } } public static Localization ForLanguage([<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] string language = null) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out var value)) { return value; } value = new Localization(); if (language != null) { value.SetupLanguage(language); } return value; } } [PublicAPI] [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] public class LocalizeKey { private static readonly List<LocalizeKey> keys = new List<LocalizeKey>(); public readonly string Key; public readonly Dictionary<string, string> Localizations = new Dictionary<string, string>(); public LocalizeKey(string key) { Key = key.Replace("$", ""); keys.Add(this); } public void Alias(string alias) { Localizations.Clear(); if (!alias.Contains("$")) { alias = "$" + alias; } Localizations["alias"] = alias; Localization.instance.AddWord(Key, Localization.instance.Localize(alias)); } public LocalizeKey English(string key) { return addForLang("English", key); } public LocalizeKey Swedish(string key) { return addForLang("Swedish", key); } public LocalizeKey French(string key) { return addForLang("French", key); } public LocalizeKey Italian(string key) { return addForLang("Italian", key); } public LocalizeKey German(string key) { return addForLang("German", key); } public LocalizeKey Spanish(string key) { return addForLang("Spanish", key); } public LocalizeKey Russian(string key) { return addForLang("Russian", key); } public LocalizeKey Romanian(string key) { return addForLang("Romanian", key); } public LocalizeKey Bulgarian(string key) { return addForLang("Bulgarian", key); } public LocalizeKey Macedonian(string key) { return addForLang("Macedonian", key); } public LocalizeKey Finnish(string key) { return addForLang("Finnish", key); } public LocalizeKey Danish(string key) { return addForLang("Danish", key); } public LocalizeKey Norwegian(string key) { return addForLang("Norwegian", key); } public LocalizeKey Icelandic(string key) { return addForLang("Icelandic", key); } public LocalizeKey Turkish(string key) { return addForLang("Turkish", key); } public LocalizeKey Lithuanian(string key) { return addForLang("Lithuanian", key); } public LocalizeKey Czech(string key) { return addForLang("Czech", key); } public LocalizeKey Hungarian(string key) { return addForLang("Hungarian", key); } public LocalizeKey Slovak(string key) { return addForLang("Slovak", key); } public LocalizeKey Polish(string key) { return addForLang("Polish", key); } public LocalizeKey Dutch(string key) { return addForLang("Dutch", key); } public LocalizeKey Portuguese_European(string key) { return addForLang("Portuguese_European", key); } public LocalizeKey Portuguese_Brazilian(string key) { return addForLang("Portuguese_Brazilian", key); } public LocalizeKey Chinese(string key) { return addForLang("Chinese", key); } public LocalizeKey Japanese(string key) { return addForLang("Japanese", key); } public LocalizeKey Korean(string key) { return addForLang("Korean", key); } public LocalizeKey Hindi(string key) { return addForLang("Hindi", key); } public LocalizeKey Thai(string key) { return addForLang("Thai", key); } public LocalizeKey Abenaki(string key) { return addForLang("Abenaki", key); } public LocalizeKey Croatian(string key) { return addForLang("Croatian", key); } public LocalizeKey Georgian(string key) { return addForLang("Georgian", key); } public LocalizeKey Greek(string key) { return addForLang("Greek", key); } public LocalizeKey Serbian(string key) { return addForLang("Serbian", key); } public LocalizeKey Ukrainian(string key) { return addForLang("Ukrainian", key); } private LocalizeKey addForLang(string lang, string value) { Localizations[lang] = value; if (Localization.instance.GetSelectedLanguage() == lang) { Localization.instance.AddWord(Key, value); } else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key)) { Localization.instance.AddWord(Key, value); } return this; } [HarmonyPriority(300)] internal static void AddLocalizedKeys(Localization __instance, string language) { foreach (LocalizeKey key in keys) { string value2; if (key.Localizations.TryGetValue(language, out var value) || key.Localizations.TryGetValue("English", out value)) { __instance.AddWord(key.Key, value); } else if (key.Localizations.TryGetValue("alias", out value2)) { __instance.AddWord(key.Key, Localization.instance.Localize(value2)); } } } } [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] private class ConfigurationManagerAttributes { [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] [UsedImplicitly] public string Category; } [HarmonyPatch(typeof(Skills), "IsSkillValid")] [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] private static class Patch_Skills_IsSkillValid { private static void Postfix(SkillType type, ref bool __result) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (!__result && skills.ContainsKey(type)) { __result = true; } } } private static readonly Dictionary<SkillType, Skill> skills; internal static readonly Dictionary<string, Skill> skillByName; private readonly string skillName; private readonly string internalSkillName; private readonly SkillDef skillDef; public readonly LocalizeKey Name; public readonly LocalizeKey Description; private float skillEffectFactor = 1f; private int skillLoss = 5; public bool Configurable = false; private static bool InitializedTerminal; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private static Localization _english; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private static BaseUnityPlugin _plugin; private static bool hasConfigSync; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private static object _configSync; public float SkillGainFactor { get { return skillDef.m_increseStep; } set { skillDef.m_increseStep = value; this.SkillGainFactorChanged?.Invoke(value); } } public float SkillEffectFactor { get { return skillEffectFactor; } set { skillEffectFactor = value; this.SkillEffectFactorChanged?.Invoke(value); } } public int SkillLoss { get { return skillLoss; } set { skillLoss = value; this.SkillLossChanged?.Invoke(value); } } private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English")); private static BaseUnityPlugin plugin { get { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown object obj = _plugin; if (obj == null) { BaseUnityPlugin val = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)Assembly.GetExecutingAssembly().DefinedTypes.First([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); _plugin = val; obj = (object)val; } return (BaseUnityPlugin)obj; } } [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private static object configSync { [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(2)] get { if (_configSync == null && hasConfigSync) { Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync"); if ((object)type != null) { _configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " SkillManager"); type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString()); type.GetProperty("IsLocked").SetValue(_configSync, true); } else { hasConfigSync = false; } } return _configSync; } } [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] [method: <09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(2)] [field: <ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] public event Action<float> SkillGainFactorChanged; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] [method: <09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(2)] [field: <ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] public event Action<float> SkillEffectFactorChanged; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] [method: <09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(2)] [field: <ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] public event Action<float> SkillLossChanged; public Skill(string englishName, string icon) : this(englishName, loadSprite(icon, 64, 64)) { } public unsafe Skill(string englishName, Sprite icon) { //IL_0022: 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_0043: 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_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0082: 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_008d: Expected O, but got Unknown SkillType val = fromName(englishName); string text = new Regex("[^a-zA-Z]").Replace(englishName, "_"); skills[val] = this; skillByName[englishName] = this; skillDef = new SkillDef { m_description = "$skilldesc_" + text, m_icon = icon, m_increseStep = 1f, m_skill = val }; internalSkillName = text; skillName = englishName; Name = new LocalizeKey("skill_" + ((object)(*(SkillType*)(&val))/*cast due to .constrained prefix*/).ToString()).English(englishName); Description = new LocalizeKey("skilldesc_" + text); } public static SkillType fromName(string englishName) { return (SkillType)Math.Abs(StringExtensionMethods.GetStableHashCode(englishName)); } static Skill() { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Expected O, but got Unknown //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Expected O, but got Unknown //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Expected O, but got Unknown //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Expected O, but got Unknown //IL_0185: 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_01ad: Expected O, but got Unknown //IL_01ad: Expected O, but got Unknown //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Expected O, but got Unknown //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Expected O, but got Unknown //IL_023f: Expected O, but got Unknown skills = new Dictionary<SkillType, Skill>(); skillByName = new Dictionary<string, Skill>(); InitializedTerminal = false; hasConfigSync = true; Harmony val = new Harmony("org.bepinex.helpers.skillmanager"); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "GetSkillDef", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_GetSkillDef", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatRaiseSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatRaiseskill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatResetSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatResetSkill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "OnDeath", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Finalizer", (Type[])null, (Type[])null)), (HarmonyMethod)null); } private static void Patch_FejdStartup() { //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Expected O, but got Unknown //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Expected O, but got Unknown //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Expected O, but got Unknown foreach (Skill skill in skills.Values) { if (skill.Configurable) { string key = skill.Name.Key; string text = new Regex("['[\"\\]]").Replace(english.Localize(key), "").Trim(); string category = Localization.instance.Localize(key).Trim(); ConfigEntry<float> skillGain = config(text, "Skill gain factor", skill.SkillGainFactor, new ConfigDescription("The rate at which you gain experience for the skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1] { new ConfigurationManagerAttributes { Category = category } })); skill.SkillGainFactor = skillGain.Value; skillGain.SettingChanged += [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (object _, EventArgs _) => { skill.SkillGainFactor = skillGain.Value; }; ConfigEntry<float> skillEffect = config(text, "Skill effect factor", skill.SkillEffectFactor, new ConfigDescription("The power of the skill, based on the default power.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1] { new ConfigurationManagerAttributes { Category = category } })); skill.SkillEffectFactor = skillEffect.Value; skillEffect.SettingChanged += [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (object _, EventArgs _) => { skill.SkillEffectFactor = skillEffect.Value; }; ConfigEntry<int> skillLoss = config(text, "Skill loss", skill.skillLoss, new ConfigDescription("How much experience to lose on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1] { new ConfigurationManagerAttributes { Category = category } })); skill.skillLoss = skillLoss.Value; skillLoss.SettingChanged += [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (object _, EventArgs _) => { skill.skillLoss = skillLoss.Value; }; } } } private static void Patch_Skills_GetSkillDef([<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] ref SkillDef __result, List<SkillDef> ___m_skills, SkillType type) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) if (__result == null) { SkillDef val = GetSkillDef(type); if (val != null) { ___m_skills.Add(val); __result = val; } } } private unsafe static bool Patch_Skills_CheatRaiseskill(Skills __instance, string name, float value, Player ___m_player) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) foreach (SkillType key in skills.Keys) { Skill skill = skills[key]; if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase)) { Skill skill2 = __instance.GetSkill(key); skill2.m_level += value; skill2.m_level = Mathf.Clamp(skill2.m_level, 0f, 100f); ((Character)___m_player).Message((MessageType)1, "Skill increased " + Localization.instance.Localize("$skill_" + ((object)(*(SkillType*)(&key))/*cast due to .constrained prefix*/).ToString()) + ": " + (int)skill2.m_level, 0, skill2.m_info.m_icon); Console.instance.Print("Skill " + skill.internalSkillName + " = " + skill2.m_level); return false; } } return true; } private static bool Patch_Skills_CheatResetSkill(Skills __instance, string name) { //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_0022: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) foreach (SkillType key in skills.Keys) { Skill skill = skills[key]; if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase)) { __instance.ResetSkill(key); Console.instance.Print("Skill " + skill.internalSkillName + " reset"); return false; } } return true; } private static void Patch_Skills_OnDeath_Prefix(Skills __instance, [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(new byte[] { 2, 1 })] ref Dictionary<SkillType, Skill> __state) { //IL_002e: 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_00a0: Unknown result type (might be due to invalid IL or missing references) if (__state == null) { __state = new Dictionary<SkillType, Skill>(); } foreach (KeyValuePair<SkillType, Skill> skill in skills) { if (__instance.m_skillData.TryGetValue(skill.Key, out var value)) { __state[skill.Key] = value; if (skill.Value.skillLoss > 0) { Skill obj = value; obj.m_level -= value.m_level * (float)skill.Value.SkillLoss / 100f; value.m_accumulator = 0f; } __instance.m_skillData.Remove(skill.Key); } } } private static void Patch_Skills_OnDeath_Finalizer(Skills __instance, [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(new byte[] { 2, 1 })] ref Dictionary<SkillType, Skill> __state) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) if (__state == null) { return; } foreach (KeyValuePair<SkillType, Skill> item in __state) { __instance.m_skillData[item.Key] = item.Value; } __state = null; } private static void Patch_Terminal_InitTerminal_Prefix() { InitializedTerminal = Terminal.m_terminalInitialized; } private static void Patch_Terminal_InitTerminal() { if (!InitializedTerminal) { AddSkill(Terminal.commands["raiseskill"]); AddSkill(Terminal.commands["resetskill"]); } static void AddSkill(ConsoleCommand command) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown ConsoleOptionsFetcher fetcher = command.m_tabOptionsFetcher; command.m_tabOptionsFetcher = (ConsoleOptionsFetcher)([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] () => { List<string> list = fetcher.Invoke(); list.AddRange(skills.Values.Select([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (Skill skill) => skill.internalSkillName)); return list; }); } } [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(2)] private static SkillDef GetSkillDef(SkillType skillType) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (!skills.ContainsKey(skillType)) { return null; } Skill skill = skills[skillType]; return skill.skillDef; } private static byte[] ReadEmbeddedFileBytes(string name) { using MemoryStream memoryStream = new MemoryStream(); Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + name).CopyTo(memoryStream); return memoryStream.ToArray(); } private static Texture2D loadTexture(string name) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Expected O, but got Unknown Texture2D val = new Texture2D(0, 0); ImageConversion.LoadImage(val, ReadEmbeddedFileBytes("icons." + name)); return val; } private static Sprite loadSprite(string name, int width, int height) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) return Sprite.Create(loadTexture(name), new Rect(0f, 0f, (float)width, (float)height), Vector2.zero); } private static ConfigEntry<T> config<[<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] T>(string group, string name, T value, ConfigDescription description) { ConfigEntry<T> val = plugin.Config.Bind<T>(group, name, value, description); configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T)) .Invoke(configSync, new object[1] { val }); return val; } private static ConfigEntry<T> config<[<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] T>(string group, string name, T value, string description) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())); } } [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] [PublicAPI] [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] public static class SkillExtensions { public static float GetSkillFactor(this Character character, string name) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return character.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor; } public static float GetSkillFactor(this Skills skills, string name) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return skills.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor; } public static void RaiseSkill(this Character character, string name, float value = 1f) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) character.RaiseSkill(Skill.fromName(name), value); } public static void RaiseSkill(this Skills skill, string name, float value = 1f) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) skill.RaiseSkill(Skill.fromName(name), value); } public static void LowerSkill(this Character character, string name, float factor = 1f) { character.GetSkills().LowerSkill(name, factor); } public static void LowerSkill(this Skills skills, string name, float factor) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (factor > 0f && skills.m_skillData.TryGetValue(Skill.fromName(name), out var value)) { Skill obj = value; obj.m_level -= value.m_level * factor; value.m_accumulator = 0f; } } } } namespace PieceManager { [PublicAPI] [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] public static class MaterialReplacer { [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] public enum ShaderType { PieceShader, VegetationShader, RockShader, RugShader, GrassShader, CustomCreature, UseUnityShader } private static readonly Dictionary<GameObject, bool> ObjectToSwap; private static readonly Dictionary<string, Material> OriginalMaterials; private static readonly Dictionary<GameObject, ShaderType> ObjectsForShaderReplace; private static readonly HashSet<Shader> CachedShaders; private static bool hasRun; static MaterialReplacer() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown CachedShaders = new HashSet<Shader>(); hasRun = false; OriginalMaterials = new Dictionary<string, Material>(); ObjectToSwap = new Dictionary<GameObject, bool>(); ObjectsForShaderReplace = new Dictionary<GameObject, ShaderType>(); Harmony val = new Harmony("org.bepinex.helpers.PieceManager"); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZoneSystem), "Start", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(MaterialReplacer), "ReplaceAllMaterialsWithOriginal", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static void RegisterGameObjectForShaderSwap(GameObject go, ShaderType type) { if (!ObjectsForShaderReplace.ContainsKey(go)) { ObjectsForShaderReplace.Add(go, type); } } public static void RegisterGameObjectForMatSwap(GameObject go, bool isJotunnMock = false) { if (!ObjectToSwap.ContainsKey(go)) { ObjectToSwap.Add(go, isJotunnMock); } } private static void GetAllMaterials() { Material[] array = Resources.FindObjectsOfTypeAll<Material>(); foreach (Material val in array) { OriginalMaterials[((Object)val).name] = val; } } [HarmonyPriority(700)] private static void ReplaceAllMaterialsWithOriginal() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 if ((int)SystemInfo.graphicsDeviceType == 4 || hasRun) { return; } if (OriginalMaterials.Count == 0) { GetAllMaterials(); } foreach (KeyValuePair<GameObject, bool> item in ObjectToSwap) { GameObject key = item.Key; bool value = item.Value; ProcessGameObjectMaterials(key, value); } AssetBundle[] array = Resources.FindObjectsOfTypeAll<AssetBundle>(); AssetBundle[] array2 = array; foreach (AssetBundle val in array2) { IEnumerable<Shader> enumerable3; try { IEnumerable<Shader> enumerable2; if (!val.isStreamedSceneAssetBundle || !Object.op_Implicit((Object)(object)val)) { IEnumerable<Shader> enumerable = val.LoadAllAssets<Shader>(); enumerable2 = enumerable; } else { enumerable2 = from shader in ((IEnumerable<string>)val.GetAllAssetNames()).Select((Func<string, Shader>)val.LoadAsset<Shader>) where (Object)(object)shader != (Object)null select shader; } enumerable3 = enumerable2; } catch (Exception) { continue; } if (enumerable3 == null) { continue; } foreach (Shader item2 in enumerable3) { CachedShaders.Add(item2); } } foreach (KeyValuePair<GameObject, ShaderType> item3 in ObjectsForShaderReplace) { GameObject key2 = item3.Key; ShaderType value2 = item3.Value; ProcessGameObjectShaders(key2, value2); } hasRun = true; } private static void ProcessGameObjectMaterials(GameObject go, bool isJotunnMock) { Renderer[] componentsInChildren = go.GetComponentsInChildren<Renderer>(true); Renderer[] array = componentsInChildren; foreach (Renderer val in array) { Material[] sharedMaterials = val.sharedMaterials.Select([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (Material material) => ReplaceMaterial(material, isJotunnMock)).ToArray(); val.sharedMaterials = sharedMaterials; } } private static Material ReplaceMaterial(Material originalMaterial, bool isJotunnMock) { string text = (isJotunnMock ? "JVLmock_" : "_REPLACE_"); if (!((Object)originalMaterial).name.StartsWith(text, StringComparison.Ordinal)) { return originalMaterial; } string text2 = ((Object)originalMaterial).name.Replace(" (Instance)", "").Replace(text, ""); if (OriginalMaterials.TryGetValue(text2, out var value)) { return value; } Debug.LogWarning((object)("No suitable material found to replace: " + text2)); return originalMaterial; } private static void ProcessGameObjectShaders(GameObject go, ShaderType shaderType) { Renderer[] componentsInChildren = go.GetComponentsInChildren<Renderer>(true); Renderer[] array = componentsInChildren; foreach (Renderer val in array) { Material[] sharedMaterials = val.sharedMaterials; foreach (Material val2 in sharedMaterials) { if ((Object)(object)val2 != (Object)null) { val2.shader = GetShaderForType(val2.shader, shaderType, ((Object)val2.shader).name); } } } } private static Shader GetShaderForType(Shader orig, ShaderType shaderType, string originalShaderName) { return (Shader)(shaderType switch { ShaderType.PieceShader => FindShaderWithName(orig, "Custom/Piece"), ShaderType.VegetationShader => FindShaderWithName(orig, "Custom/Vegetation"), ShaderType.RockShader => FindShaderWithName(orig, "Custom/StaticRock"), ShaderType.RugShader => FindShaderWithName(orig, "Custom/Rug"), ShaderType.GrassShader => FindShaderWithName(orig, "Custom/Grass"), ShaderType.CustomCreature => FindShaderWithName(orig, "Custom/Creature"), ShaderType.UseUnityShader => FindShaderWithName(orig, ((Object)(object)FindShaderWithName(orig, originalShaderName) != (Object)null) ? originalShaderName : "ToonDeferredShading2017"), _ => FindShaderWithName(orig, "Standard"), }); } public static Shader FindShaderWithName(Shader origShader, string name) { foreach (Shader cachedShader in CachedShaders) { if (((Object)cachedShader).name == name) { return cachedShader; } } return origShader; } } [PublicAPI] public enum CraftingTable { None, [InternalName("piece_workbench")] Workbench, [InternalName("piece_cauldron")] Cauldron, [InternalName("forge")] Forge, [InternalName("piece_artisanstation")] ArtisanTable, [InternalName("piece_stonecutter")] StoneCutter, [InternalName("piece_magetable")] MageTable, [InternalName("blackforge")] BlackForge, Custom } [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] public class InternalName : Attribute { public readonly string internalName; public InternalName(string internalName) { this.internalName = internalName; } } [PublicAPI] [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] public class ExtensionList { public readonly List<ExtensionConfig> ExtensionStations = new List<ExtensionConfig>(); public void Set(CraftingTable table, int maxStationDistance = 5) { ExtensionStations.Add(new ExtensionConfig { Table = table, maxStationDistance = maxStationDistance }); } public void Set(string customTable, int maxStationDistance = 5) { ExtensionStations.Add(new ExtensionConfig { Table = CraftingTable.Custom, custom = customTable, maxStationDistance = maxStationDistance }); } } public struct ExtensionConfig { public CraftingTable Table; public float maxStationDistance; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] public string custom; } [PublicAPI] [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] public class CraftingStationList { public readonly List<CraftingStationConfig> Stations = new List<CraftingStationConfig>(); public void Set(CraftingTable table) { Stations.Add(new CraftingStationConfig { Table = table }); } public void Set(string customTable) { Stations.Add(new CraftingStationConfig { Table = CraftingTable.Custom, custom = customTable }); } } public struct CraftingStationConfig { public CraftingTable Table; public int level; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] public string custom; } [PublicAPI] public enum BuildPieceCategory { Misc = 0, Crafting = 1, BuildingWorkbench = 2, BuildingStonecutter = 3, Furniture = 4, All = 100, Custom = 99 } [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] [PublicAPI] public class RequiredResourcesList { public readonly List<Requirement> Requirements = new List<Requirement>(); public void Add(string item, int amount, bool recover) { Requirements.Add(new Requirement { itemName = item, amount = amount, recover = recover }); } } public struct Requirement { [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(1)] public string itemName; public int amount; public bool recover; } public struct SpecialProperties { [Description("Admins should be the only ones that can build this piece.")] public bool AdminOnly; [Description("Turns off generating a config for this build piece.")] public bool NoConfig; } [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] [PublicAPI] public class BuildingPieceCategory { public BuildPieceCategory Category; public string custom = ""; public void Set(BuildPieceCategory category) { Category = category; } public void Set(string customCategory) { Category = BuildPieceCategory.Custom; custom = customCategory; } } [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] [PublicAPI] [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] public class PieceTool { public readonly HashSet<string> Tools = new HashSet<string>(); public void Add(string tool) { Tools.Add(tool); } } [PublicAPI] [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(1)] public class BuildPiece { [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] internal class PieceConfig { public ConfigEntry<string> craft = null; public ConfigEntry<BuildPieceCategory> category = null; public ConfigEntry<string> customCategory = null; public ConfigEntry<string> tools = null; public ConfigEntry<CraftingTable> extensionTable = null; public ConfigEntry<string> customExtentionTable = null; public ConfigEntry<float> maxStationDistance = null; public ConfigEntry<CraftingTable> table = null; public ConfigEntry<string> customTable = null; } [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] [UsedImplicitly] public string Category; [UsedImplicitly] [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(new byte[] { 2, 1 })] public Action<ConfigEntryBase> CustomDrawer; } [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(0)] private class SerializedRequirements { public readonly List<Requirement> Reqs; public SerializedRequirements(List<Requirement> reqs) { Reqs = reqs; } public SerializedRequirements(string reqs) { Reqs = reqs.Split(new char[1] { ',' }).Select([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (string r) => { string[] array = r.Split(new char[1] { ':' }); int result; bool result2 = default(bool); return new Requirement { itemName = array[0], amount = ((array.Length <= 1 || !int.TryParse(array[1], out result)) ? 1 : result), recover = (array.Length <= 2 || !bool.TryParse(array[2], out result2) || result2) }; }).ToList(); } public override string ToString() { return string.Join(",", Reqs.Select([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (Requirement r) => $"{r.itemName}:{r.amount}:{r.recover}")); } [return: <ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] public static ItemDrop fetchByName(ObjectDB objectDB, string name) { GameObject itemPrefab = objectDB.GetItemPrefab(name); ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null); if ((Object)(object)val == (Object)null) { Debug.LogWarning((object)(((!string.IsNullOrWhiteSpace(((Object)plugin).name)) ? ("[" + ((Object)plugin).name + "]") : "") + " The required item '" + name + "' does not exist.")); } return val; } public static Requirement[] toPieceReqs(SerializedRequirements craft) { Dictionary<string, Requirement> dictionary = craft.Reqs.Where((Requirement r) => r.itemName != "").ToDictionary((Func<Requirement, string>)([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (Requirement r) => r.itemName), (Func<Requirement, Requirement>)([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (Requirement r) => { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) ItemDrop val = ResItem(r); return (val == null) ? ((Requirement)null) : new Requirement { m_amount = r.amount, m_resItem = val, m_recover = r.recover }; })); return dictionary.Values.Where([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (Requirement v) => v != null).ToArray(); [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(2)] static ItemDrop ResItem(Requirement r) { return fetchByName(ObjectDB.instance, r.itemName); } } } internal static readonly List<BuildPiece> registeredPieces = new List<BuildPiece>(); private static readonly Dictionary<Piece, BuildPiece> pieceMap = new Dictionary<Piece, BuildPiece>(); internal static Dictionary<BuildPiece, PieceConfig> pieceConfigs = new Dictionary<BuildPiece, PieceConfig>(); internal List<Conversion> Conversions = new List<Conversion>(); internal List<ItemConversion> conversions = new List<ItemConversion>(); [Description("Disables generation of the configs for your pieces. This is global, this turns it off for all pieces in your mod.")] public static bool ConfigurationEnabled = true; public readonly GameObject Prefab; [Description("Specifies the resources needed to craft the piece.\nUse .Add to add resources with their internal ID and an amount.\nUse one .Add for each resource type the building piece should need.")] public readonly RequiredResourcesList RequiredItems = new RequiredResourcesList(); [Description("Sets the category for the building piece.")] public readonly BuildingPieceCategory Category = new BuildingPieceCategory(); [Description("Specifies the tool needed to build your piece.\nUse .Add to add a tool.")] public readonly PieceTool Tool = new PieceTool(); [Description("Specifies the crafting station needed to build your piece.\nUse .Add to add a crafting station, using the CraftingTable enum and a minimum level for the crafting station.")] public CraftingStationList Crafting = new CraftingStationList(); [Description("Makes this piece a station extension")] public ExtensionList Extension = new ExtensionList(); [Description("Change the extended/special properties of your build piece.")] public SpecialProperties SpecialProperties; [Description("Specifies a config entry which toggles whether a recipe is active.")] [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] public ConfigEntryBase RecipeIsActive = null; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private LocalizeKey _name; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private LocalizeKey _description; internal string[] activeTools = null; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private static object configManager; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private static Localization _english; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] internal static BaseUnityPlugin _plugin = null; private static bool hasConfigSync = true; [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private static object _configSync; public LocalizeKey Name { get { LocalizeKey name = _name; if (name != null) { return name; } Piece component = Prefab.GetComponent<Piece>(); if (component.m_name.StartsWith("$")) { _name = new LocalizeKey(component.m_name); } else { string text = "$piece_" + ((Object)Prefab).name.Replace(" ", "_"); _name = new LocalizeKey(text).English(component.m_name); component.m_name = text; } return _name; } } public LocalizeKey Description { get { LocalizeKey description = _description; if (description != null) { return description; } Piece component = Prefab.GetComponent<Piece>(); if (component.m_description.StartsWith("$")) { _description = new LocalizeKey(component.m_description); } else { string text = "$piece_" + ((Object)Prefab).name.Replace(" ", "_") + "_description"; _description = new LocalizeKey(text).English(component.m_description); component.m_description = text; } return _description; } } private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English")); internal static BaseUnityPlugin plugin { get { //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown if (_plugin != null) { return _plugin; } IEnumerable<TypeInfo> source; try { source = Assembly.GetExecutingAssembly().DefinedTypes.ToList(); } catch (ReflectionTypeLoadException ex) { source = from t in ex.Types where t != null select t.GetTypeInfo(); } _plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); return _plugin; } } [<ceb323af-b840-4258-961e-1c015a8e52db>Nullable(2)] private static object configSync { [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(2)] get { if (_configSync != null || !hasConfigSync) { return _configSync; } Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync"); if ((object)type != null) { _configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " PieceManager"); type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString()); type.GetProperty("IsLocked").SetValue(_configSync, true); } else { hasConfigSync = false; } return _configSync; } } public BuildPiece(string assetBundleFileName, string prefabName, string folderName = "assets") : this(PiecePrefabManager.RegisterAssetBundle(assetBundleFileName, folderName), prefabName) { } public BuildPiece(AssetBundle bundle, string prefabName) { Prefab = PiecePrefabManager.RegisterPrefab(bundle, prefabName); registeredPieces.Add(this); } internal static void Patch_FejdStartup(FejdStartup __instance) { //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_02e1: Unknown result type (might be due to invalid IL or missing references) //IL_02eb: Expected O, but got Unknown //IL_0389: Unknown result type (might be due to invalid IL or missing references) //IL_0393: Expected O, but got Unknown //IL_0431: Unknown result type (might be due to invalid IL or missing references) //IL_040b: Unknown result type (might be due to invalid IL or missing references) //IL_0410: Unknown result type (might be due to invalid IL or missing references) //IL_048c: Unknown result type (might be due to invalid IL or missing references) //IL_0496: Expected O, but got Unknown //IL_0606: Unknown result type (might be due to invalid IL or missing references) //IL_0610: Expected O, but got Unknown //IL_08ea: Unknown result type (might be due to invalid IL or missing references) //IL_08f4: Expected O, but got Unknown //IL_067b: Unknown result type (might be due to invalid IL or missing references) //IL_0685: Expected O, but got Unknown //IL_0721: Unknown result type (might be due to invalid IL or missing references) //IL_072b: Expected O, but got Unknown //IL_095f: Unknown result type (might be due to invalid IL or missing references) //IL_0969: Expected O, but got Unknown //IL_0b7e: Unknown result type (might be due to invalid IL or missing references) //IL_0b88: Expected O, but got Unknown //IL_0c18: Unknown result type (might be due to invalid IL or missing references) //IL_0c22: Expected O, but got Unknown Type configManagerType = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (Assembly a) => a.GetName().Name == "ConfigurationManager")?.GetType("ConfigurationManager.ConfigurationManager"); configManager = ((configManagerType == null) ? null : Chainloader.ManagerObject.GetComponent(configManagerType)); foreach (BuildPiece registeredPiece in registeredPieces) { registeredPiece.activeTools = registeredPiece.Tool.Tools.DefaultIfEmpty("Hammer").ToArray(); if (registeredPiece.Category.Category != BuildPieceCategory.Custom) { registeredPiece.Prefab.GetComponent<Piece>().m_category = (PieceCategory)registeredPiece.Category.Category; } else { registeredPiece.Prefab.GetComponent<Piece>().m_category = PiecePrefabManager.GetCategory(registeredPiece.Category.custom); } } if (!ConfigurationEnabled) { return; } bool saveOnConfigSet = plugin.Config.SaveOnConfigSet; plugin.Config.SaveOnConfigSet = false; foreach (BuildPiece registeredPiece2 in registeredPieces) { BuildPiece piece = registeredPiece2; if (piece.SpecialProperties.NoConfig) { continue; } PieceConfig pieceConfig = (pieceConfigs[piece] = new PieceConfig()); PieceConfig cfg = pieceConfig; Piece piecePrefab = piece.Prefab.GetComponent<Piece>(); string pieceName = piecePrefab.m_name; string englishName = new Regex("[=\\n\\t\\\\\"\\'\\[\\]]*").Replace(english.Localize(pieceName), "").Trim(); string localizedName = Localization.instance.Localize(pieceName).Trim(); int order = 0; cfg.category = config(englishName, "Build Table Category", piece.Category.Category, new ConfigDescription("Build Category where " + localizedName + " is available.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = (order -= 1), Category = localizedName } })); ConfigurationManagerAttributes customTableAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), Browsable = (cfg.category.Value == BuildPieceCategory.Custom), Category = localizedName }; cfg.customCategory = config(englishName, "Custom Build Category", piece.Category.custom, new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes })); cfg.category.SettingChanged += BuildTableConfigChanged; cfg.customCategory.SettingChanged += BuildTableConfigChanged; if (cfg.category.Value == BuildPieceCategory.Custom) { piecePrefab.m_category = PiecePrefabManager.GetCategory(cfg.customCategory.Value); } else { piecePrefab.m_category = (PieceCategory)cfg.category.Value; } cfg.tools = config(englishName, "Tools", string.Join(", ", piece.activeTools), new ConfigDescription("Comma separated list of tools where " + localizedName + " is available.", (AcceptableValueBase)null, new object[1] { customTableAttributes })); piece.activeTools = (from s in cfg.tools.Value.Split(new char[1] { ',' }) select s.Trim()).ToArray(); cfg.tools.SettingChanged += [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (object _, EventArgs _) => { Inventory[] source = (from c in Player.s_players.Select([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (Player p) => ((Humanoid)p).GetInventory()).Concat(from c in Object.FindObjectsOfType<Container>() select c.GetInventory()) where c != null select c).ToArray(); Dictionary<string, List<PieceTable>> dictionary = (from kv in (from i in (from p in ObjectDB.instance.m_items select p.GetComponent<ItemDrop>() into c where Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((Component)c).GetComponent<ZNetView>()) select c).Concat(ItemDrop.s_instances) select new KeyValuePair<string, ItemData>(Utils.GetPrefabName(((Component)i).gameObject), i.m_itemData)).Concat(from i in source.SelectMany([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (Inventory i) => i.GetAllItems()) select new KeyValuePair<string, ItemData>(((Object)i.m_dropPrefab).name, i)) where Object.op_Implicit((Object)(object)kv.Value.m_shared.m_buildPieces) group kv by kv.Key).ToDictionary([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (IGrouping<string, KeyValuePair<string, ItemData>> g) => g.Key, [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (IGrouping<string, KeyValuePair<string, ItemData>> g) => g.Select([<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (KeyValuePair<string, ItemData> kv) => kv.Value.m_shared.m_buildPieces).Distinct().ToList()); string[] array4 = piece.activeTools; foreach (string key in array4) { if (dictionary.TryGetValue(key, out var value)) { foreach (PieceTable item3 in value) { item3.m_pieces.Remove(piece.Prefab); } } } piece.activeTools = (from s in cfg.tools.Value.Split(new char[1] { ',' }) select s.Trim()).ToArray(); if (Object.op_Implicit((Object)(object)ObjectDB.instance)) { string[] array5 = piece.activeTools; foreach (string key2 in array5) { if (dictionary.TryGetValue(key2, out var value2)) { foreach (PieceTable item4 in value2) { if (!item4.m_pieces.Contains(piece.Prefab)) { item4.m_pieces.Add(piece.Prefab); } } } } if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)Player.m_localPlayer.m_buildPieces)) { ((Humanoid)Player.m_localPlayer).SetPlaceMode(Player.m_localPlayer.m_buildPieces); } } }; StationExtension pieceExtensionComp; List<ConfigurationManagerAttributes> hideWhenNoneAttributes; if (piece.Extension.ExtensionStations.Count > 0) { pieceExtensionComp = piece.Prefab.GetOrAddComponent<StationExtension>(); PieceConfig pieceConfig3 = cfg; string text = englishName; CraftingTable table = piece.Extension.ExtensionStations.First().Table; string text2 = "Crafting station that " + localizedName + " extends."; object[] array = new object[1]; ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes(); int num = order - 1; order = num; configurationManagerAttributes.Order = num; array[0] = configurationManagerAttributes; pieceConfig3.extensionTable = config(text, "Extends Station", table, new ConfigDescription(text2, (AcceptableValueBase)null, array)); cfg.customExtentionTable = config(englishName, "Custom Extend Station", piece.Extension.ExtensionStations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes })); PieceConfig pieceConfig4 = cfg; string text3 = englishName; float maxStationDistance = piece.Extension.ExtensionStations.First().maxStationDistance; string text4 = "Distance from the station that " + localizedName + " can be placed."; object[] array2 = new object[1]; ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes(); num = order - 1; order = num; configurationManagerAttributes2.Order = num; array2[0] = configurationManagerAttributes2; pieceConfig4.maxStationDistance = config(text3, "Max Station Distance", maxStationDistance, new ConfigDescription(text4, (AcceptableValueBase)null, array2)); hideWhenNoneAttributes = new List<ConfigurationManagerAttributes>(); cfg.extensionTable.SettingChanged += ExtensionTableConfigChanged; cfg.customExtentionTable.SettingChanged += ExtensionTableConfigChanged; cfg.maxStationDistance.SettingChanged += ExtensionTableConfigChanged; ConfigurationManagerAttributes configurationManagerAttributes3 = new ConfigurationManagerAttributes(); num = order - 1; order = num; configurationManagerAttributes3.Order = num; configurationManagerAttributes3.Browsable = cfg.extensionTable.Value != CraftingTable.None; ConfigurationManagerAttributes item = configurationManagerAttributes3; hideWhenNoneAttributes.Add(item); } List<ConfigurationManagerAttributes> hideWhenNoneAttributes2; if (piece.Crafting.Stations.Count > 0) { hideWhenNoneAttributes2 = new List<ConfigurationManagerAttributes>(); PieceConfig pieceConfig5 = cfg; string text5 = englishName; CraftingTable table2 = piece.Crafting.Stations.First().Table; string text6 = "Crafting station where " + localizedName + " is available."; object[] array3 = new object[1]; ConfigurationManagerAttributes configurationManagerAttributes4 = new ConfigurationManagerAttributes(); int num = order - 1; order = num; configurationManagerAttributes4.Order = num; array3[0] = configurationManagerAttributes4; pieceConfig5.table = config(text5, "Crafting Station", table2, new ConfigDescription(text6, (AcceptableValueBase)null, array3)); cfg.customTable = config(englishName, "Custom Crafting Station", piece.Crafting.Stations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes })); cfg.table.SettingChanged += TableConfigChanged; cfg.customTable.SettingChanged += TableConfigChanged; ConfigurationManagerAttributes configurationManagerAttributes5 = new ConfigurationManagerAttributes(); num = order - 1; order = num; configurationManagerAttributes5.Order = num; configurationManagerAttributes5.Browsable = cfg.table.Value != CraftingTable.None; ConfigurationManagerAttributes item2 = configurationManagerAttributes5; hideWhenNoneAttributes2.Add(item2); } cfg.craft = itemConfig("Crafting Costs", new SerializedRequirements(piece.RequiredItems.Requirements).ToString(), "Item costs to craft " + localizedName); cfg.craft.SettingChanged += [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (object _, EventArgs _) => { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && (Object)(object)ObjectDB.instance.GetItemPrefab("YmirRemains") != (Object)null) { Requirement[] resources = SerializedRequirements.toPieceReqs(new SerializedRequirements(cfg.craft.Value)); piecePrefab.m_resources = resources; Piece[] array4 = Object.FindObjectsOfType<Piece>(); foreach (Piece val in array4) { if (val.m_name == pieceName) { val.m_resources = resources; } } } }; for (int num2 = 0; num2 < piece.Conversions.Count; num2++) { string text7 = ((piece.Conversions.Count > 1) ? $"{num2 + 1}. " : ""); Conversion conversion = piece.Conversions[num2]; conversion.config = new Conversion.ConversionConfig(); int index = num2; conversion.config.input = config(englishName, text7 + "Conversion Input Item", conversion.Input, new ConfigDescription("Conversion input item within " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName } })); conversion.config.input.SettingChanged += [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (object _, EventArgs _) => { if (index < piece.conversions.Count) { ObjectDB instance = ObjectDB.instance; if (instance != null) { ItemDrop val = SerializedRequirements.fetchByName(instance, conversion.config.input.Value); piece.conversions[index].m_from = val; } } }; conversion.config.output = config(englishName, text7 + "Conversion Output Item", conversion.Output, new ConfigDescription("Conversion output item within " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName } })); conversion.config.output.SettingChanged += [<09e2646f-a54e-47af-9cb7-c0de79f57a8d>NullableContext(0)] (object _, EventArgs _) => { if (index < piece.conversions.Count) { ObjectDB instance = ObjectDB.instance; if (instance != null) { ItemDrop to = SerializedRequirements.fetchByName(instance, conversion.config.output.Value); piece.conversions[index].m_to = to; } } }; } void BuildTableConfigChanged(object o, EventArgs e) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) if (registeredPieces.Count > 0) { if (cfg.category.Value == BuildPieceCategory.Custom) { piecePrefab.m_category = PiecePrefabManager.GetCategory(cfg.customCategory.Value); } else { piecePrefab.m_category = (PieceCategory)cfg.category.Value; } if (Object.op_Implicit((Object)(object)Hud.instance)) { PiecePrefabManager.CreateCategoryTabs(); } } customTableAttributes.Browsable = cfg.category.Value == BuildPieceCategory.Custom; ReloadConfigDisplay(); } void ExtensionTableConfigChanged(object o, EventArgs e) { if (piece.RequiredItems.Requirements.Count > 0) { CraftingTable value = cfg.extensionTable.Value; CraftingTable cr
plugins/HBK-HBKHEIM/ConversionSizeAndSpeed-1.0.18/ConversionSizeSpeed.dll
Decompiled 5 hours agousing 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.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: Guid("C1C2EA18-3496-498E-BD7D-AC324A050DFE")] [assembly: ComVisible(false)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyProduct("ConversionSizeSpeed")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyDescription("https://valheim.hexium.gg/mods/Smoothbrain/ConversionSizeAndSpeed")] [assembly: AssemblyTitle("ConversionSizeSpeed")] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(8)] [assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")] [assembly: AssemblyCompany("")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: <60aad3a1-9ea1-4c41-9bea-c20f0f12f8d2>RefSafetyRules(11)] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<02a25bbc-271f-458a-b9a4-db305a606fbd>Embedded] internal sealed class <02a25bbc-271f-458a-b9a4-db305a606fbd>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [<02a25bbc-271f-458a-b9a4-db305a606fbd>Embedded] internal sealed class <6e719793-ab73-42bf-87ea-98a9bcf18ad8>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <6e719793-ab73-42bf-87ea-98a9bcf18ad8>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <6e719793-ab73-42bf-87ea-98a9bcf18ad8>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [<02a25bbc-271f-458a-b9a4-db305a606fbd>Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class <34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContextAttribute : Attribute { public readonly byte Flag; public <34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [<02a25bbc-271f-458a-b9a4-db305a606fbd>Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class <60aad3a1-9ea1-4c41-9bea-c20f0f12f8d2>RefSafetyRulesAttribute : Attribute { public readonly int Version; public <60aad3a1-9ea1-4c41-9bea-c20f0f12f8d2>RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ConversionSizeSpeed { [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(0)] [<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(1)] [BepInPlugin("org.bepinex.plugins.conversionsizespeed", "Conversion Size & Speed", "1.0.18")] [BepInIncompatibility("org.bepinex.plugins.valheim_plus")] public class ConversionSizeSpeed : BaseUnityPlugin { [<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(0)] private class ConfigurationManagerAttributes { [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(2)] [UsedImplicitly] public string Category; [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? ShowRangeAsPercent; } [<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(0)] private enum Toggle { On = 1, Off = 0 } [<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(0)] [HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")] private class FetchSmelterPiecesObjectDB { [HarmonyPriority(0)] [<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(1)] private static void Postfix(ObjectDB __instance) { GameObject itemPrefab = __instance.GetItemPrefab("Hammer"); PieceTable val = ((itemPrefab == null) ? null : itemPrefab.GetComponent<ItemDrop>()?.m_itemData.m_shared.m_buildPieces); if (val != null) { FetchSmelterPieces(val.m_pieces); } } } [<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(0)] [HarmonyPatch(typeof(ZNetScene), "Awake")] private class FetchSmelterPiecesZNetScene { [<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(1)] [HarmonyPriority(0)] private static void Postfix(ZNetScene __instance) { FetchSmelterPieces(__instance.m_prefabs); } } [HarmonyPatch(typeof(Smelter), "Awake")] [<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(0)] private class ChangeSmelterValues { [<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(1)] [UsedImplicitly] private static void Postfix(Smelter __instance) { string name = ((Component)__instance).GetComponentInParent<Piece>().m_name; if (Object.op_Implicit((Object)(object)__instance.m_addOreSwitch) && storageSpace.TryGetValue(name, out var value)) { __instance.m_maxOre = value.Value + storageSpaceIncreasePerBoss[name].Value * BossesDead(); } if (Object.op_Implicit((Object)(object)__instance.m_addWoodSwitch) && fuelSpace.TryGetValue(name, out var value2)) { __instance.m_maxFuel = value2.Value + fuelSpaceIncreasePerBoss[name].Value * BossesDead(); } if (conversionSpeed.TryGetValue(name, out var value3)) { __instance.m_secPerProduct = value3.Value; } if (fuelPerProduct.TryGetValue(name, out var value4)) { __instance.m_fuelPerProduct = value4.Value; } } } [HarmonyPatch(typeof(Character), "OnDeath")] [<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(0)] private class PatchBossDeath { [UsedImplicitly] [<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(1)] private static void Postfix(Character __instance) { if (__instance.IsBoss()) { RecalculateAllSizes(); } } } [HarmonyPatch(typeof(Smelter), "OnAddOre")] [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(0)] private class FillAllOres { [HarmonyPriority(600)] public static void Prefix(Smelter __instance, [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(2)] ItemData item, [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(new byte[] { 0, 2 })] out KeyValuePair<ItemData, int> __state) { int value = __instance.m_nview.GetZDO().GetInt("queued", 0); __state = new KeyValuePair<ItemData, int>(item, value); } public static void Postfix(Smelter __instance, Switch sw, Humanoid user, [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(new byte[] { 0, 2 })] KeyValuePair<ItemData, int> __state, bool __result) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000e: 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_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) KeyboardShortcut value = fillModifierKey.Value; int num; if (Input.GetKey(((KeyboardShortcut)(ref value)).MainKey)) { value = fillModifierKey.Value; num = (((KeyboardShortcut)(ref value)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey) ? 1 : 0); } else { num = 0; } if (((uint)num & (__result ? 1u : 0u)) == 0 || __state.Key != null) { return; } if (!__instance.m_nview.IsOwner()) { ZDOID uid = __instance.m_nview.GetZDO().m_uid; if (!ZDOExtraData.s_ints.TryGetValue(uid, out var value2)) { value2 = (ZDOExtraData.s_ints[uid] = new BinarySearchDictionary<int, int>()); } int num2 = default(int); value2.TryGetValue(StringExtensionMethods.GetStableHashCode("queued"), ref num2); if (num2 == __state.Value) { value2[StringExtensionMethods.GetStableHashCode("queued")] = num2 + 1; } } MessageHud instance = MessageHud.m_instance; MessageHud.m_instance = null; try { __instance.OnAddOre(sw, user, (ItemData)null); } finally { MessageHud.m_instance = instance; } } } [HarmonyPatch(typeof(Smelter), "OnAddFuel")] [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(0)] private class FillAllFuel { [HarmonyPriority(600)] public static void Prefix(Smelter __instance, [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(2)] ItemData item, [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(new byte[] { 0, 2 })] out KeyValuePair<ItemData, float> __state) { float value = __instance.m_nview.GetZDO().GetFloat(StringExtensionMethods.GetStableHashCode("fuel"), 0f); __state = new KeyValuePair<ItemData, float>(item, value); } public static void Postfix(Smelter __instance, Switch sw, Humanoid user, [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(new byte[] { 0, 2 })] KeyValuePair<ItemData, float> __state, bool __result) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000e: 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_0024: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) KeyboardShortcut value = fillModifierKey.Value; int num; if (Input.GetKey(((KeyboardShortcut)(ref value)).MainKey)) { value = fillModifierKey.Value; num = (((KeyboardShortcut)(ref value)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey) ? 1 : 0); } else { num = 0; } if (((uint)num & (__result ? 1u : 0u)) == 0 || __state.Key != null) { return; } if (!__instance.m_nview.IsOwner()) { ZDOID uid = __instance.m_nview.GetZDO().m_uid; if (!ZDOExtraData.s_floats.TryGetValue(uid, out var value2)) { value2 = (ZDOExtraData.s_floats[uid] = new BinarySearchDictionary<int, float>()); } float num2 = default(float); value2.TryGetValue(StringExtensionMethods.GetStableHashCode("fuel"), ref num2); if (num2 == __state.Value) { value2[StringExtensionMethods.GetStableHashCode("fuel")] = num2 + 1f; } } MessageHud instance = MessageHud.m_instance; MessageHud.m_instance = null; try { __instance.OnAddFuel(sw, user, (ItemData)null); } finally { MessageHud.m_instance = instance; } } } [HarmonyPatch(typeof(Smelter), "RPC_AddOre")] [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(0)] private class ThrottleOreEffects { private static float lastFill; public static void Prefix(Smelter __instance, [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(2)] out EffectList __state) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown if (Math.Abs(lastFill - Time.fixedTime) > 0f) { __state = null; lastFill = Time.fixedTime; } else { __state = __instance.m_oreAddedEffects; __instance.m_oreAddedEffects = new EffectList(); } } public static void Finalizer(Smelter __instance, [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(2)] EffectList __state) { if (__state != null) { __instance.m_oreAddedEffects = __state; } } } [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(0)] [HarmonyPatch(typeof(Smelter), "RPC_AddFuel")] private class ThrottleFuelEffects { private static float lastFill; public static void Prefix(Smelter __instance, [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(2)] out EffectList __state) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown if (Math.Abs(lastFill - Time.fixedTime) > 0f) { __state = null; lastFill = Time.fixedTime; } else { __state = __instance.m_fuelAddedEffects; __instance.m_fuelAddedEffects = new EffectList(); } } public static void Finalizer(Smelter __instance, [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(2)] EffectList __state) { if (__state != null) { __instance.m_fuelAddedEffects = __state; } } } [<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(0)] [HarmonyPatch(typeof(Smelter), "OnHoverAddFuel")] private class OverrideFuelHoverText { [<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(1)] public static void Postfix(Smelter __instance, ref string __result) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0081: Unknown result type (might be due to invalid IL or missing references) KeyboardShortcut value = fillModifierKey.Value; if ((int)((KeyboardShortcut)(ref value)).MainKey != 0) { int val = __instance.m_maxFuel - Mathf.CeilToInt(__instance.GetFuel()); Player localPlayer = Player.m_localPlayer; int num = Math.Min(val, (localPlayer != null) ? ((Humanoid)localPlayer).m_inventory.CountItems(__instance.m_fuelItem.m_itemData.m_shared.m_name, -1, true) : 0); if (num > 0) { __result += Localization.instance.Localize($"\n[<b><color=yellow>{fillModifierKey.Value}</color> + <color=yellow>$KEY_Use</color></b>] $piece_smelter_add {__instance.m_fuelItem.m_itemData.m_shared.m_name} ({num})"); } } } } [HarmonyPatch] [<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(0)] private class OverrideOreHoverText { public static IEnumerable<MethodInfo> TargetMethods() { return new MethodInfo[2] { AccessTools.DeclaredMethod(typeof(Smelter), "OnHoverAddOre", (Type[])null, (Type[])null), AccessTools.DeclaredMethod(typeof(Smelter), "OnHoverEmptyOre", (Type[])null, (Type[])null) }; } public static void Postfix(Smelter __instance, ref string __result) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_011b: Unknown result type (might be due to invalid IL or missing references) KeyboardShortcut value = fillModifierKey.Value; if ((int)((KeyboardShortcut)(ref value)).MainKey == 0) { return; } int num = __instance.m_maxOre - __instance.GetQueueSize(); List<string> list = new List<string>(); foreach (ItemConversion item in __instance.m_conversion) { if (num <= 0) { break; } Player localPlayer = Player.m_localPlayer; int num2 = ((localPlayer != null) ? ((Humanoid)localPlayer).m_inventory.CountItems(item.m_from.m_itemData.m_shared.m_name, -1, true) : 0); if (num2 > 0) { list.Add($"{Math.Min(num, num2)} {item.m_from.m_itemData.m_shared.m_name}"); } num -= num2; } if (list.Count > 0) { __result += Localization.instance.Localize(string.Format("\n[<b><color=yellow>{0}</color> + <color=yellow>$KEY_Use</color></b>] {1} ({2})", fillModifierKey.Value, __instance.m_addOreTooltip, string.Join(", ", list))); } } } [HarmonyPatch(typeof(Windmill), "GetPowerOutput")] [<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(0)] private static class MakeWindmillIgnoreWind { private static bool Prefix(ref float __result) { if (ignoreWindspeed.Value == Toggle.On) { __result = 0.5f; return false; } return true; } } private const string ModName = "Conversion Size & Speed"; private const string ModVersion = "1.0.18"; private const string ModGUID = "org.bepinex.plugins.conversionsizespeed"; private readonly ConfigSync configSync = new ConfigSync("Conversion Size & Speed") { DisplayName = "Conversion Size & Speed", CurrentVersion = "1.0.18", MinimumRequiredVersion = "1.0.18" }; private static ConfigEntry<Toggle> serverConfigLocked = null; private static ConfigEntry<KeyboardShortcut> fillModifierKey = null; private static readonly Dictionary<string, ConfigEntry<int>> storageSpace = new Dictionary<string, ConfigEntry<int>>(); private static readonly Dictionary<string, ConfigEntry<int>> fuelSpace = new Dictionary<string, ConfigEntry<int>>(); private static readonly Dictionary<string, ConfigEntry<int>> fuelPerProduct = new Dictionary<string, ConfigEntry<int>>(); private static readonly Dictionary<string, ConfigEntry<int>> storageSpaceIncreasePerBoss = new Dictionary<string, ConfigEntry<int>>(); private static readonly Dictionary<string, ConfigEntry<int>> fuelSpaceIncreasePerBoss = new Dictionary<string, ConfigEntry<int>>(); private static readonly Dictionary<string, ConfigEntry<int>> conversionSpeed = new Dictionary<string, ConfigEntry<int>>(); private static ConfigEntry<Toggle> ignoreWindspeed = null; private static ConversionSizeSpeed mod = null; private ConfigEntry<T> config<[<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description); SyncedConfigEntry<T> syncedConfigEntry = configSync.AddConfigEntry<T>(val); syncedConfigEntry.SynchronizedConfig = synchronizedSetting; return val; } private ConfigEntry<T> config<[<6e719793-ab73-42bf-87ea-98a9bcf18ad8>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting); } public void Awake() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown mod = this; Assembly executingAssembly = Assembly.GetExecutingAssembly(); Harmony val = new Harmony("org.bepinex.plugins.conversionsizespeed"); val.PatchAll(executingAssembly); serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, new ConfigDescription("If on, only admins can change the configuration on a server.", (AcceptableValueBase)null, Array.Empty<object>())); configSync.AddLockingConfigEntry<Toggle>(serverConfigLocked); fillModifierKey = config<KeyboardShortcut>("1 - General", "Fill up modifier key", new KeyboardShortcut((KeyCode)304, Array.Empty<KeyCode>()), new ConfigDescription("Modifier key to hold, to fill all possible items at once. Clear value to disable this.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); } private static void FetchSmelterPieces(IEnumerable<GameObject> prefabs) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Expected O, but got Unknown //IL_02ff: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Expected O, but got Unknown //IL_0582: Unknown result type (might be due to invalid IL or missing references) //IL_058d: Expected O, but got Unknown //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Expected O, but got Unknown //IL_0639: Unknown result type (might be due to invalid IL or missing references) //IL_0644: Expected O, but got Unknown //IL_03d1: Unknown result type (might be due to invalid IL or missing references) //IL_03dc: Expected O, but got Unknown //IL_04b2: Unknown result type (might be due to invalid IL or missing references) //IL_04bd: Expected O, but got Unknown Localization val = new Localization(); val.SetupLanguage("English"); Regex regex = new Regex("['\\[\"\\]]"); foreach (Smelter item in from p in prefabs select p.GetComponentInChildren<Smelter>() into s where (Object)(object)((s != null) ? ((Component)s).GetComponentInParent<Piece>(true) : null) != (Object)null select s) { int num = 0; string name = ((Component)item).GetComponentInParent<Piece>(true).m_name; if (conversionSpeed.ContainsKey(name)) { continue; } if (Object.op_Implicit((Object)(object)item.m_addOreSwitch)) { storageSpace[name] = mod.config(regex.Replace(val.Localize(name), "") ?? "", "Storage space", item.m_maxOre, new ConfigDescription("Sets the maximum number of items that a " + val.Localize(name) + " can hold.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 1000), new object[1] { new ConfigurationManagerAttributes { Category = (Localization.instance.Localize(name) ?? ""), Order = (num -= 1) } })); storageSpace[name].SettingChanged += OnSizeChanged; storageSpaceIncreasePerBoss[name] = mod.config(regex.Replace(val.Localize(name), "") ?? "", "Storage space increase per boss", 0, new ConfigDescription("Increases the maximum number of items that a " + val.Localize(name) + " can hold for each boss killed.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1] { new ConfigurationManagerAttributes { Category = (Localization.instance.Localize(name) ?? ""), Order = (num -= 1), ShowRangeAsPercent = false } })); storageSpaceIncreasePerBoss[name].SettingChanged += OnSizeChanged; } if (Object.op_Implicit((Object)(object)item.m_addWoodSwitch)) { fuelSpace[name] = mod.config(regex.Replace(val.Localize(name), "") ?? "", "Fuel space", item.m_maxFuel, new ConfigDescription("Sets the maximum number of fuel that a " + val.Localize(name) + " can hold.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 1000), new object[1] { new ConfigurationManagerAttributes { Category = (Localization.instance.Localize(name) ?? ""), Order = (num -= 1) } })); fuelSpace[name].SettingChanged += OnSizeChanged; fuelSpaceIncreasePerBoss[name] = mod.config(regex.Replace(val.Localize(name), "") ?? "", "Fuel space increase per boss", 0, new ConfigDescription("Increases the maximum number of fuel that a " + val.Localize(name) + " can hold for each boss killed.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1] { new ConfigurationManagerAttributes { Category = (Localization.instance.Localize(name) ?? ""), Order = (num -= 1), ShowRangeAsPercent = false } })); fuelSpaceIncreasePerBoss[name].SettingChanged += OnSizeChanged; if (name != "$piece_bathtub") { fuelPerProduct[name] = mod.config(regex.Replace(val.Localize(name), "") ?? "", "Fuel per product", item.m_fuelPerProduct, new ConfigDescription("Sets how much fuel a " + val.Localize(name) + " needs per produced product.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 20), new object[1] { new ConfigurationManagerAttributes { Category = (Localization.instance.Localize(name) ?? ""), Order = (num -= 1) } })); fuelPerProduct[name].SettingChanged += OnFuelPerProductChanged; } } if (item.m_windmill != null) { ignoreWindspeed = mod.config(regex.Replace(val.Localize(name), "") ?? "", "Ignore wind intensity", Toggle.Off, new ConfigDescription("If on, " + val.Localize(name) + " always produces at average speed, regardless of wind.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = (Localization.instance.Localize(name) ?? ""), Order = (num -= 1) } })); } conversionSpeed[name] = mod.config(regex.Replace(val.Localize(name), "") ?? "", "Conversion time", (int)item.m_secPerProduct, new ConfigDescription("Time in seconds that a " + val.Localize(name) + " needs for one conversion.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, (name == "$piece_bathtub") ? 10000 : 1000), new object[1] { new ConfigurationManagerAttributes { Category = (Localization.instance.Localize(name) ?? ""), Order = (num -= 1) } })); conversionSpeed[name].SettingChanged += OnSpeedChanged; } } private static int BossesDead() { return new string[7] { "eikthyr", "gdking", "bonemass", "dragon", "goblinking", "queen", "fader" }.Count([<34766c07-c56e-41b2-a4bc-6c0fdd6a336b>NullableContext(0)] (string boss) => ZoneSystem.instance.GetGlobalKey("defeated_" + boss)); } private static void OnSizeChanged(object o, EventArgs e) { RecalculateAllSizes(); } private static void OnSpeedChanged(object o, EventArgs e) { UpdateConversionSpeed(); } private static void OnFuelPerProductChanged(object o, EventArgs e) { UpdateFuelPerProduct(); } private static void RecalculateAllSizes() { Smelter[] array = Object.FindObjectsOfType<Smelter>(); foreach (Smelter val in array) { string name = ((Component)val).GetComponentInParent<Piece>().m_name; if (Object.op_Implicit((Object)(object)val.m_addOreSwitch) && storageSpace.TryGetValue(name, out var value)) { val.m_maxOre = value.Value + storageSpaceIncreasePerBoss[name].Value * BossesDead(); } if (Object.op_Implicit((Object)(object)val.m_addWoodSwitch) && fuelSpace.TryGetValue(name, out var value2)) { val.m_maxFuel = value2.Value + fuelSpaceIncreasePerBoss[name].Value * BossesDead(); } } } private static void UpdateConversionSpeed() { Smelter[] array = Object.FindObjectsOfType<Smelter>(); foreach (Smelter val in array) { string name = ((Component)val).GetComponentInParent<Piece>().m_name; if (conversionSpeed.TryGetValue(name, out var value)) { val.m_secPerProduct = value.Value; } } } private static void UpdateFuelPerProduct() { Smelter[] array = Object.FindObjectsOfType<Smelter>(); foreach (Smelter val in array) { string name = ((Component)val).GetComponentInParent<Piece>().m_name; if (fuelPerProduct.ContainsKey(name) && Object.op_Implicit((Object)(object)val.m_addWoodSwitch)) { val.m_fuelPerProduct = fuelPerProduct[name].Value; } } } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [Embedded] [CompilerGenerated] 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] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry<T> 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; } } } internal 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] internal sealed class CustomSyncedValue<T> : 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] internal 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<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)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<ZNetPeer> 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<string> CurrentList = new List<string>(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List<string>(adminList.GetList()); List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, 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<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>(); public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>(); } [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 = false; public volatile int versionMatchQueued = -1; public readonly List<ZPackage> Package = new List<ZPackage>(); 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 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<Assembly, BufferingSocket>(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary<Assembly, BufferingSocket> __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<PackageEntry> entries = new List<PackageEntry>(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; 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 = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet<ConfigSync> configSyncs; private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>(); private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>(); private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action<bool>? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet<ConfigSync>(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry<T>(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(0L, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry<T>(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry<T>)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<CustomSyncedValueBase>(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_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: 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<long, string> 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 SortedDictionary<int, byte[]> value)) { value = new SortedDictionary<int, byte[]>(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair<long, string>(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) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); 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<OwnConfigEntryBase, object> 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<CustomSyncedValueBase, object> 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<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary<string, CustomSyncedValueBase> 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; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute<ConfigurationManagerAttributes>(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<bool> 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 fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); 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<bool> 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<object>().GetEnumerator(); } List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != 0) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List<IEnumerator<bool>> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); } } private 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<OwnConfigEntryBase>().SingleOrDefault(); } public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config) { return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault(); } private static T configAttribute<T>(ConfigEntryBase config) { return config.Description.Tags.OfType<T>().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>(); List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>()) { 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<string>) && 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<object> source = new List<object>(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [HarmonyPatch] [PublicAPI] internal class VersionCheck { private static readonly HashSet<VersionCheck> versionChecks; private static readonly Dictionary<string, string> 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<ZRpc> ValidatedClients = new List<ZRpc>(); 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 { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: 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<VersionCheck>(); notProcessedNames = new Dictionary<string, string>(); 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 flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion); bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". 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) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } 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<ZRpc, ZPackage>? 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; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.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_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: 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<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)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 }); } } } [HarmonyPrefix] [HarmonyPatch(typeof(ZNet), "Disconnect")] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPostfix] [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] private static void ShowConnectionError(FejdStartup __instance) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: 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_01de: 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_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0229: 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<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> 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<RectTransform>(); 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<RectTransform>(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } }
plugins/HBK-HBKHEIM/DualWield-1.0.12/DualWield.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using SkillManager; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("DualWield")] [assembly: AssemblyDescription("https://valheim.hexium.gg/mods/Smoothbrain/DualWield")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DualWield")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("497EB368-9410-49A7-A098-9E3905D0DA35")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.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 DualWield { [BepInPlugin("org.bepinex.plugins.dualwield", "Dual Wield", "1.0.12")] [BepInIncompatibility("org.bepinex.plugins.valheim_plus")] public class DualWield : BaseUnityPlugin { private enum Toggle { On = 1, Off = 0 } private struct AnimationBalancing { public float speed; public float damage; public float stamina; } private struct AnimationBalancingConfig { public ConfigEntry<float> speed; public ConfigEntry<float> damage; public ConfigEntry<float> stamina; } [HarmonyPatch(typeof(Player), "Start")] private static class Patch_Player_Start { private static void Postfix(Player __instance) { if (CustomRuntimeControllers.Count == 0 && Player.m_localPlayer != null) { CustomRuntimeControllers["Original"] = MakeAOC(new Dictionary<string, string>(), ((Character)__instance).m_animator.runtimeAnimatorController); CustomRuntimeControllers["DWswords"] = MakeAOC(replacementMap["DWswords"], ((Character)__instance).m_animator.runtimeAnimatorController); CustomRuntimeControllers["DWaxes"] = MakeAOC(replacementMap["DWaxes"], ((Character)__instance).m_animator.runtimeAnimatorController); } } } [HarmonyPatch(typeof(Humanoid), "EquipItem")] private static class Patch_Humanoid_EquipItem { private static bool CheckDualOneHandedWeaponEquip(Humanoid __instance, ItemData item, bool triggerEquipEffects) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Invalid comparison between Unknown and I4 //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Invalid comparison between Unknown and I4 Player val = (Player)(object)((__instance is Player) ? __instance : null); if (val != null) { ItemData rightItem = ((Humanoid)val).m_rightItem; if (rightItem != null && (int)rightItem.m_shared.m_itemType == 3 && ((Humanoid)val).m_rightItem.m_shared.m_skillType == item.m_shared.m_skillType && (int)item.m_shared.m_skillType != 5 && !DualWieldExclusion.Contains(((Object)item.m_dropPrefab).name)) { if (((Humanoid)val).m_leftItem != null) { ((Humanoid)val).UnequipItem(((Humanoid)val).m_leftItem, triggerEquipEffects); } ((Humanoid)val).m_leftItem = item; return true; } } return false; } private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> instrs = instructions.ToList(); int i = 0; while (i < instrs.Count) { yield return instrs[i]; if (i >= 4 && instrs[i - 4].opcode == OpCodes.Ldarg_1 && instrs[i - 1].opcode == OpCodes.Ldc_I4_3 && instrs[i].opcode == OpCodes.Bne_Un) { yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Ldarg_1, (object)null); yield return new CodeInstruction(OpCodes.Ldarg_2, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(Patch_Humanoid_EquipItem), "CheckDualOneHandedWeaponEquip", (Type[])null, (Type[])null)); yield return new CodeInstruction(OpCodes.Brtrue, instrs[i].operand); } int num = i + 1; i = num; } } private static void Prefix() { Patch_Humanoid_SetupEquipment.ManipulatingEquipment = true; } private static void Postfix() { Patch_Humanoid_SetupEquipment.ManipulatingEquipment = false; } } [HarmonyPatch(typeof(Humanoid), "UnequipAllItems")] private static class Patch_Humanoid_UnequipAllItems { private static void Prefix() { Patch_Humanoid_SetupEquipment.ManipulatingEquipment = true; } private static void Postfix() { Patch_Humanoid_SetupEquipment.ManipulatingEquipment = false; } } [HarmonyPatch(typeof(Humanoid), "SetupEquipment")] private static class Patch_Humanoid_SetupEquipment { public static bool ManipulatingEquipment; private static void Prefix(Humanoid __instance) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Invalid comparison between Unknown and I4 Player val = (Player)(object)((__instance is Player) ? __instance : null); if (val != null && !ManipulatingEquipment && ((Humanoid)val).m_rightItem == null) { ItemData leftItem = ((Humanoid)val).m_leftItem; if (leftItem != null && (int)leftItem.m_shared.m_itemType == 3) { ItemData leftItem2 = ((Humanoid)val).m_leftItem; ((Humanoid)val).UnequipItem(((Humanoid)val).m_leftItem, false); ((Humanoid)val).m_rightItem = leftItem2; ((Humanoid)val).m_rightItem.m_equipped = true; ((Humanoid)val).m_leftItem = null; } } } } [HarmonyPatch(typeof(Humanoid), "ShowHandItems")] private static class SwapHiddenItemsEquipOrder { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { FieldInfo leftHand = AccessTools.DeclaredField(typeof(Humanoid), "m_hiddenLeftItem"); FieldInfo rightHand = AccessTools.DeclaredField(typeof(Humanoid), "m_hiddenRightItem"); foreach (CodeInstruction instruction in instructions) { if (CodeInstructionExtensions.LoadsField(instruction, leftHand, false)) { yield return new CodeInstruction(OpCodes.Ldfld, (object)rightHand); } else if (CodeInstructionExtensions.LoadsField(instruction, rightHand, false)) { yield return new CodeInstruction(OpCodes.Ldfld, (object)leftHand); } else { yield return instruction; } } } } [HarmonyPatch(typeof(VisEquipment), "SetWeaponTrails")] private static class Patch_VisEquipment_SetWeaponTrails { private static void Postfix(VisEquipment __instance, bool enabled) { if (Object.op_Implicit((Object)(object)__instance.m_leftItemInstance)) { MeleeWeaponTrail[] componentsInChildren = __instance.m_leftItemInstance.GetComponentsInChildren<MeleeWeaponTrail>(); for (int i = 0; i < componentsInChildren.Length; i++) { componentsInChildren[i].Emit = enabled; } } } } [HarmonyPatch(typeof(VisEquipment), "AttachItem")] private static class Patch_VisEquipment_AttachBackItem { private static void Postfix(VisEquipment __instance, Transform joint) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) if (__instance.m_isPlayer) { if ((Object)(object)joint == (Object)(object)__instance.m_backMelee && joint.childCount > 1) { joint.GetChild(1).localPosition = new Vector3(-0.003f, 0f, 0.003f); joint.GetChild(1).localEulerAngles = new Vector3(0f, 80f, 0f); } if ((Object)(object)joint == (Object)(object)__instance.m_backTool && joint.childCount > 1) { joint.GetChild(1).localPosition = new Vector3(-0.0008f, -0.0052f, 0f); joint.GetChild(1).localEulerAngles = new Vector3(20f, 0f, 0f); } } } } [HarmonyPatch(typeof(ZSyncAnimation), "RPC_SetTrigger")] private static class Patch_ZSyncAnimation_RPC_SetTrigger { private static void Prefix(ZSyncAnimation __instance, string name) { Player player = ((Component)__instance).GetComponent<Player>(); if (player == null) { return; } SharedData val = sharedData((VisEquipment v) => v.m_currentRightItemHash); SharedData data = sharedData((VisEquipment v) => v.m_currentLeftItemHash); if (!HasAttack(data) && !HasAttack(val)) { return; } string key = "Original"; if (Onehanded(data) && Onehanded(val)) { key = "DWswords"; if (name == "mace_secondary" || val.m_attack.m_attackAnimation == "swing_axe" || val.m_secondaryAttack.m_attackAnimation == "axe_secondary") { key = "DWaxes"; } } if (CustomRuntimeControllers.TryGetValue(key, out RuntimeAnimatorController value)) { FastReplaceRAC(player, value); } bool HasAttack(SharedData? val2) { if (!HasAttackName(val2?.m_attack.m_attackAnimation)) { return HasAttackName(val2?.m_secondaryAttack.m_attackAnimation); } return true; } bool HasAttackName(string? anim) { if (anim == null || !name.StartsWith(anim, StringComparison.Ordinal) || anim.Length > name.Length + 1) { return anim == "swing_axe"; } return true; } static bool Onehanded(SharedData? val2) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 if (val2 == null) { return false; } return (int)val2.m_itemType == 3; } SharedData? sharedData(Func<VisEquipment, int> eq) { int num = eq(((Humanoid)player).m_visEquipment); if (num == 0) { return null; } GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(num); if (itemPrefab == null) { return null; } return itemPrefab.GetComponent<ItemDrop>()?.m_itemData.m_shared; } } } [HarmonyPatch(typeof(Attack), "OnAttackTrigger")] private static class Patch_Attack_OnAttackTrigger { private class DmgFactor { public float dmgFactor; public float knockback; } private static HitPointType? originalHitpointType; private static readonly Dictionary<SharedData, DmgFactor> alteredSharedData = new Dictionary<SharedData, DmgFactor>(); private static void ApplyDmgFactor(bool reverse, string attackAnimation) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Invalid comparison between Unknown and I4 //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Invalid comparison between Unknown and I4 foreach (KeyValuePair<SharedData, DmgFactor> alteredSharedDatum in alteredSharedData) { SharedData key = alteredSharedDatum.Key; SkillType skillType = key.m_skillType; bool flag = (((int)skillType == 3 || (int)skillType == 7) ? true : false); bool flag2 = flag; if (flag2) { bool flag3 = ((attackAnimation == "axe_secondary" || attackAnimation == "mace_secondary") ? true : false); flag2 = flag3; } if (flag2) { if (reverse) { key.m_attackForce = alteredSharedDatum.Value.knockback; } else { alteredSharedDatum.Value.knockback = key.m_attackForce; key.m_attackForce = 0f; } } float num = (reverse ? (1f / alteredSharedDatum.Value.dmgFactor) : alteredSharedDatum.Value.dmgFactor); ((DamageTypes)(ref key.m_damages)).Modify(num); key.m_backstabBonus /= num; } } private static void Prefix(Attack __instance) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Invalid comparison between Unknown and I4 //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Invalid comparison between Unknown and I4 //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0112: 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_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_018b: 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_016e: Unknown result type (might be due to invalid IL or missing references) if (!(__instance.m_character is Player)) { return; } SharedData val = __instance.m_character.m_leftItem?.m_shared; if (val == null) { return; } SharedData val2 = __instance.m_character.m_rightItem?.m_shared; if (val2 == null || (int)val.m_itemType != 3 || (int)val2.m_itemType != 3) { return; } if (attackMap.TryGetValue(((Object)((AnimatorClipInfo)(ref ((Character)__instance.m_character).m_animator.GetCurrentAnimatorClipInfo(0)[0])).clip).name, out var value) && balancingMap.TryGetValue(val2.m_skillType, out AnimationBalancingConfig[] value2)) { float dmgFactor = value2[value].damage.Value / 100f; alteredSharedData.Add(val2, new DmgFactor { dmgFactor = dmgFactor }); if (val2 != val) { alteredSharedData.Add(val, new DmgFactor { dmgFactor = dmgFactor }); } ApplyDmgFactor(reverse: false, __instance.m_attackAnimation); } originalHitpointType = __instance.m_hitPointtype; __instance.m_hitPointtype = (HitPointType)2; __instance.m_attackAngle = 0f - __instance.m_attackAngle; __instance.m_weapon = __instance.m_character.m_leftItem; SkillType skillType = __instance.m_character.m_leftItem.m_shared.m_skillType; if (skillMap.TryGetValue(skillType, out var value3)) { __instance.m_character.m_leftItem.m_shared.m_skillType = value3; } __instance.DoMeleeAttack(); __instance.m_character.m_leftItem.m_shared.m_skillType = skillType; __instance.m_weapon = __instance.m_character.m_rightItem; __instance.m_attackAngle = 0f - __instance.m_attackAngle; } private static void Postfix(Attack __instance) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (originalHitpointType.HasValue) { __instance.m_hitPointtype = originalHitpointType.Value; originalHitpointType = null; } ApplyDmgFactor(reverse: true, __instance.m_attackAnimation); alteredSharedData.Clear(); } } [HarmonyPatch(typeof(Player), "GetRandomSkillFactor")] private static class Patch_Skills_GetRandomSkillFactor { private static bool Prefix(Player __instance, SkillType skill, ref float __result) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (skillMap.ContainsValue(skill)) { __result = 0.03f + ((Character)__instance).GetSkillFactor(skill) * 1.5f; return false; } return true; } } [HarmonyPatch(typeof(Attack), "GetAttackStamina")] private static class Patch_Attack_GetAttackStamina { private static bool Prefix(Attack __instance, ref float __result) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: 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) bool flag = Onehanded(__instance.m_character.m_rightItem) && Onehanded(__instance.m_character.m_leftItem); if (__instance.m_character is Player && flag && balancingMap.TryGetValue(__instance.m_weapon.m_shared.m_skillType, out AnimationBalancingConfig[] value)) { float value2 = value[(__instance.m_attackChainLevels > 1) ? (__instance.m_currentAttackCainLevel + 1) : 0].stamina.Value; __result = value2 - value2 / 6f * ((Character)__instance.m_character).GetSkillFactor(__instance.m_weapon.m_shared.m_skillType) - value2 / 6f * ((Character)__instance.m_character).GetSkillFactor(skillMap[__instance.m_weapon.m_shared.m_skillType]); return false; } return true; static bool Onehanded(ItemData? item) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 if (item == null) { return false; } return (int)item.m_shared.m_itemType == 3; } } } [HarmonyPatch(typeof(Attack), "DoMeleeAttack")] private static class Patch_Attack_DoMeleeAttack { private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator gen) { MethodInfo quaternionCreator = AccessTools.DeclaredMethod(typeof(Quaternion), "Euler", new Type[3] { typeof(float), typeof(float), typeof(float) }, (Type[])null); FieldInfo attackAngle = AccessTools.DeclaredField(typeof(Attack), "m_attackAngle"); List<CodeInstruction> instrs = instructions.ToList(); int i = 0; while (i < instrs.Count) { if (instrs[i].opcode == OpCodes.Neg && instrs[i + 2].opcode == OpCodes.Call && CodeInstructionExtensions.OperandIs(instrs[i + 2], (MemberInfo)quaternionCreator)) { Label label = gen.DefineLabel(); yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Ldfld, (object)attackAngle); yield return new CodeInstruction(OpCodes.Ldc_R4, (object)0f); yield return new CodeInstruction(OpCodes.Ble, (object)label); yield return new CodeInstruction(OpCodes.Neg, (object)null); instrs[i + 1].labels.Add(label); } else { yield return instrs[i]; } if (instrs[i].opcode == OpCodes.Ldfld && CodeInstructionExtensions.OperandIs(instrs[i], (MemberInfo)attackAngle)) { yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(Mathf), "Abs", new Type[1] { typeof(float) }, (Type[])null)); } int num = i + 1; i = num; } } } private const string ModName = "Dual Wield"; private const string ModVersion = "1.0.12"; private const string ModGUID = "org.bepinex.plugins.dualwield"; private static readonly ConfigSync configSync = new ConfigSync("org.bepinex.plugins.dualwield") { DisplayName = "Dual Wield", CurrentVersion = "1.0.12" }; private static ConfigEntry<Toggle> serverConfigLocked = null; private static ConfigEntry<string> dualWieldExclusionList = null; private static ConfigEntry<float> experienceGainFactor = null; private static ConfigEntry<int> experienceLoss = null; private static ConfigEntry<Toggle> singleOffhandSkill = null; private static AssetBundle asset = null; private static readonly Dictionary<string, Dictionary<string, string>> replacementMap = new Dictionary<string, Dictionary<string, string>>(); private static readonly Dictionary<string, int> attackMap = new Dictionary<string, int>(); private static readonly Dictionary<string, AnimationClip> ExternalAnimations = new Dictionary<string, AnimationClip>(); private static readonly Dictionary<string, RuntimeAnimatorController> CustomRuntimeControllers = new Dictionary<string, RuntimeAnimatorController>(); private static readonly List<string> DualWieldExclusion = new List<string>(); private static readonly Dictionary<SkillType, SkillType> skillMap = new Dictionary<SkillType, SkillType>(); private static readonly Dictionary<SkillType, AnimationBalancing[]> balancingMapDefault = new Dictionary<SkillType, AnimationBalancing[]> { { (SkillType)7, new AnimationBalancing[4] { new AnimationBalancing { speed = 0.6f, damage = 0.9f, stamina = 40f }, new AnimationBalancing { speed = 0.8f, damage = 0.9f, stamina = 20f }, new AnimationBalancing { speed = 0.7f, damage = 0.95f, stamina = 20f }, new AnimationBalancing { speed = 0.6f, damage = 1.7f, stamina = 30f } } }, { (SkillType)3, new AnimationBalancing[4] { new AnimationBalancing { speed = 0.8f, damage = 0.6f, stamina = 35f }, new AnimationBalancing { speed = 1.2f, damage = 0.65f, stamina = 14f }, new AnimationBalancing { speed = 1.3f, damage = 0.75f, stamina = 15f }, new AnimationBalancing { speed = 1.5f, damage = 0.75f, stamina = 15f } } }, { (SkillType)2, new AnimationBalancing[4] { new AnimationBalancing { speed = 1.4f, damage = 0.3f, stamina = 32f }, new AnimationBalancing { speed = 1.4f, damage = 0.2f, stamina = 9f }, new AnimationBalancing { speed = 1.4f, damage = 0.2f, stamina = 9f }, new AnimationBalancing { speed = 2f, damage = 1.4f, stamina = 27f } } }, { (SkillType)1, new AnimationBalancing[4] { new AnimationBalancing { speed = 1f, damage = 0.5f, stamina = 40f }, new AnimationBalancing { speed = 1f, damage = 0.9f, stamina = 15f }, new AnimationBalancing { speed = 1f, damage = 0.9f, stamina = 15f }, new AnimationBalancing { speed = 1.2f, damage = 0.9f, stamina = 20f } } } }; private static readonly Dictionary<SkillType, AnimationBalancingConfig[]> balancingMap = new Dictionary<SkillType, AnimationBalancingConfig[]>(); private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description); configSync.AddConfigEntry<T>(val).SynchronizedConfig = synchronizedSetting; return val; } private ConfigEntry<T> config<T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting); } private static void InitSwordAnimation() { replacementMap["DWswords"] = new Dictionary<string, string> { ["fight idle"] = "BlockExternal", ["Block idle"] = "BlockExternal" }; foreach (KeyValuePair<string, int> item in attackMap) { replacementMap["DWswords"][item.Key] = ((item.Value == 0) ? "DualSwordsSpecial" : $"Attack{item.Value}External"); } } private static void InitAxesAnimation() { replacementMap["DWaxes"] = new Dictionary<string, string> { ["fight idle"] = "BlockExternal", ["Block idle"] = "BlockExternal" }; foreach (KeyValuePair<string, int> item in attackMap) { replacementMap["DWaxes"][item.Key] = ((item.Value == 0) ? "DualAxesSpecial" : $"Attack{item.Value}External"); } } public void Awake() { //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Expected O, but got Unknown //IL_0230: Unknown result type (might be due to invalid IL or missing references) //IL_023b: Expected O, but got Unknown //IL_02aa: Unknown result type (might be due to invalid IL or missing references) //IL_02b5: Expected O, but got Unknown //IL_0705: Unknown result type (might be due to invalid IL or missing references) //IL_06d2: 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_04f8: Unknown result type (might be due to invalid IL or missing references) //IL_054f: Unknown result type (might be due to invalid IL or missing references) //IL_0537: Unknown result type (might be due to invalid IL or missing references) //IL_0572: Unknown result type (might be due to invalid IL or missing references) //IL_057d: Expected O, but got Unknown //IL_058c: Unknown result type (might be due to invalid IL or missing references) //IL_0591: Unknown result type (might be due to invalid IL or missing references) //IL_05e8: Unknown result type (might be due to invalid IL or missing references) //IL_05d0: Unknown result type (might be due to invalid IL or missing references) //IL_060b: Unknown result type (might be due to invalid IL or missing references) //IL_0616: Expected O, but got Unknown //IL_0625: 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_067b: Unknown result type (might be due to invalid IL or missing references) //IL_0663: Unknown result type (might be due to invalid IL or missing references) //IL_069e: Unknown result type (might be due to invalid IL or missing references) //IL_06a9: Expected O, but got Unknown List<Skill> skills = new List<Skill>(); Skill skill = new Skill("Dual Axes", "dualaxes.png"); skill.Description.English("Increases the damage done with your left hand, when dual wielding axes."); skill.Configurable = false; skills.Add(skill); skill = new Skill("Dual Clubs", "dualclubs.png"); skill.Description.English("Increases the damage done with your left hand, when dual wielding clubs."); skill.Configurable = false; skills.Add(skill); skill = new Skill("Dual Knives", "dualknives.png"); skill.Description.English("Increases the damage done with your left hand, when dual wielding knives."); skill.Configurable = false; skills.Add(skill); skill = new Skill("Dual Swords", "dualswords.png"); skill.Description.English("Increases the damage done with your left hand, when dual wielding swords."); skill.Configurable = false; skills.Add(skill); skill = new Skill("Dual Offhand", "dualswords.png"); skill.Description.English("Increases the damage done with your left hand, when dual wielding."); skill.Configurable = false; skills.Add(skill); serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only."); configSync.AddLockingConfigEntry<Toggle>(serverConfigLocked); dualWieldExclusionList = config("1 - General", "Dual Wield Exclusion", "", "List prefab names of weapons that should be excluded from being dual-wielded. Comma separated."); dualWieldExclusionList.SettingChanged += UpdateExclusionList; experienceGainFactor = config("1 - General", "Dual Wield Experience Factor", 1f, new ConfigDescription("Factor for experience gained for the dual wielding skills.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>())); experienceGainFactor.SettingChanged += delegate { foreach (Skill item in skills) { item.SkillGainFactor = experienceGainFactor.Value; } }; foreach (Skill item2 in skills) { item2.SkillGainFactor = experienceGainFactor.Value; } experienceLoss = config("1 - General", "Skill Experience Loss", 5, new ConfigDescription("How much experience to lose in the dual wielding skills on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); experienceLoss.SettingChanged += delegate { foreach (Skill item3 in skills) { item3.SkillLoss = experienceLoss.Value; } }; foreach (Skill item4 in skills) { item4.SkillLoss = experienceLoss.Value; } singleOffhandSkill = config("1 - General", "Single Offhand Skill", Toggle.Off, new ConfigDescription("If on, all weapon types share a single offhand skill.", (AcceptableValueBase)null, Array.Empty<object>())); singleOffhandSkill.SettingChanged += delegate { ToggleOffhandSkill(); }; ToggleOffhandSkill(); asset = GetAssetBundle("dwanimations"); ExternalAnimations["Attack1External"] = asset.LoadAsset<AnimationClip>("Attack1"); ExternalAnimations["Attack2External"] = asset.LoadAsset<AnimationClip>("Attack2"); ExternalAnimations["Attack3External"] = asset.LoadAsset<AnimationClip>("Attack3"); ExternalAnimations["BlockExternal"] = asset.LoadAsset<AnimationClip>("DWblock"); ExternalAnimations["DualSwordsSpecial"] = asset.LoadAsset<AnimationClip>("DWspecial"); ExternalAnimations["DualAxesSpecial"] = asset.LoadAsset<AnimationClip>("DWspecial2"); attackMap["Sword-Attack-R4"] = 0; attackMap["Knife JumpAttack"] = 0; attackMap["MaceAltAttack"] = 0; attackMap["Attack1"] = 1; attackMap["Attack2"] = 2; attackMap["Attack3"] = 3; attackMap["Axe Secondary Attack"] = 0; attackMap["axe_swing"] = 1; attackMap["Axe combo 2"] = 2; attackMap["Axe combo 3"] = 3; attackMap["knife_slash0"] = 1; attackMap["knife_slash1"] = 2; attackMap["knife_slash2"] = 3; InitSwordAnimation(); InitAxesAnimation(); foreach (KeyValuePair<SkillType, AnimationBalancing[]> item5 in balancingMapDefault) { AnimationBalancingConfig[] array = new AnimationBalancingConfig[4]; for (int num = 0; num < item5.Value.Length; num++) { AnimationBalancing animationBalancing = item5.Value[num]; string text = ((num == 0) ? "Special attack" : $"Attack {num}"); array[num] = new AnimationBalancingConfig { damage = config("2 - " + ((object)item5.Key/*cast due to .constrained prefix*/).ToString(), text + " - Damage", animationBalancing.damage * 100f, new ConfigDescription((num == 0) ? $"The damage dealt by the special attack with {item5.Key} as a percentage of the weapon damage." : $"The damage dealt by the {num}. attack of the {item5.Key} attack combo as a percentage of the weapon damage.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 500f), Array.Empty<object>())), speed = config("2 - " + ((object)item5.Key/*cast due to .constrained prefix*/).ToString(), text + " - Speed", animationBalancing.speed * 100f, new ConfigDescription((num == 0) ? $"The attack speed of the special attack with {item5.Key} as a percentage." : $"The attack speed of the {num}. attack of the {item5.Key} attack combo. Provided as a percentage.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 300f), Array.Empty<object>())), stamina = config("2 - " + ((object)item5.Key/*cast due to .constrained prefix*/).ToString(), text + " - Stamina", animationBalancing.stamina, new ConfigDescription((num == 0) ? $"The stamina usage of the special attack with {item5.Key}." : $"The stamina usage of the {num}. attack of the {item5.Key} attack combo.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 200f), Array.Empty<object>())) }; } balancingMap[item5.Key] = array; } Assembly executingAssembly = Assembly.GetExecutingAssembly(); new Harmony("org.bepinex.plugins.dualwield").PatchAll(executingAssembly); UpdateExclusionList(null, null); AnimationSpeedManager.Add(delegate(Character character, double speed) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Invalid comparison between Unknown and I4 //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Invalid comparison between Unknown and I4 //IL_00a4: Unknown result type (might be due to invalid IL or missing references) if (!character.IsPlayer() || !character.InAttack()) { return speed; } Player val = (Player)character; if (((Humanoid)val).m_currentAttack == null) { return speed; } AnimatorClipInfo[] currentAnimatorClipInfo = character.m_animator.GetCurrentAnimatorClipInfo(0); if (currentAnimatorClipInfo.Length == 0) { return speed; } if (!attackMap.TryGetValue(((Object)((AnimatorClipInfo)(ref currentAnimatorClipInfo[0])).clip).name, out var value)) { return speed; } float num2 = 1f; SharedData val2 = sharedData(((Humanoid)val).m_visEquipment.m_currentLeftItemHash); if (val2 != null) { SharedData val3 = sharedData(((Humanoid)val).m_visEquipment.m_currentRightItemHash); if (val3 != null && (int)val2.m_itemType == 3 && (int)val3.m_itemType == 3 && balancingMap.TryGetValue(val3.m_skillType, out AnimationBalancingConfig[] value2)) { num2 = value2[value].speed.Value / 100f; } } return speed * (double)num2; }, 200); static SharedData? sharedData(int hash) { if (hash != 0) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(hash); if (itemPrefab == null) { return null; } return itemPrefab.GetComponent<ItemDrop>()?.m_itemData.m_shared; } return null; } } private static void ToggleOffhandSkill() { //IL_0077: 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_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) skillMap.Clear(); if (singleOffhandSkill.Value == Toggle.On) { skillMap.Add((SkillType)1, Skill.fromName("Dual Offhand")); skillMap.Add((SkillType)2, Skill.fromName("Dual Offhand")); skillMap.Add((SkillType)3, Skill.fromName("Dual Offhand")); skillMap.Add((SkillType)7, Skill.fromName("Dual Offhand")); } else { skillMap.Add((SkillType)7, Skill.fromName("Dual Axes")); skillMap.Add((SkillType)3, Skill.fromName("Dual Clubs")); skillMap.Add((SkillType)2, Skill.fromName("Dual Knives")); skillMap.Add((SkillType)1, Skill.fromName("Dual Swords")); } } private static void UpdateExclusionList(object? sender, EventArgs? e) { DualWieldExclusion.Clear(); string[] array = dualWieldExclusionList.Value.Split(new char[1] { ',' }); foreach (string text in array) { DualWieldExclusion.Add(text.Trim()); } } private static AssetBundle GetAssetBundle(string filename) { Assembly executingAssembly = Assembly.GetExecutingAssembly(); string name = executingAssembly.GetManifestResourceNames().Single((string str) => str.EndsWith(filename)); using Stream stream = executingAssembly.GetManifestResourceStream(name); return AssetBundle.LoadFromStream(stream); } private static RuntimeAnimatorController MakeAOC(Dictionary<string, string> replacement, RuntimeAnimatorController ORIGINAL) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown AnimatorOverrideController val = new AnimatorOverrideController(ORIGINAL); List<KeyValuePair<AnimationClip, AnimationClip>> list = new List<KeyValuePair<AnimationClip, AnimationClip>>(); AnimationClip[] animationClips = ((RuntimeAnimatorController)val).animationClips; foreach (AnimationClip val2 in animationClips) { string name = ((Object)val2).name; if (replacement.TryGetValue(name, out string value)) { AnimationClip val3 = Object.Instantiate<AnimationClip>(ExternalAnimations[value]); ((Object)val3).name = name; list.Add(new KeyValuePair<AnimationClip, AnimationClip>(val2, val3)); } else { list.Add(new KeyValuePair<AnimationClip, AnimationClip>(val2, val2)); } } val.ApplyOverrides((IList<KeyValuePair<AnimationClip, AnimationClip>>)list); return (RuntimeAnimatorController)(object)val; } private static void FastReplaceRAC(Player player, RuntimeAnimatorController replace) { if (!((Object)(object)((Character)player).m_animator.runtimeAnimatorController == (Object)(object)replace)) { ((Character)player).m_animator.runtimeAnimatorController = replace; ((Character)player).m_animator.Update(Time.deltaTime); } } } } namespace ServerSync { [PublicAPI] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry<T> 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; } } } internal 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] internal sealed class CustomSyncedValue<T> : 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] internal 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<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)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<ZNetPeer> 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<string> CurrentList = new List<string>(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List<string>(adminList.GetList()); List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, 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<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>(); public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>(); } [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 = false; public volatile int versionMatchQueued = -1; public readonly List<ZPackage> Package = new List<ZPackage>(); 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 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<Assembly, BufferingSocket>(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary<Assembly, BufferingSocket> __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<PackageEntry> entries = new List<PackageEntry>(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; 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 = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet<ConfigSync> configSyncs; private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>(); private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>(); private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action<bool>? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet<ConfigSync>(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry<T>(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(0L, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry<T>(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry<T>)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<CustomSyncedValueBase>(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_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: 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<long, string> 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 SortedDictionary<int, byte[]> value)) { value = new SortedDictionary<int, byte[]>(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair<long, string>(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) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); 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<OwnConfigEntryBase, object> 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<CustomSyncedValueBase, object> 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<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary<string, CustomSyncedValueBase> 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; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute<ConfigurationManagerAttributes>(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<bool> 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 fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); 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<bool> 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<object>().GetEnumerator(); } List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != 0) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List<IEnumerator<bool>> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); } } private 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<OwnConfigEntryBase>().SingleOrDefault(); } public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config) { return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault(); } private static T configAttribute<T>(ConfigEntryBase config) { return config.Description.Tags.OfType<T>().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>(); List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>()) { 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<string>) && 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<object> source = new List<object>(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [PublicAPI] [HarmonyPatch] internal class VersionCheck { private static readonly HashSet<VersionCheck> versionChecks; private static readonly Dictionary<string, string> 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<ZRpc> ValidatedClients = new List<ZRpc>(); 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 { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: 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<VersionCheck>(); notProcessedNames = new Dictionary<string, string>(); 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 flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion); bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". 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) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } 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<ZRpc, ZPackage>? 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; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.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_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: 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<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)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_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: 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_01de: 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_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0229: 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<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> 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<RectTransform>(); 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<RectTransform>(); 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 SkillManager { [PublicAPI] internal class Skill { public static class LocalizationCache { private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>(); internal static void LocalizationPostfix(Localization __instance, string language) { string key = localizations.FirstOrDefault<KeyValuePair<string, Localization>>((KeyValuePair<string, Localization> l) => l.Value == __instance).Key; if (key != null) { localizations.Remove(key); } if (!localizations.ContainsKey(language)) { localizations.Add(language, __instance); } } public static Localization ForLanguage(string? language = null) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out Localization value)) { return value; } value = new Localization(); if (language != null) { value.SetupLanguage(language); } return value; } } [PublicAPI] public class LocalizeKey { private static readonly List<LocalizeKey> keys = new List<LocalizeKey>(); public readonly string Key; public readonly Dictionary<string, string> Localizations = new Dictionary<string, string>(); public LocalizeKey(string key) { Key = key.Replace("$", ""); keys.Add(this); } public void Alias(string alias) { Localizations.Clear(); if (!alias.Contains("$")) { alias = "$" + alias; } Localizations["alias"] = alias; Localization.instance.AddWord(Key, Localization.instance.Localize(alias)); } public LocalizeKey English(string key) { return addForLang("English", key); } public LocalizeKey Swedish(string key) { return addForLang("Swedish", key); } public LocalizeKey French(string key) { return addForLang("French", key); } public LocalizeKey Italian(string key) { return addForLang("Italian", key); } public LocalizeKey German(string key) { return addForLang("German", key); } public LocalizeKey Spanish(string key) { return addForLang("Spanish", key); } public LocalizeKey Russian(string key) { return addForLang("Russian", key); } public LocalizeKey Romanian(string key) { return addForLang("Romanian", key); } public LocalizeKey Bulgarian(string key) { return addForLang("Bulgarian", key); } public LocalizeKey Macedonian(string key) { return addForLang("Macedonian", key); } public LocalizeKey Finnish(string key) { return addForLang("Finnish", key); } public LocalizeKey Danish(string key) { return addForLang("Danish", key); } public LocalizeKey Norwegian(string key) { return addForLang("Norwegian", key); } public LocalizeKey Icelandic(string key) { return addForLang("Icelandic", key); } public LocalizeKey Turkish(string key) { return addForLang("Turkish", key); } public LocalizeKey Lithuanian(string key) { return addForLang("Lithuanian", key); } public LocalizeKey Czech(string key) { return addForLang("Czech", key); } public LocalizeKey Hungarian(string key) { return addForLang("Hungarian", key); } public LocalizeKey Slovak(string key) { return addForLang("Slovak", key); } public LocalizeKey Polish(string key) { return addForLang("Polish", key); } public LocalizeKey Dutch(string key) { return addForLang("Dutch", key); } public LocalizeKey Portuguese_European(string key) { return addForLang("Portuguese_European", key); } public LocalizeKey Portuguese_Brazilian(string key) { return addForLang("Portuguese_Brazilian", key); } public LocalizeKey Chinese(string key) { return addForLang("Chinese", key); } public LocalizeKey Japanese(string key) { return addForLang("Japanese", key); } public LocalizeKey Korean(string key) { return addForLang("Korean", key); } public LocalizeKey Hindi(string key) { return addForLang("Hindi", key); } public LocalizeKey Thai(string key) { return addForLang("Thai", key); } public LocalizeKey Abenaki(string key) { return addForLang("Abenaki", key); } public LocalizeKey Croatian(string key) { return addForLang("Croatian", key); } public LocalizeKey Georgian(string key) { return addForLang("Georgian", key); } public LocalizeKey Greek(string key) { return addForLang("Greek", key); } public LocalizeKey Serbian(string key) { return addForLang("Serbian", key); } public LocalizeKey Ukrainian(string key) { return addForLang("Ukrainian", key); } private LocalizeKey addForLang(string lang, string value) { Localizations[lang] = value; if (Localization.instance.GetSelectedLanguage() == lang) { Localization.instance.AddWord(Key, value); } else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key)) { Localization.instance.AddWord(Key, value); } return this; } [HarmonyPriority(300)] internal static void AddLocalizedKeys(Localization __instance, string language) { foreach (LocalizeKey key in keys) { string value2; if (key.Localizations.TryGetValue(language, out string value) || key.Localizations.TryGetValue("English", out value)) { __instance.AddWord(key.Key, value); } else if (key.Localizations.TryGetValue("alias", out value2)) { __instance.AddWord(key.Key, Localization.instance.Localize(value2)); } } } } private class ConfigurationManagerAttributes { [UsedImplicitly] public string? Category; } [HarmonyPatch(typeof(Skills), "IsSkillValid")] private static class Patch_Skills_IsSkillValid { private static void Postfix(SkillType type, ref bool __result) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (!__result && skills.ContainsKey(type)) { __result = true; } } } private static readonly Dictionary<SkillType, Skill> skills; internal static readonly Dictionary<string, Skill> skillByName; private readonly string skillName; private readonly string internalSkillName; private readonly SkillDef skillDef; public readonly LocalizeKey Name; public readonly LocalizeKey Description; private float skillEffectFactor = 1f; private int skillLoss = 5; public bool Configurable = false; private static bool InitializedTerminal; private static Localization? _english; private static BaseUnityPlugin? _plugin; private static bool hasConfigSync; private static object? _configSync; public float SkillGainFactor { get { return skillDef.m_increseStep; } set { skillDef.m_increseStep = value; this.SkillGainFactorChanged?.Invoke(value); } } public float SkillEffectFactor { get { return skillEffectFactor; } set { skillEffectFactor = value; this.SkillEffectFactorChanged?.Invoke(value); } } public int SkillLoss { get { return skillLoss; } set { skillLoss = value; this.SkillLossChanged?.Invoke(value); } } private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English")); private static BaseUnityPlugin plugin { get { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown object obj = _plugin; if (obj == null) { BaseUnityPlugin val = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)Assembly.GetExecutingAssembly().DefinedTypes.First((TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); _plugin = val; obj = (object)val; } return (BaseUnityPlugin)obj; } } private static object? configSync { get { if (_configSync == null && hasConfigSync) { Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync"); if ((object)type != null) { _configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " SkillManager"); type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString()); type.GetProperty("IsLocked").SetValue(_configSync, true); } else { hasConfigSync = false; } } return _configSync; } } public event Action<float>? SkillGainFactorChanged; public event Action<float>? SkillEffectFactorChanged; public event Action<float>? SkillLossChanged; public Skill(string englishName, string icon) : this(englishName, loadSprite(icon, 64, 64)) { } public unsafe Skill(string englishName, Sprite icon) { //IL_0022: 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_0043: 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_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0082: 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_008d: Expected O, but got Unknown SkillType val = fromName(englishName); string text = new Regex("[^a-zA-Z]").Replace(englishName, "_"); skills[val] = this; skillByName[englishName] = this; skillDef = new SkillDef { m_description = "$skilldesc_" + text, m_icon = icon, m_increseStep = 1f, m_skill = val }; internalSkillName = text; skillName = englishName; Name = new LocalizeKey("skill_" + ((object)(*(SkillType*)(&val))/*cast due to .constrained prefix*/).ToString()).English(englishName); Description = new LocalizeKey("skilldesc_" + text); } public static SkillType fromName(string englishName) { return (SkillType)Math.Abs(StringExtensionMethods.GetStableHashCode(englishName)); } static Skill() { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Expected O, but got Unknown //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Expected O, but got Unknown //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Expected O, but got Unknown //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Expected O, but got Unknown //IL_0185: 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_01ad: Expected O, but got Unknown //IL_01ad: Expected O, but got Unknown //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Expected O, but got Unknown //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Expected O, but got Unknown //IL_023f: Expected O, but got Unknown skills = new Dictionary<SkillType, Skill>(); skillByName = new Dictionary<string, Skill>(); InitializedTerminal = false; hasConfigSync = true; Harmony val = new Harmony("org.bepinex.helpers.skillmanager"); val.Patch((MethodBase)AccessTools.
plugins/HBK-HBKHEIM/FirstPersonMode-1.4.6/FirstPersonMode.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using FirstPersonMode.Util; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; using UnityEngine.Rendering; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("FirstPersonMode")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Azumatt")] [assembly: AssemblyProduct("FirstPersonMode")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("E0E2F92E-557C-4A05-9D89-AA92A0BD75C4")] [assembly: AssemblyFileVersion("1.4.6")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.4.6.0")] [module: UnverifiableCode] 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; } } } namespace FirstPersonMode { public class FirstPersonBody : MonoBehaviour { private const string CloneName = "FPM_Headless"; private static readonly int CapeAshHash = StringExtensionMethods.GetStableHashCode("CapeAsh"); private static readonly Dictionary<Mesh, Mesh?> Headless = new Dictionary<Mesh, Mesh>(); private static readonly Dictionary<Mesh, bool> Headgear = new Dictionary<Mesh, bool>(); private Player _player; private VisEquipment _vis; private readonly List<(SkinnedMeshRenderer source, SkinnedMeshRenderer clone, Mesh mesh)> _clones = new List<(SkinnedMeshRenderer, SkinnedMeshRenderer, Mesh)>(); private readonly Dictionary<Renderer, ShadowCastingMode> _shadowOnly = new Dictionary<Renderer, ShadowCastingMode>(); private readonly List<SkinnedMeshRenderer> _skinned = new List<SkinnedMeshRenderer>(); private readonly List<Renderer> _renderers = new List<Renderer>(); private readonly List<Material> _mats = new List<Material>(); private AnimatorCullingMode? _cullingMode; private AnimatorUpdateMode? _updateMode; private bool _active; private bool _dirty; private bool _rolling; private void Awake() { _player = ((Component)this).GetComponent<Player>(); _vis = ((Component)this).GetComponent<VisEquipment>(); } private void OnDestroy() { Restore(); } internal void MarkDirty() { _dirty = true; } internal void Tick(bool fp) { if ((Object)(object)_vis == (Object)null || (Object)(object)_vis.m_bodyModel == (Object)null) { return; } foreach (var (val, _, val2) in _clones) { if ((Object)(object)val != (Object)null && (Object)(object)val.sharedMesh != (Object)(object)val2) { _dirty = true; } } bool flag = fp && FirstPersonModePlugin.HideBodyWhenRolling.Value == FirstPersonModePlugin.Toggle.On && ((Character)_player).InDodge(); if (flag != _rolling) { _rolling = flag; _dirty = true; } if (fp != _active || (fp && _dirty)) { Restore(); if (fp) { Apply(); } _active = fp; _dirty = false; } if (!_active) { return; } foreach (var (val3, val4, _) in _clones) { if (!((Object)(object)val3 == (Object)null) && !((Object)(object)val4 == (Object)null)) { ((Renderer)val3).GetSharedMaterials(_mats); if (_mats.Count > 0 && (Object)(object)((Renderer)val4).sharedMaterial != (Object)(object)_mats[0]) { ((Renderer)val4).sharedMaterials = _mats.ToArray(); } } } } private void Apply() { //IL_001f: 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) if ((Object)(object)((Character)_player).m_animator != (Object)null) { _cullingMode = ((Character)_player).m_animator.cullingMode; ((Character)_player).m_animator.cullingMode = (AnimatorCullingMode)0; _updateMode = ((Character)_player).m_animator.updateMode; ((Character)_player).m_animator.updateMode = (AnimatorUpdateMode)0; } if (_rolling) { ShadowOnly(_vis.m_visual); return; } if ((Object)(object)((Character)_player).m_head != (Object)null) { ShadowOnly(((Component)((Character)_player).m_head).gameObject); } if ((Object)(object)_vis.m_helmet != (Object)null) { ShadowOnly(((Component)_vis.m_helmet).gameObject); } ShadowOnly(_vis.m_helmetItemInstance); ShadowOnly(_vis.m_beardItemInstance); ShadowOnly(_vis.m_hairItemInstance); if (_vis.m_currentShoulderItemHash == CapeAshHash && _vis.m_shoulderItemInstances != null) { foreach (GameObject shoulderItemInstance in _vis.m_shoulderItemInstances) { ShadowOnly(shoulderItemInstance); } } _vis.m_visual.GetComponentsInChildren<SkinnedMeshRenderer>(_skinned); foreach (SkinnedMeshRenderer item in _skinned) { if (!((Object)(object)item.rootBone != (Object)(object)_vis.m_bodyModel.rootBone) && !(((Object)item).name == "FPM_Headless") && !_shadowOnly.ContainsKey((Renderer)(object)item)) { Mesh headless = GetHeadless(item, ((Character)_player).m_head); if ((Object)(object)headless != (Object)null) { ShadowOnly((Renderer)(object)item); MakeClone(item, headless); } else if ((Object)(object)item.sharedMesh != (Object)null && !item.sharedMesh.isReadable && IsHeadgear(item, ((Character)_player).m_head)) { ShadowOnly((Renderer)(object)item); } } } } private void Restore() { //IL_0031: 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_00bc: Unknown result type (might be due to invalid IL or missing references) if (_cullingMode.HasValue && (Object)(object)((Character)_player).m_animator != (Object)null) { ((Character)_player).m_animator.cullingMode = _cullingMode.Value; } if (_updateMode.HasValue && (Object)(object)((Character)_player).m_animator != (Object)null) { ((Character)_player).m_animator.updateMode = _updateMode.Value; } _cullingMode = null; _updateMode = null; foreach (KeyValuePair<Renderer, ShadowCastingMode> item2 in _shadowOnly) { if ((Object)(object)item2.Key != (Object)null) { item2.Key.shadowCastingMode = item2.Value; } } _shadowOnly.Clear(); foreach (var clone in _clones) { SkinnedMeshRenderer item = clone.clone; if ((Object)(object)item != (Object)null) { Object.Destroy((Object)(object)((Component)item).gameObject); } } _clones.Clear(); } private void MakeClone(SkinnedMeshRenderer source, Mesh headless) { //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_001b: 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) GameObject val = new GameObject("FPM_Headless") { layer = ((Component)source).gameObject.layer }; val.transform.SetParent(((Component)source).transform, false); SkinnedMeshRenderer val2 = val.AddComponent<SkinnedMeshRenderer>(); val2.sharedMesh = headless; val2.bones = source.bones; val2.rootBone = source.rootBone; ((Renderer)val2).localBounds = ((Renderer)source).localBounds; ((Renderer)val2).sharedMaterials = ((Renderer)source).sharedMaterials; ((Renderer)val2).shadowCastingMode = (ShadowCastingMode)0; _clones.Add((source, val2, source.sharedMesh)); } private void ShadowOnly(GameObject? instance) { if ((Object)(object)instance == (Object)null) { return; } instance.GetComponentsInChildren<Renderer>(true, _renderers); foreach (Renderer renderer in _renderers) { ShadowOnly(renderer); } } private void ShadowOnly(Renderer renderer) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (!_shadowOnly.ContainsKey(renderer)) { _shadowOnly[renderer] = renderer.shadowCastingMode; renderer.shadowCastingMode = (ShadowCastingMode)3; } } private static bool IsHeadgear(SkinnedMeshRenderer smr, Transform head) { //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: 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_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: 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_00f8: 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_0101: 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_0109: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_0132: 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_0152: 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_0172: 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_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) Mesh sharedMesh = smr.sharedMesh; if (Headgear.TryGetValue(sharedMesh, out var value)) { return value; } bool flag = false; Matrix4x4[] bindposes = sharedMesh.bindposes; Transform[] bones = smr.bones; int num = Array.IndexOf(bones, head); int num2 = (((Object)(object)head.parent != (Object)null) ? Array.IndexOf(bones, head.parent) : (-1)); int num3 = Array.IndexOf(bones, smr.rootBone); if (num >= 0 && num2 >= 0 && num3 >= 0 && Mathf.Max(new int[3] { num, num2, num3 }) < bindposes.Length) { Matrix4x4 inverse = ((Matrix4x4)(ref bindposes[num])).inverse; Vector3 val = ((Matrix4x4)(ref inverse)).MultiplyPoint3x4(Vector3.zero); inverse = ((Matrix4x4)(ref bindposes[num2])).inverse; Vector3 val2 = ((Matrix4x4)(ref inverse)).MultiplyPoint3x4(Vector3.zero); inverse = ((Matrix4x4)(ref bindposes[num3])).inverse; Vector3 val3 = ((Matrix4x4)(ref inverse)).MultiplyPoint3x4(Vector3.zero); Vector3 val4 = val - val3; Vector3 normalized = ((Vector3)(ref val4)).normalized; Bounds bounds = sharedMesh.bounds; float num4 = float.MaxValue; Vector3 val5 = default(Vector3); for (int i = 0; i < 8; i++) { ((Vector3)(ref val5))..ctor(((i & 1) == 0) ? ((Bounds)(ref bounds)).min.x : ((Bounds)(ref bounds)).max.x, ((i & 2) == 0) ? ((Bounds)(ref bounds)).min.y : ((Bounds)(ref bounds)).max.y, ((i & 4) == 0) ? ((Bounds)(ref bounds)).min.z : ((Bounds)(ref bounds)).max.z); num4 = Mathf.Min(num4, Vector3.Dot(val5 - val2, normalized)); } flag = normalized != Vector3.zero && num4 >= 0f; } Headgear[sharedMesh] = flag; return flag; } private static Mesh? GetHeadless(SkinnedMeshRenderer smr, Transform head) { //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) Mesh sharedMesh = smr.sharedMesh; if ((Object)(object)sharedMesh == (Object)null || !sharedMesh.isReadable) { return null; } if (Headless.TryGetValue(sharedMesh, out Mesh value)) { return value; } Transform[] bones = smr.bones; bool[] array = new bool[bones.Length]; for (int i = 0; i < bones.Length; i++) { array[i] = (Object)(object)bones[i] != (Object)null && bones[i].IsChildOf(head); } BoneWeight[] boneWeights = sharedMesh.boneWeights; bool[] array2 = new bool[boneWeights.Length]; for (int j = 0; j < boneWeights.Length; j++) { BoneWeight val = boneWeights[j]; float num = 0f; if (array[((BoneWeight)(ref val)).boneIndex0]) { num += ((BoneWeight)(ref val)).weight0; } if (array[((BoneWeight)(ref val)).boneIndex1]) { num += ((BoneWeight)(ref val)).weight1; } if (array[((BoneWeight)(ref val)).boneIndex2]) { num += ((BoneWeight)(ref val)).weight2; } if (array[((BoneWeight)(ref val)).boneIndex3]) { num += ((BoneWeight)(ref val)).weight3; } array2[j] = num > 0.5f; } Mesh val2 = Object.Instantiate<Mesh>(sharedMesh); bool flag = false; List<int> list = new List<int>(); for (int k = 0; k < sharedMesh.subMeshCount; k++) { int[] triangles = sharedMesh.GetTriangles(k); list.Clear(); for (int l = 0; l < triangles.Length; l += 3) { if (array2[triangles[l]] || array2[triangles[l + 1]] || array2[triangles[l + 2]]) { flag = true; continue; } list.Add(triangles[l]); list.Add(triangles[l + 1]); list.Add(triangles[l + 2]); } val2.SetTriangles(list, k, false); } if (!flag) { Object.Destroy((Object)(object)val2); val2 = null; } Headless[sharedMesh] = val2; return val2; } } [HarmonyPatch] internal static class CamCullMaterials { private static readonly int CamCull = Shader.PropertyToID("_CamCull"); private static readonly Dictionary<Material, float> Originals = new Dictionary<Material, float>(); private static readonly HashSet<Material> FromConfig = new HashSet<Material>(); [HarmonyPatch(typeof(InstanceRenderer), "OnEnable")] [HarmonyPrefix] private static void InstanceRendererOnEnable(InstanceRenderer __instance) { Transform parent = ((Component)__instance).transform.parent; if (((parent != null) ? ((Object)parent).name : null) == "grassroot") { Register(__instance.m_material); } } [HarmonyPatch(typeof(Pickable), "Awake")] [HarmonyPostfix] private static void PickableAwake(Pickable __instance) { RegisterAll(((Component)__instance).gameObject); } [HarmonyPatch(typeof(Plant), "Awake")] [HarmonyPostfix] private static void PlantAwake(Plant __instance) { RegisterAll(((Component)__instance).gameObject); } private static void RegisterAll(GameObject go) { Renderer[] componentsInChildren = go.GetComponentsInChildren<Renderer>(true); for (int i = 0; i < componentsInChildren.Length; i++) { Material[] sharedMaterials = componentsInChildren[i].sharedMaterials; for (int j = 0; j < sharedMaterials.Length; j++) { Register(sharedMaterials[j]); } } } [HarmonyPatch(typeof(ZNetScene), "Awake")] [HarmonyPostfix] private static void ZNetSceneAwake() { RebuildFromConfig(); } internal static void RebuildFromConfig() { foreach (Material item in FromConfig) { if (Originals.TryGetValue(item, out var value)) { Originals.Remove(item); if ((Object)(object)item != (Object)null) { item.SetFloat(CamCull, value); } } } FromConfig.Clear(); if ((Object)(object)ZNetScene.instance == (Object)null) { return; } string[] array = FirstPersonModePlugin.SolidPrefabs.Value.Split(new char[1] { ',' }); foreach (string text in array) { GameObject prefab = ZNetScene.instance.GetPrefab(text.Trim()); if ((Object)(object)prefab == (Object)null) { continue; } Renderer[] componentsInChildren = prefab.GetComponentsInChildren<Renderer>(true); for (int j = 0; j < componentsInChildren.Length; j++) { Material[] sharedMaterials = componentsInChildren[j].sharedMaterials; foreach (Material val in sharedMaterials) { if (Register(val)) { FromConfig.Add(val); } } } } } internal static void Refresh() { bool flag = Active(); foreach (KeyValuePair<Material, float> original in Originals) { if ((Object)(object)original.Key != (Object)null) { original.Key.SetFloat(CamCull, flag ? 0f : original.Value); } } } private static bool Active() { if (FirstPersonModePlugin.FirstPersonEnabled.Value == FirstPersonModePlugin.Toggle.On) { return Functions.IsInFirstPersonMode(); } return false; } private static bool Register(Material? material) { if ((Object)(object)material == (Object)null || Originals.ContainsKey(material) || !material.HasProperty(CamCull)) { return false; } float num = material.GetFloat(CamCull); if (num == 0f) { return false; } Originals[material] = num; if (Active()) { material.SetFloat(CamCull, 0f); } return true; } } [HarmonyPatch(typeof(ShieldDomeImageEffect), "OnRenderImage")] internal static class ShieldDomeRayPatch { private static readonly MethodInfo ViewportPointToRay = AccessTools.Method(typeof(Camera), "ViewportPointToRay", new Type[1] { typeof(Vector3) }, (Type[])null); private static readonly MethodInfo Replacement = AccessTools.Method(typeof(ShieldDomeRayPatch), "CornerRay", (Type[])null, (Type[])null); private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions) { foreach (CodeInstruction instruction in instructions) { if (CodeInstructionExtensions.Calls(instruction, ViewportPointToRay)) { instruction.opcode = OpCodes.Call; instruction.operand = Replacement; } yield return instruction; } } private static Ray CornerRay(Camera cam, Vector3 viewport) { //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_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0011: 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_003a: 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_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_0056: 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_005a: 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_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) Matrix4x4 val = cam.projectionMatrix; val = ((Matrix4x4)(ref val)).inverse; Vector3 val2 = ((Matrix4x4)(ref val)).MultiplyPoint(new Vector3(viewport.x * 2f - 1f, viewport.y * 2f - 1f, -1f)); Vector3 position = ((Component)cam).transform.position; val = cam.cameraToWorldMatrix; Vector3 val3 = ((Matrix4x4)(ref val)).MultiplyVector(val2); return new Ray(position, ((Vector3)(ref val3)).normalized); } } [HarmonyPatch(typeof(Player), "TestGhostClipping")] public static class Player_TestGhostClipping_Patch { private static bool Prefix() { return FirstPersonModePlugin.FirstPersonEnabled.Value == FirstPersonModePlugin.Toggle.On; } } [HarmonyPatch(typeof(Character), "SetVisible")] public static class CharacterSetVisiblePatch { private static bool Prefix(ref Character __instance, bool visible) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) if (FirstPersonModePlugin.FirstPersonEnabled.Value != FirstPersonModePlugin.Toggle.On) { return true; } if ((Object)(object)__instance.m_lodGroup == (Object)null || __instance.m_lodVisible == visible || (__instance.IsPlayer() && !visible)) { return false; } __instance.m_lodVisible = visible; __instance.m_lodGroup.localReferencePoint = (Vector3)(__instance.m_lodVisible ? __instance.m_originalLocalRef : new Vector3(999999f, 999999f, 999999f)); return false; } } [HarmonyPatch(typeof(GameCamera), "Awake")] public static class GameCameraAwakePatch { private static void Postfix(ref GameCamera __instance) { if (FirstPersonModePlugin.FirstPersonEnabled.Value == FirstPersonModePlugin.Toggle.On) { FirstPersonModePlugin.CachedCameraValues.ZoomSens = __instance.m_zoomSens; FirstPersonModePlugin.CachedCameraValues.MinDistance = __instance.m_minDistance; FirstPersonModePlugin.CachedCameraValues.MaxDistance = __instance.m_maxDistance; FirstPersonModePlugin.CachedCameraValues.FOV = __instance.m_fov; FirstPersonModePlugin.CachedCameraValues.NearClipPlaneMax = __instance.m_nearClipPlaneMax; FirstPersonModePlugin.CachedCameraValues.NearClipPlaneMin = __instance.m_nearClipPlaneMin; } } } [HarmonyPatch] internal static class VisEquipmentSkinBoundsPatch { [HarmonyPatch(typeof(VisEquipment), "AttachItem")] [HarmonyPostfix] private static void AttachItem(VisEquipment __instance, GameObject __result) { FixBounds(__instance, __result); } [HarmonyPatch(typeof(VisEquipment), "AttachArmor")] [HarmonyPostfix] private static void AttachArmor(VisEquipment __instance, List<GameObject> __result) { if (__result == null) { return; } foreach (GameObject item in __result) { FixBounds(__instance, item); } } private static void FixBounds(VisEquipment vis, GameObject instance) { //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) //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_0083: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)instance == (Object)null || (Object)(object)vis.m_bodyModel == (Object)null) { return; } FirstPersonBody component = ((Component)vis).GetComponent<FirstPersonBody>(); if ((Object)(object)component != (Object)null) { component.MarkDirty(); } Bounds localBounds = ((Renderer)vis.m_bodyModel).localBounds; Vector3 size = ((Bounds)(ref localBounds)).size; ((Bounds)(ref localBounds)).Expand(((Vector3)(ref size)).magnitude * 0.5f); SkinnedMeshRenderer[] componentsInChildren = instance.GetComponentsInChildren<SkinnedMeshRenderer>(); foreach (SkinnedMeshRenderer val in componentsInChildren) { if ((Object)(object)val.rootBone == (Object)(object)vis.m_bodyModel.rootBone) { ((Renderer)val).localBounds = localBounds; } } } } [HarmonyPatch(typeof(GameCamera), "UpdateCamera")] public static class GameCameraUpdatePatch { private static void Postfix(ref GameCamera __instance, float dt) { //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_018a: 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_01cd: Unknown result type (might be due to invalid IL or missing references) if (FirstPersonModePlugin.FirstPersonEnabled.Value != FirstPersonModePlugin.Toggle.On || (FirstPersonModePlugin.CHEInBuildMode != null && FirstPersonModePlugin.CHEIsLoaded && (bool)FirstPersonModePlugin.CHEInBuildMode.Invoke(null, null))) { return; } if (__instance.m_freeFly) { __instance.UpdateFreeFly(dt); __instance.UpdateCameraShake(dt); return; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } bool flag = Functions.IsInFirstPersonMode(); bool flag2 = FirstPersonModePlugin.ToggleFirstPersonHotkey.Value.IsKeyDown(); if ((__instance.m_distance <= 1f || FirstPersonModePlugin.FirstPersonEnforced.Value == FirstPersonModePlugin.Toggle.On) && !flag && !flag2) { flag = true; FirstPersonModePlugin.DynamicPerson.IsFirstPerson = true; Functions.SetupFP(ref __instance, ref localPlayer); } else if ((double)__instance.m_minDistance > 0.0 && flag && !flag2) { flag = false; Functions.ExitFP(ref __instance); Functions.SetFOV(__instance, FirstPersonModePlugin.CachedCameraValues.FOV); } if (flag2 && FirstPersonModePlugin.FirstPersonEnforced.Value != FirstPersonModePlugin.Toggle.On) { if (FirstPersonModePlugin.DynamicPerson.IsFirstPerson = !flag) { Functions.SetupFP(ref __instance, ref localPlayer); } else { __instance.m_distance = 1.5f; Functions.ExitFP(ref __instance); Functions.SetFOV(__instance, FirstPersonModePlugin.CachedCameraValues.FOV); } } __instance.m_camera.fieldOfView = __instance.m_fov; __instance.m_skyCamera.fieldOfView = __instance.m_fov; if (!Functions.ShouldIgnoreAdjustments(localPlayer)) { if (Functions.IsInFirstPersonMode()) { Functions.HandleFirstPersonMode(ref __instance); } else { Functions.HandleNotFirstPersonMode(ref __instance, localPlayer); } } Functions.HandleScrollOutDetection(ref __instance, localPlayer); if (((Character)localPlayer).IsDead() && Object.op_Implicit((Object)(object)localPlayer.GetRagdoll())) { ((Component)__instance).transform.LookAt(localPlayer.GetRagdoll().GetAverageBodyPosition()); } else if (((Character)localPlayer).IsAttached() && (Object)(object)localPlayer.GetAttachCameraPoint() != (Object)null) { Transform attachCameraPoint = localPlayer.GetAttachCameraPoint(); ((Component)__instance).transform.position = attachCameraPoint.position; ((Component)__instance).transform.rotation = attachCameraPoint.rotation; } else { Functions.SetCameraTransform(ref __instance, localPlayer, dt); } __instance.UpdateCameraShake(dt); } } [HarmonyPatch(typeof(Player), "AlwaysRotateCamera")] internal static class PlayerAlwaysRotateCameraPatch { private static void Postfix(Player __instance, ref bool __result) { if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && Functions.IsInFirstPersonMode()) { __result = true; } } } [HarmonyPatch(typeof(Player), "LateUpdate")] internal static class PlayerLateUpdatePatch { private static Transform _cachedSpine; private static Player _cachedPlayer; private static FirstPersonBody _body; private static void Postfix(Player __instance) { //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: 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_0101: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer) { return; } bool flag = FirstPersonModePlugin.FirstPersonEnabled.Value == FirstPersonModePlugin.Toggle.On && Functions.IsInFirstPersonMode(); if ((Object)(object)_body == (Object)null || (Object)(object)((Component)_body).gameObject != (Object)(object)((Component)__instance).gameObject) { _body = ((Component)__instance).GetComponent<FirstPersonBody>(); if ((Object)(object)_body == (Object)null) { _body = ((Component)__instance).gameObject.AddComponent<FirstPersonBody>(); } } _body.Tick(flag); if (flag && ((Character)__instance).IsDrawingBow()) { if ((Object)(object)_cachedSpine == (Object)null || (Object)(object)_cachedPlayer != (Object)(object)__instance) { _cachedSpine = Utils.FindChild(((Component)__instance).transform, "Spine", (IterativeSearchType)0); _cachedPlayer = __instance; } if (!((Object)(object)_cachedSpine == (Object)null)) { Quaternion rotation = ((Component)((Character)__instance).m_eye).transform.rotation; Vector3 eulerAngles = ((Quaternion)(ref rotation)).eulerAngles; Transform cachedSpine = _cachedSpine; rotation = _cachedSpine.rotation; cachedSpine.rotation = Quaternion.Euler(((Quaternion)(ref rotation)).eulerAngles.x, eulerAngles.y + 90f, eulerAngles.x); } } } } [HarmonyPatch(typeof(Humanoid), "UseMeleeCamera")] internal static class HumanoidUseMeleeCameraPatch { private static void Postfix(Humanoid __instance, ref bool __result) { if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && FirstPersonModePlugin.CenterBehindPlayer.Value == FirstPersonModePlugin.Toggle.On) { __result = true; } } } [HarmonyPatch(typeof(DamageText), "Awake")] internal static class DamageTextAwakePatch { private static void Prefix(DamageText __instance) { __instance.m_maxTextDistance = 100f; __instance.m_smallFontDistance = 35f; } } [HarmonyPatch(typeof(Hud), "UpdateShipHud")] internal static class UpdateHud_fixshiphud { private static void Postfix(Hud __instance, Player player) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) if (FirstPersonModePlugin.FirstPersonEnabled.Value == FirstPersonModePlugin.Toggle.On) { Camera mainCamera = Utils.GetMainCamera(); if (!((Object)(object)mainCamera == (Object)null) && Functions.IsInFirstPersonMode()) { __instance.m_shipControlsRoot.transform.position = new Vector3((float)mainCamera.pixelWidth * 0.5f, (float)mainCamera.pixelHeight * 0.2f, 0f); } } } } [BepInPlugin("Azumatt.FirstPersonMode", "FirstPersonMode", "1.4.6")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class FirstPersonModePlugin : BaseUnityPlugin { public enum Toggle { On = 1, Off = 0 } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct DynamicPerson { public static bool IsFirstPerson = false; public static Vector3 NoFp3RdOffset = Vector3.zero; public static Vector3 NoFpFPSOffset = Vector3.zero; } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct CachedCameraValues { public static float ZoomSens = 10f; public static float MinDistance = 1f; public static float MaxDistance = 8f; public static float FOV = 8f; public static float NearClipPlaneMax = 0.5f; public static float NearClipPlaneMin = 0.1f; } private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [UsedImplicitly] public string Category; [UsedImplicitly] public Action<ConfigEntryBase> CustomDrawer; } internal const string ModName = "FirstPersonMode"; internal const string ModVersion = "1.4.6"; internal const string Author = "Azumatt"; private const string ModGUID = "Azumatt.FirstPersonMode"; private static string ConfigFileName = "Azumatt.FirstPersonMode.cfg"; private static string ConfigFileFullPath; internal static string ConnectionError; private const string OldSolidPrefabs = "SwampTree1,SwampTree1_Stub,SwampTree2,SwampTree2_darkland,SwampTree2_log"; internal readonly Harmony _harmony = new Harmony("Azumatt.FirstPersonMode"); private static readonly ConfigSync ConfigSync; public static bool CHEIsLoaded; private Assembly _cheAssembly; public static MethodInfo? CHEInBuildMode; public static readonly ManualLogSource FirstPersonModeLogger; internal static FirstPersonModePlugin Instance; private static ConfigEntry<Toggle> _serverConfigLocked; internal static ConfigEntry<Toggle> FirstPersonEnabled; internal static ConfigEntry<Toggle> FirstPersonEnforced; internal static ConfigEntry<Toggle> CenterBehindPlayer; internal static ConfigEntry<Toggle> HideBodyWhenRolling; internal static ConfigEntry<float> DefaultFOV; internal static ConfigEntry<KeyboardShortcut> ToggleFirstPersonHotkey; internal static ConfigEntry<KeyboardShortcut> RaiseFOVHotkey; internal static ConfigEntry<KeyboardShortcut> LowerFOVHotkey; internal static ConfigEntry<float> NearClipPlane; internal static ConfigEntry<Vector3> OffsetWhenAiming; internal static ConfigEntry<Vector3> CameraOffset; internal static ConfigEntry<float> HeadBob; internal static ConfigEntry<float> IdleSwayDeadzone; internal static ConfigEntry<string> SolidPrefabs; public void Awake() { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Expected O, but got Unknown //IL_017f: 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_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Expected O, but got Unknown //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Expected O, but got Unknown //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02fb: Unknown result type (might be due to invalid IL or missing references) //IL_032e: Unknown result type (might be due to invalid IL or missing references) Instance = this; if (Chainloader.PluginInfos.ContainsKey("org.bepinex.plugins.valheim_plus")) { FirstPersonModeLogger.LogWarning((object)"Valheim Plus detected, disabling FirstPersonMode to prevent camera stuttering. Please use the First Person mode in Valheim Plus or disable it to use this mod."); return; } _serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, new ConfigDescription("If on, the configuration is locked and can be changed by server admins only. All Synced With Server configurations will be enforced to the clients.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = 8 } })); ConfigSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked); FirstPersonEnabled = config("1 - Toggles", "Enable First Person", Toggle.On, "If on, First Person is enabled."); FirstPersonEnabled.SettingChanged += delegate { CamCullMaterials.Refresh(); }; FirstPersonEnforced = config("1 - Toggles", "Enforce First Person", Toggle.Off, "If on, First Person is enforced to always be on. Respects the Enable First Person configuration and both must be on for First Person to be enforced."); CenterBehindPlayer = config("1 - Toggles", "Center Behind Player", Toggle.Off, "If on, the camera will center behind the player when not in First Person. This is useful for people who want to play in third person but want the camera to be centered behind the player and not a little offset like vanilla has it.", synchronizedSetting: false); HideBodyWhenRolling = config("1 - Toggles", "Hide Body When Rolling", Toggle.On, "If on, your body is hidden while dodge rolling in First Person so it doesn't block the view. Your shadow stays.", synchronizedSetting: false); DefaultFOV = config("2 - Camera", "Default FOV", 65f, "Default FOV for First Person.", synchronizedSetting: false); NearClipPlane = config("2 - Camera", "Near Clip Plane", 0.02f, new ConfigDescription("Nearest distance at which things are rendered in first person. Keep it small or weapons held close to your face (daggers, blocking) disappear.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 0.3f), Array.Empty<object>()), synchronizedSetting: false); CameraOffset = config<Vector3>("2 - Camera", "Camera Offset", new Vector3(0f, 0.15f, 0.071f), "Camera offset from your head in first person, relative to where you're looking. X is right, Y is up, Z is forward. Clamped to half a meter each way.", synchronizedSetting: false); OffsetWhenAiming = config<Vector3>("2 - Camera", "Offset When Aiming", new Vector3(-0.08f, 0.2f, 0f), "Same thing, used while drawing a bow. Higher X moves the camera right, away from the arrow.", synchronizedSetting: false); HeadBob = config("2 - Camera", "Head Bob", 1f, new ConfigDescription("How much of the walk animation's bounce reaches the camera. 1 is vanilla, 0 smooths it out completely.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()), synchronizedSetting: false); IdleSwayDeadzone = config("2 - Camera", "Idle Sway Deadzone", 0.05f, new ConfigDescription("How far (in meters) your head can sway while standing still before the camera follows it. Stops the idle breathing from wobbling the view. 0 turns it off.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 0.1f), Array.Empty<object>()), synchronizedSetting: false); SolidPrefabs = config("2 - Camera", "Solid Prefabs", "SwampTree1,SwampTree1_Stub,SwampTree2,SwampTree2_darkland,SwampTree2_log,AshlandsTree1,AshlandsTree3,AshlandsTree4,AshlandsTree5,AshlandsTree6,AshlandsTree6_big", "Comma separated prefab names that shouldn't fade out when your camera is inside them in first person. Grass and pickables are always handled.", synchronizedSetting: false); if (SolidPrefabs.Value == "SwampTree1,SwampTree1_Stub,SwampTree2,SwampTree2_darkland,SwampTree2_log") { SolidPrefabs.Value = (string)((ConfigEntryBase)SolidPrefabs).DefaultValue; } SolidPrefabs.SettingChanged += delegate { CamCullMaterials.RebuildFromConfig(); }; ToggleFirstPersonHotkey = config<KeyboardShortcut>("3 - Keyboard Shortcuts", "Toggle First Person Shortcut", new KeyboardShortcut((KeyCode)104, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Keyboard Shortcut needed to toggle First Person. If FirstPersonMode is enforced, you cannot toggle.", synchronizedSetting: false); RaiseFOVHotkey = config<KeyboardShortcut>("3 - Keyboard Shortcuts", "Raise FOV Shortcut", new KeyboardShortcut((KeyCode)280, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Keyboard Shortcut needed to raise FOV.", synchronizedSetting: false); LowerFOVHotkey = config<KeyboardShortcut>("3 - Keyboard Shortcuts", "Lower FOV Shortcut", new KeyboardShortcut((KeyCode)281, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Keyboard Shortcut needed to lower FOV.", synchronizedSetting: false); CleanupOldConfigEntries(); CHEIsLoaded = Chainloader.PluginInfos.ContainsKey("Azumatt.BuildCameraCHE"); if (CHEIsLoaded) { _cheAssembly = ((object)Chainloader.PluginInfos["Azumatt.BuildCameraCHE"].Instance).GetType().Assembly; CHEInBuildMode = _cheAssembly.GetType("Valheim_Build_Camera.Utils")?.GetMethod("InBuildMode", BindingFlags.Static | BindingFlags.Public); } Assembly executingAssembly = Assembly.GetExecutingAssembly(); _harmony.PatchAll(executingAssembly); SetupWatcher(); } private void Start() { AutoDoc(); PPCompat.Init(); } private void AutoDoc() { } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); } private void SetupWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private void ReadConfigValues(object sender, FileSystemEventArgs e) { if (!File.Exists(ConfigFileFullPath)) { return; } try { FirstPersonModeLogger.LogDebug((object)"ReadConfigValues called"); ((BaseUnityPlugin)this).Config.Reload(); } catch { FirstPersonModeLogger.LogError((object)("There was an issue loading your " + ConfigFileName)); FirstPersonModeLogger.LogError((object)"Please check your config entries for spelling and format!"); } } private void CleanupOldConfigEntries() { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Expected O, but got Unknown //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Expected O, but got Unknown //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Expected O, but got Unknown //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Expected O, but got Unknown //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Expected O, but got Unknown //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Expected O, but got Unknown //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Expected O, but got Unknown //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Expected O, but got Unknown //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Expected O, but got Unknown if (AccessTools.Property(((object)((BaseUnityPlugin)this).Config).GetType(), "OrphanedEntries")?.GetValue(((BaseUnityPlugin)this).Config) is IDictionary dictionary && (0u | ((dictionary.Contains((object)new ConfigDefinition("2 - Camera", "Max Deviation")) && RemoveEntry(dictionary, new ConfigDefinition("2 - Camera", "Max Deviation"))) ? 1u : 0u) | ((dictionary.Contains((object)new ConfigDefinition("2 - Camera", "Slerp Multiplier")) && RemoveEntry(dictionary, new ConfigDefinition("2 - Camera", "Slerp Multiplier"))) ? 1u : 0u) | ((dictionary.Contains((object)new ConfigDefinition("1 - Toggles", "Hide Head")) && RemoveEntry(dictionary, new ConfigDefinition("1 - Toggles", "Hide Head"))) ? 1u : 0u) | ((dictionary.Contains((object)new ConfigDefinition("2 - Camera", "NearClipPlaneMin")) && RemoveEntry(dictionary, new ConfigDefinition("2 - Camera", "NearClipPlaneMin"))) ? 1u : 0u) | ((dictionary.Contains((object)new ConfigDefinition("2 - Camera", "NearClipPlaneMax")) && RemoveEntry(dictionary, new ConfigDefinition("2 - Camera", "NearClipPlaneMax"))) ? 1u : 0u) | ((dictionary.Contains((object)new ConfigDefinition("2 - Camera", "OffsetWhenAiming")) && RemoveEntry(dictionary, new ConfigDefinition("2 - Camera", "OffsetWhenAiming"))) ? 1u : 0u)) != 0) { ((BaseUnityPlugin)this).Config.Save(); ((BaseUnityPlugin)this).Config.Reload(); } } private static bool RemoveEntry(IDictionary dict, ConfigDefinition key) { dict.Remove(key); return true; } private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val); ConfigSync.AddConfigEntry<T>(val2).SynchronizedConfig = synchronizedSetting; return val2; } private ConfigEntry<T> config<T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting); } static FirstPersonModePlugin() { string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName; ConnectionError = ""; ConfigSync = new ConfigSync("Azumatt.FirstPersonMode") { DisplayName = "FirstPersonMode", CurrentVersion = "1.4.6", MinimumRequiredVersion = "1.4.6", ModRequired = false }; FirstPersonModeLogger = Logger.CreateLogSource("FirstPersonMode"); _serverConfigLocked = null; FirstPersonEnabled = null; FirstPersonEnforced = null; CenterBehindPlayer = null; HideBodyWhenRolling = null; DefaultFOV = null; ToggleFirstPersonHotkey = null; RaiseFOVHotkey = null; LowerFOVHotkey = null; NearClipPlane = null; OffsetWhenAiming = null; CameraOffset = null; HeadBob = null; IdleSwayDeadzone = null; SolidPrefabs = null; } } } namespace FirstPersonMode.Util { public class PPCompat { public static bool IsInAEM; public static void Init() { if (Chainloader.PluginInfos.TryGetValue("Azumatt_and_ValheimPlusDevs.PerfectPlacement", out var value) && value != null && !((Object)(object)value.Instance == (Object)null) && (value.Metadata.Version.Major > 1 || (value.Metadata.Version.Major == 1 && value.Metadata.Version.Minor > 1) || (value.Metadata.Version.Major == 1 && value.Metadata.Version.Minor == 1 && value.Metadata.Version.Build >= 10))) { FirstPersonModePlugin.Instance._harmony.PatchAll(typeof(PPCompat)); } } [HarmonyPatch("PerfectPlacement.Patches.AEM, PerfectPlacement", "IsInAemMode")] [HarmonyPostfix] public static void IsInAemMode(ref bool __result) { if ((Object)(object)Player.m_localPlayer != (Object)null) { IsInAEM = __result; } } } public static class KeyboardExtensions { public static bool IsKeyDown(this KeyboardShortcut shortcut) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey == 0) { return false; } bool keyDown = Input.GetKeyDown(((KeyboardShortcut)(ref shortcut)).MainKey); bool flag = ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey); return keyDown && flag; } public static bool IsKeyHeld(this KeyboardShortcut shortcut) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKey(((KeyboardShortcut)(ref shortcut)).MainKey)) { return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey); } return false; } } public static class Functions { private static Vector3 _smoothedHead; private static Vector3 _headVelocity; private static Player? _headPlayer; private static Vector3 _headAnchor; private static float _deadzone; private static Vector3 _anchorLook; internal static bool ShouldIgnoreAdjustments(Player localPlayer) { Chat instance = Chat.instance; if ((instance == null || !instance.HasFocus()) && !Console.IsVisible() && !InventoryGui.IsVisible() && !StoreGui.IsVisible() && !Menu.IsVisible() && !Minimap.IsOpen() && !((Character)localPlayer).InCutscene() && !((Character)localPlayer).InPlaceMode()) { return IsInAEM(); } return true; } public static bool IsInAEM() { return PPCompat.IsInAEM; } public static bool IsInFirstPersonMode() { return FirstPersonModePlugin.DynamicPerson.IsFirstPerson; } internal static void HandleScrollOutDetection(ref GameCamera __instance, Player localPlayer) { if (IsInFirstPersonMode() && FirstPersonModePlugin.FirstPersonEnforced.Value != FirstPersonModePlugin.Toggle.On && ((((Character)localPlayer).TakeInput() && Input.GetAxis("Mouse ScrollWheel") < 0f && !((Character)localPlayer).InPlaceMode()) || (ZInput.GetButton("JoyAltKeys") && !Hud.InRadial() && ZInput.GetButton("JoyCamZoomOut")))) { GameCamera obj = __instance; obj.m_minDistance += 2f; } } private static bool InTempFOV(GameCamera cam) { if (cam.m_fovInertia != 0f) { return cam.m_fovTarget != cam.m_fovBase; } return false; } internal static void SetFOV(GameCamera cam, float fov) { bool num = InTempFOV(cam); cam.m_fovBase = fov; if (!num) { cam.m_fovTarget = fov; cam.m_fov = fov; } } internal static void SetupFP(ref GameCamera __instance, ref Player localPlayer) { //IL_002c: 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_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) //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) //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) FirstPersonModePlugin.CachedCameraValues.MaxDistance = __instance.m_maxDistance; FirstPersonModePlugin.CachedCameraValues.FOV = (InTempFOV(__instance) ? __instance.m_fovBase : __instance.m_fov); FirstPersonModePlugin.DynamicPerson.NoFp3RdOffset = __instance.m_3rdOffset; FirstPersonModePlugin.DynamicPerson.NoFpFPSOffset = __instance.m_fpsOffset; __instance.m_3rdOffset = Vector3.zero; __instance.m_fpsOffset = Vector3.zero; __instance.m_minDistance = 0f; __instance.m_maxDistance = 0f; __instance.m_zoomSens = 0f; __instance.m_nearClipPlaneMax = FirstPersonModePlugin.NearClipPlane.Value; __instance.m_nearClipPlaneMin = FirstPersonModePlugin.NearClipPlane.Value; SetFOV(__instance, FirstPersonModePlugin.DefaultFOV.Value); CamCullMaterials.Refresh(); } internal static void ExitFP(ref GameCamera __instance) { //IL_0008: 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_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) FirstPersonModePlugin.DynamicPerson.IsFirstPerson = false; __instance.m_3rdOffset = FirstPersonModePlugin.DynamicPerson.NoFp3RdOffset; __instance.m_fpsOffset = FirstPersonModePlugin.DynamicPerson.NoFpFPSOffset; __instance.m_minDistance = FirstPersonModePlugin.CachedCameraValues.MinDistance; __instance.m_maxDistance = FirstPersonModePlugin.CachedCameraValues.MaxDistance; __instance.m_zoomSens = FirstPersonModePlugin.CachedCameraValues.ZoomSens; __instance.m_nearClipPlaneMax = FirstPersonModePlugin.CachedCameraValues.NearClipPlaneMax; __instance.m_nearClipPlaneMin = FirstPersonModePlugin.CachedCameraValues.NearClipPlaneMin; CamCullMaterials.Refresh(); } internal static void HandleFirstPersonMode(ref GameCamera __instance) { //IL_0005: 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) if (FirstPersonModePlugin.RaiseFOVHotkey.Value.IsKeyDown()) { ConfigEntry<float> defaultFOV = FirstPersonModePlugin.DefaultFOV; defaultFOV.Value += 1f; SetFOV(__instance, FirstPersonModePlugin.DefaultFOV.Value); Console instance = Console.instance; if (instance != null) { ((Terminal)instance).AddString($"Changed fov to: {FirstPersonModePlugin.DefaultFOV.Value}"); } } else if (FirstPersonModePlugin.LowerFOVHotkey.Value.IsKeyDown()) { ConfigEntry<float> defaultFOV2 = FirstPersonModePlugin.DefaultFOV; defaultFOV2.Value -= 1f; SetFOV(__instance, FirstPersonModePlugin.DefaultFOV.Value); Console instance2 = Console.instance; if (instance2 != null) { ((Terminal)instance2).AddString($"Changed fov to: {FirstPersonModePlugin.DefaultFOV.Value}"); } } } internal static void HandleNotFirstPersonMode(ref GameCamera __instance, Player localPlayer) { _ = __instance.m_minDistance; float num = Input.GetAxis("Mouse ScrollWheel"); if (Player.m_debugMode) { num = ScrollReturn(__instance, num); } GameCamera obj = __instance; obj.m_distance -= num / 3f * __instance.m_zoomSens; float num2 = (((Object)(object)localPlayer.GetControlledShip() != (Object)null) ? __instance.m_maxDistanceBoat : __instance.m_maxDistance); __instance.m_distance = Mathf.Clamp(Mathf.Lerp(__instance.m_distance, Mathf.Clamp(__instance.m_distance, 0f, num2), 0.1f), 0f, num2); } internal static float ScrollReturn(GameCamera cam, float scroll) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0048: 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) if (ZInput.GetKey((KeyCode)304, true) && ZInput.GetKey((KeyCode)99, true) && !Console.IsVisible()) { Vector2 mouseDelta = ZInput.GetMouseDelta(); EnvMan.instance.m_debugTimeOfDay = true; EnvMan.instance.m_debugTime = (float)(((double)EnvMan.instance.m_debugTime + (double)mouseDelta.y * 0.004999999888241291) % 1.0); if ((double)EnvMan.instance.m_debugTime < 0.0) { EnvMan instance = EnvMan.instance; instance.m_debugTime += 1f; } cam.m_fov += mouseDelta.x * 1f; cam.m_fov = Mathf.Clamp(cam.m_fov, 0.5f, 165f); cam.m_camera.fieldOfView = cam.m_fov; cam.m_skyCamera.fieldOfView = cam.m_fov; if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && ((Character)Player.m_localPlayer).IsDebugFlying()) { if ((double)scroll > 0.0) { Character.m_debugFlySpeed = (int)Mathf.Clamp((float)Character.m_debugFlySpeed * 1.1f, (float)(Character.m_debugFlySpeed + 1), 300f); } else if ((double)scroll < 0.0 && Character.m_debugFlySpeed > 1) { Character.m_debugFlySpeed = (int)Mathf.Min((float)Character.m_debugFlySpeed * 0.9f, (float)(Character.m_debugFlySpeed - 1)); } } scroll = 0f; } return scroll; } private static Vector3 SmoothHeadPoint(Player localPlayer, float dt) { //IL_0008: 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_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: 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_004c: 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_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) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: 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_0081: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: 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_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0117: 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_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_0169: 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_0137: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0152: 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) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_015f: 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) Transform transform = ((Component)localPlayer).transform; Vector3 headPoint = ((Character)localPlayer).GetHeadPoint(); Vector3 val = transform.InverseTransformPoint(headPoint); Vector3 val2 = val; Vector3 val3; if (!((Object)(object)_headPlayer != (Object)(object)localPlayer)) { val3 = val - _smoothedHead; if (!(((Vector3)(ref val3)).sqrMagnitude > 4f)) { goto IL_0066; } } _headPlayer = localPlayer; _smoothedHead = val; _headAnchor = val; _headVelocity = Vector3.zero; _deadzone = 0f; goto IL_0066; IL_0066: Vector3 forward = ((Character)localPlayer).m_eye.forward; if (_deadzone <= 0f) { _anchorLook = forward; } val3 = ((Character)localPlayer).GetMoveDir(); _deadzone = ((((Vector3)(ref val3)).sqrMagnitude < 0.01f && !((Character)localPlayer).InAttack() && !((Character)localPlayer).InDodge() && Vector3.Angle(forward, _anchorLook) < 10f) ? Mathf.MoveTowards(_deadzone, FirstPersonModePlugin.IdleSwayDeadzone.Value, 0.05f * dt) : Mathf.MoveTowards(_deadzone, 0f, 0.2f * dt)); _headAnchor = val - Vector3.ClampMagnitude(val - _headAnchor, _deadzone); val = _headAnchor; float value = FirstPersonModePlugin.HeadBob.Value; if (value < 1f) { _smoothedHead = Vector3.SmoothDamp(_smoothedHead, val, ref _headVelocity, 0.12f, float.PositiveInfinity, dt); val = Vector3.Lerp(_smoothedHead, val, value); } return headPoint + transform.TransformVector(val - val2); } private static Vector3 Clamp(Vector3 offset) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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) return new Vector3(Mathf.Clamp(offset.x, -0.5f, 0.5f), Mathf.Clamp(offset.y, -0.5f, 0.5f), Mathf.Clamp(offset.z, -0.5f, 0.5f)); } internal static void SetCameraTransform(ref GameCamera __instance, Player localPlayer, float dt) { //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_004a: 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_0063: 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_00f1: 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_00fa: 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_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: 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_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) if (IsInFirstPersonMode()) { Vector3 val = SmoothHeadPoint(localPlayer, dt); Vector3 val2 = ((Component)((Character)localPlayer).m_eye).transform.rotation * Clamp(FirstPersonModePlugin.CameraOffset.Value); if (((Character)localPlayer).IsDrawingBow()) { val2 = ((Component)((Character)localPlayer).m_eye).transform.rotation * Clamp(FirstPersonModePlugin.OffsetWhenAiming.Value); } if (Object.op_Implicit((Object)(object)Utils.FindChild(((Component)localPlayer).transform, "Azu_transform", (IterativeSearchType)0))) { val = Utils.FindChild(Utils.FindChild(((Component)localPlayer).transform, "Azu_transform", (IterativeSearchType)0), "Head", (IterativeSearchType)0).position; val2 = ((Component)((Character)localPlayer).m_eye).transform.rotation * new Vector3(0f, 0.15f, 0.142f); __instance.m_nearClipPlaneMax = 0.47f; } __instance.m_nearClipPlaneMax = FirstPersonModePlugin.NearClipPlane.Value; Vector3 position = ((Component)__instance).transform.position; ((Component)__instance).transform.position = Vector3.Lerp(position, val + val2, 1f); } else { Vector3 position2 = default(Vector3); Quaternion rotation = default(Quaternion); __instance.GetCameraPosition(dt, ref position2, ref rotation); ((Component)__instance).transform.position = position2; ((Component)__instance).transform.rotation = rotation; } } } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ServerSync { [PublicAPI] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry<T> 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; } } } internal 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] internal sealed class CustomSyncedValue<T> : 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] internal 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<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)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<ZNetPeer> 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<string> CurrentList = new List<string>(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List<string>(adminList.GetList()); List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, 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<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>(); public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>(); } [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 = false; public volatile int versionMatchQueued = -1; public readonly List<ZPackage> Package = new List<ZPackage>(); 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 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<Assembly, BufferingSocket>(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary<Assembly, BufferingSocket> __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<PackageEntry> entries = new List<PackageEntry>(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; 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 = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet<ConfigSync> configSyncs; private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>(); private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>(); private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action<bool>? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet<ConfigSync>(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry<T>(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(0L, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry<T>(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry<T>)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<CustomSyncedValueBase>(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_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: 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<long, string> 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 SortedDictionary<int, byte[]> value)) { value = new SortedDictionary<int, byte[]>(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair<long, string>(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) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); 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<OwnConfigEntryBase, object> 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<CustomSyncedValueBase, object> 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<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary<string, CustomSyncedValueBase> 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; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute<ConfigurationManagerAttributes>(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<bool> 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 fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); 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<bool> 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<object>().GetEnumerator(); } List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != 0) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List<IEnumerator<bool>> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); } } private 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<OwnConfigEntryBase>().SingleOrDefault(); } public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config) { return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault(); } private static T configAttribute<T>(ConfigEntryBase config)
plugins/HBK-HBKHEIM/Foglands-1.0.3/Foglands.dll
Decompiled 5 hours agousing 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.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; 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; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Foglands")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Azumatt")] [assembly: AssemblyProduct("Foglands")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")] [assembly: AssemblyFileVersion("1.0.3")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.3.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; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class ExtensionMarkerAttribute : Attribute { public ExtensionMarkerAttribute(string name) { } } } namespace Foglands { public static class VeilController { public enum VeilState { Day, Dusk, Night, Dawn } private const float DawnPoint = 0.25f; private const float DuskPoint = 0.75f; private static float _lastLoggedFraction = -1f; private static string _lastWeather = ""; public static VeilState CurrentState { get; private set; } = VeilState.Day; public static float CurrentIntensity { get; private set; } public static float WeatherMultiplier { get; private set; } = 1f; public static void UpdateVeilState() { if (!FoglandsPlugin._enableEitrVeil.Value.IsOn() || (Object)(object)EnvMan.instance == (Object)null) { CurrentIntensity = 0f; CurrentState = VeilState.Day; return; } float dayFraction = EnvMan.instance.GetDayFraction(); float num = FoglandsPlugin._transitionDuration.Value / 24f; VeilState veilState; float num3; if (dayFraction >= 0.25f - num && dayFraction < 0.25f + num) { veilState = VeilState.Dawn; float num2 = (dayFraction - (0.25f - num)) / (num * 2f); num3 = 1f - Mathf.Clamp01(num2); } else if (dayFraction >= 0.75f - num && dayFraction < 0.75f + num) { veilState = VeilState.Dusk; num3 = Mathf.Clamp01((dayFraction - (0.75f - num)) / (num * 2f)); } else if (EnvMan.IsDay()) { veilState = VeilState.Day; num3 = 0f; } else { veilState = VeilState.Night; num3 = 1f; } if (Mathf.Abs(dayFraction - _lastLoggedFraction) >= 0.04f || _lastLoggedFraction < 0f) { FoglandsPlugin.FoglandsLogger.LogDebug((object)$"DayFraction: {dayFraction:F3} | Veil: {veilState} | Intensity: {num3:F2}"); _lastLoggedFraction = dayFraction; } CurrentState = veilState; CurrentIntensity = num3; UpdateWeatherMultiplier(); } private static void UpdateWeatherMultiplier() { if (!FoglandsPlugin._enableWeatherIntegration.Value.IsOn() || (Object)(object)EnvMan.instance == (Object)null) { WeatherMultiplier = 1f; return; } string text = EnvMan.instance.GetCurrentEnvironment()?.m_name ?? ""; if (!(text == _lastWeather)) { FoglandsPlugin.FoglandsLogger.LogDebug((object)("Weather changed: '" + _lastWeather + "' -> '" + text + "'")); _lastWeather = text; if (text.IndexOf("storm", StringComparison.OrdinalIgnoreCase) >= 0) { WeatherMultiplier = FoglandsPlugin._stormFogMultiplier.Value; } else if (text.IndexOf("rain", StringComparison.OrdinalIgnoreCase) >= 0) { WeatherMultiplier = FoglandsPlugin._rainFogMultiplier.Value; } else if (text.IndexOf("snow", StringComparison.OrdinalIgnoreCase) >= 0) { WeatherMultiplier = FoglandsPlugin._rainFogMultiplier.Value * 0.8f; } else { WeatherMultiplier = 1f; } } } public static float GetEmissionMultiplier() { float num = 0.4f * FoglandsPlugin._nightFogMultiplier.Value; return Mathf.Lerp(0.4f, num, CurrentIntensity) * WeatherMultiplier; } public static float GetCurrentAlpha() { float value = FoglandsPlugin._dayFogAlpha.Value; float value2 = FoglandsPlugin._nightFogAlpha.Value; return Mathf.Min(Mathf.Lerp(value, value2, CurrentIntensity) * Mathf.Lerp(1f, WeatherMultiplier * 0.7f, 0.5f), 0.7f); } public static float GetSizeMultiplier() { return Mathf.Lerp(1f, 1.3f, CurrentIntensity) * Mathf.Lerp(1f, 1.1f, (WeatherMultiplier - 1f) / 0.5f); } } public class MistControllerBehaviour : MonoBehaviour { private readonly float _scanInterval = 2f; private float _timeSinceLastScan; private readonly float _veilUpdateInterval = 0.5f; private float _timeSinceVeilUpdate; private Biome _lastBiome; private void Update() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Invalid comparison between Unknown and I4 //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Invalid comparison between Unknown and I4 //IL_0038: 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) Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } Biome currentBiome = localPlayer.GetCurrentBiome(); if (currentBiome != _lastBiome) { if ((int)_lastBiome == 512) { MistObjectController.Reset(); ParticleMistPatches.ResetModificationState(); } _lastBiome = currentBiome; } if ((int)currentBiome == 512) { _timeSinceVeilUpdate += Time.deltaTime; if (_timeSinceVeilUpdate >= _veilUpdateInterval) { _timeSinceVeilUpdate = 0f; VeilController.UpdateVeilState(); } _timeSinceLastScan += Time.deltaTime; if (_timeSinceLastScan >= _scanInterval) { _timeSinceLastScan = 0f; MistObjectController.ScanAndModifyMistObjects(); } } } } public static class MistObjectController { private static bool _hasScannedForMist; private static GameObject _localMistCloud; private static GameObject _globalMist; private static ParticleSystem _globalMistPS; private static Color _originalStartColor; private static float _originalStartSize; private static float _originalEmissionRate; private static bool _originalValuesStored; private static int _failedSearchAttempts; private const int MaxBackoffAttempts = 5; public static bool ScanAndModifyMistObjects() { if (_hasScannedForMist && (Object)(object)_globalMist != (Object)null) { return false; } if (_failedSearchAttempts > 0) { int num = Mathf.Min(_failedSearchAttempts, 5); if (_failedSearchAttempts % (num + 1) != 0) { _failedSearchAttempts++; return false; } } if (FindMistObjects()) { _failedSearchAttempts = 0; if ((Object)(object)_globalMist != (Object)null && (Object)(object)_globalMistPS != (Object)null) { ModifyGlobalMist(); } } else { _failedSearchAttempts++; } return true; } private static bool FindMistObjects() { //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Invalid comparison between Unknown and I4 if ((Object)(object)_localMistCloud == (Object)null) { GameObject val = GameObject.Find("_GameMain"); if ((Object)(object)val != (Object)null) { Transform val2 = val.transform.Find("_Environment/FollowPlayer/Mist/cloud (1)"); if ((Object)(object)val2 != (Object)null) { _localMistCloud = ((Component)val2).gameObject; } } } if ((Object)(object)_globalMist != (Object)null) { return (Object)(object)_globalMist != (Object)null; } ParticleMist[] array = Object.FindObjectsByType<ParticleMist>((FindObjectsSortMode)0); foreach (ParticleMist val3 in array) { if ((int)val3.m_biome == 512) { _globalMist = ((Component)val3).gameObject; _globalMistPS = val3.m_ps; _hasScannedForMist = true; return true; } } ParticleSystem[] array2 = Object.FindObjectsByType<ParticleSystem>((FindObjectsSortMode)0); foreach (ParticleSystem val4 in array2) { if (((Object)((Component)val4).gameObject).name.IndexOf("Globalmist", StringComparison.OrdinalIgnoreCase) >= 0) { _globalMist = ((Component)val4).gameObject; _globalMistPS = val4; _hasScannedForMist = true; return true; } } return (Object)(object)_globalMist != (Object)null; } private static void ModifyGlobalMist() { //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_0022: 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_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_globalMistPS == (Object)null)) { if (!_originalValuesStored) { MainModule main = _globalMistPS.main; MinMaxGradient startColor = ((MainModule)(ref main)).startColor; _originalStartColor = ((MinMaxGradient)(ref startColor)).color; MinMaxCurve val = ((MainModule)(ref main)).startSize; _originalStartSize = ((MinMaxCurve)(ref val)).constant; EmissionModule emission = _globalMistPS.emission; val = ((EmissionModule)(ref emission)).rateOverTime; _originalEmissionRate = ((MinMaxCurve)(ref val)).constant; _originalValuesStored = true; } if (FoglandsPlugin.IsParticleMistDisabled) { _globalMistPS.Clear(); } } } public static void Reset() { _hasScannedForMist = false; _localMistCloud = null; _globalMist = null; _globalMistPS = null; _failedSearchAttempts = 0; } } [HarmonyPatch] public static class ParticleMistPatches { private static bool _hasInitializedParticleSystem; private static int _originalLocalEmission; private static int _originalLocalEmissionPerUnit; private static float _originalEmissionMax; private static float _originalEmissionPerUnit; private static float _originalDistantEmissionMax; private static float _originalMinDistance; private static bool _originalValuesStored; [HarmonyPatch(typeof(ParticleMist), "Update")] [HarmonyPrefix] private static bool ParticleMist_Update_Prefix(ParticleMist __instance) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 if ((int)__instance.m_biome != 512) { return true; } if (FoglandsPlugin.IsParticleMistDisabled) { __instance.m_ps.Clear(); return false; } if (!_originalValuesStored) { _originalLocalEmission = __instance.m_localEmission; _originalLocalEmissionPerUnit = __instance.m_localEmissionPerUnit; _originalEmissionMax = __instance.m_emissionMax; _originalEmissionPerUnit = __instance.m_emissionPerUnit; _originalDistantEmissionMax = __instance.m_distantEmissionMax; _originalMinDistance = __instance.m_minDistance; _originalValuesStored = true; } if (!_hasInitializedParticleSystem && (Object)(object)__instance.m_ps != (Object)null) { InitializeParticleSystem(__instance.m_ps); _hasInitializedParticleSystem = true; } float emissionMultiplier = VeilController.GetEmissionMultiplier(); __instance.m_localEmission = (int)((float)_originalLocalEmission * emissionMultiplier); __instance.m_localEmissionPerUnit = (int)((float)_originalLocalEmissionPerUnit * emissionMultiplier); __instance.m_emissionMax = _originalEmissionMax * emissionMultiplier; __instance.m_emissionPerUnit = _originalEmissionPerUnit * emissionMultiplier; __instance.m_distantEmissionMax = _originalDistantEmissionMax * emissionMultiplier; float num = Mathf.Lerp(1.5f, 1f, VeilController.CurrentIntensity); __instance.m_minDistance = _originalMinDistance * num; if ((Object)(object)__instance.m_ps != (Object)null) { UpdateParticleSystemDynamic(__instance.m_ps); } return true; } private static void InitializeParticleSystem(ParticleSystem ps) { //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_001a: Unknown result type (might be due to invalid IL or missing references) MainModule main = ps.main; ((MainModule)(ref main)).maxParticles = 2000; ((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(4f); ((MainModule)(ref main)).simulationSpeed = 0.75f; } private static void UpdateParticleSystemDynamic(ParticleSystem ps) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_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_0059: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)ps == (Object)null)) { MainModule main = ps.main; float currentAlpha = VeilController.GetCurrentAlpha(); Color val = default(Color); ((Color)(ref val))..ctor(FoglandsPlugin._fogColorR.Value, FoglandsPlugin._fogColorG.Value, FoglandsPlugin._fogColorB.Value, currentAlpha); ((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(val); float sizeMultiplier = VeilController.GetSizeMultiplier(); ((MainModule)(ref main)).startSize = MinMaxCurve.op_Implicit(5f * sizeMultiplier); } } [HarmonyPatch(typeof(ParticleMist), "IsInMist")] [HarmonyPrefix] private static bool IsInMist_Prefix(ref bool __result, Vector3 p0) { if (!FoglandsPlugin.IsParticleMistDisabled && !(VeilController.CurrentIntensity < 0.3f)) { return true; } __result = false; return false; } [HarmonyPatch(typeof(ParticleMist), "IsMistBlocked")] [HarmonyPrefix] private static bool IsMistBlocked_Prefix(ref bool __result) { if (!FoglandsPlugin.IsParticleMistDisabled && !(VeilController.CurrentIntensity < 0.3f)) { return true; } __result = false; return false; } public static void ResetModificationState() { _hasInitializedParticleSystem = false; } } [BepInPlugin("Azumatt.Foglands", "Foglands", "1.0.3")] public class FoglandsPlugin : BaseUnityPlugin { public enum Toggle { On = 1, Off = 0 } private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [UsedImplicitly] public string? Category; [UsedImplicitly] public Action<ConfigEntryBase>? CustomDrawer; } internal const string ModName = "Foglands"; internal const string ModVersion = "1.0.3"; internal const string Author = "Azumatt"; private const string ModGUID = "Azumatt.Foglands"; private static string ConfigFileName = "Azumatt.Foglands.cfg"; private static string ConfigFileFullPath; internal static string ConnectionError; private readonly Harmony _harmony = new Harmony("Azumatt.Foglands"); public static readonly ManualLogSource FoglandsLogger; private static readonly ConfigSync ConfigSync; private FileSystemWatcher _watcher; private readonly object _reloadLock = new object(); private DateTime _lastConfigReloadTime; private const long RELOAD_DELAY = 10000000L; private static ConfigEntry<Toggle> _serverConfigLocked; internal static ConfigEntry<Toggle> _disableParticleMist; internal static ConfigEntry<float> _fogColorR; internal static ConfigEntry<float> _fogColorG; internal static ConfigEntry<float> _fogColorB; internal static ConfigEntry<Toggle> _enableEitrVeil; internal static ConfigEntry<float> _transitionDuration; internal static ConfigEntry<float> _nightFogMultiplier; internal static ConfigEntry<float> _nightFogAlpha; internal static ConfigEntry<float> _dayFogAlpha; internal static ConfigEntry<Toggle> _enableWeatherIntegration; internal static ConfigEntry<float> _stormFogMultiplier; internal static ConfigEntry<float> _rainFogMultiplier; internal static bool IsParticleMistDisabled { get { if (_disableParticleMist.Value.IsOn()) { return !IsMistBeGoneInstalled; } return false; } } private static bool IsMistBeGoneInstalled => Chainloader.PluginInfos.ContainsKey("Azumatt.MistBeGone"); public void Awake() { //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected O, but got Unknown //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Expected O, but got Unknown //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Expected O, but got Unknown //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Expected O, but got Unknown //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Expected O, but got Unknown //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Expected O, but got Unknown //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0206: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Expected O, but got Unknown //IL_0289: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Expected O, but got Unknown bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; _serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only."); ConfigSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked); _disableParticleMist = config("2 - Fog Settings", "Disable Particle Mist", Toggle.Off, "OFF = Replace mist with pleasant fog (gray, less dense, still atmospheric). ON = Remove ALL mist/fog particles completely. Doesn't work when MistBeGone is installed."); _fogColorR = config("2 - Fog Settings", "Fog Color Red", 0.45f, new ConfigDescription("Red component of fog particle color (0-1). Default gives a neutral gray.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); _fogColorG = config("2 - Fog Settings", "Fog Color Green", 0.45f, new ConfigDescription("Green component of fog particle color (0-1). Default gives a neutral gray.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); _fogColorB = config("2 - Fog Settings", "Fog Color Blue", 0.5f, new ConfigDescription("Blue component of fog particle color (0-1). Default has a slight blue tint.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); _enableEitrVeil = config("3 - Fog System", "Enable Time-Based Veil", Toggle.On, "Enables the Time Based Fog System where fog intensity changes based on time of day."); _transitionDuration = config("3 - Fog System", "Transition Duration Hours", 1.5f, new ConfigDescription("How long the fog takes to transition at dawn/dusk. Uses vanilla's day/night timing.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 4f), Array.Empty<object>())); _nightFogMultiplier = config("3 - Fog System", "Night Fog Multiplier", 2.5f, new ConfigDescription("How much thicker the fog is at night compared to day. 1.0 = same as day, 3.0 = three times thicker.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>())); _nightFogAlpha = config("3 - Fog System", "Night Fog Alpha", 0.5f, new ConfigDescription("Fog particle opacity at night. Higher = more opaque.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 0.8f), Array.Empty<object>())); _dayFogAlpha = config("3 - Fog System", "Day Fog Alpha", 0.25f, new ConfigDescription("Fog particle opacity during the day.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 0.5f), Array.Empty<object>())); _enableWeatherIntegration = config("4 - Weather", "Enable Weather Integration", Toggle.On, "When enabled, storms and rain in Mistlands will make the fog thicker."); _stormFogMultiplier = config("4 - Weather", "Storm Fog Multiplier", 1.5f, new ConfigDescription("How much thicker fog gets during thunderstorms. Applied on top of time-based intensity.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 3f), Array.Empty<object>())); _rainFogMultiplier = config("4 - Weather", "Rain Fog Multiplier", 1.25f, new ConfigDescription("How much thicker fog gets during rain. Applied on top of time-based intensity.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 2f), Array.Empty<object>())); Assembly executingAssembly = Assembly.GetExecutingAssembly(); _harmony.PatchAll(executingAssembly); SetupWatcher(); ((Component)this).gameObject.AddComponent<MistControllerBehaviour>(); ((BaseUnityPlugin)this).Config.Save(); if (saveOnConfigSet) { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; } } private void OnDestroy() { SaveWithRespectToConfigSet(); _watcher?.Dispose(); } private void SetupWatcher() { _watcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName); _watcher.Changed += ReadConfigValues; _watcher.Created += ReadConfigValues; _watcher.Renamed += ReadConfigValues; _watcher.IncludeSubdirectories = true; _watcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; _watcher.EnableRaisingEvents = true; } private void ReadConfigValues(object sender, FileSystemEventArgs e) { DateTime now = DateTime.Now; if (now.Ticks - _lastConfigReloadTime.Ticks < 10000000) { return; } lock (_reloadLock) { if (!File.Exists(ConfigFileFullPath)) { FoglandsLogger.LogWarning((object)"Config file does not exist. Skipping reload."); return; } try { FoglandsLogger.LogDebug((object)"Reloading configuration..."); SaveWithRespectToConfigSet(reload: true); FoglandsLogger.LogInfo((object)"Configuration reload complete."); } catch (Exception ex) { FoglandsLogger.LogError((object)("Error reloading configuration: " + ex.Message)); } } _lastConfigReloadTime = now; } private void SaveWithRespectToConfigSet(bool reload = false) { bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; if (reload) { ((BaseUnityPlugin)this).Config.Reload(); } ((BaseUnityPlugin)this).Config.Save(); if (saveOnConfigSet) { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; } } private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val); ConfigSync.AddConfigEntry<T>(val2).SynchronizedConfig = synchronizedSetting; return val2; } private ConfigEntry<T> config<T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting); } static FoglandsPlugin() { string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName; ConnectionError = ""; FoglandsLogger = Logger.CreateLogSource("Foglands"); ConfigSync = new ConfigSync("Azumatt.Foglands") { DisplayName = "Foglands", CurrentVersion = "1.0.3", MinimumRequiredVersion = "1.0.3" }; _serverConfigLocked = null; _disableParticleMist = null; _fogColorR = null; _fogColorG = null; _fogColorB = null; _enableEitrVeil = null; _transitionDuration = null; _nightFogMultiplier = null; _nightFogAlpha = null; _dayFogAlpha = null; _enableWeatherIntegration = null; _stormFogMultiplier = null; _rainFogMultiplier = null; } } public static class ToggleExtentions { [SpecialName] public sealed class <G>$E2280148A27CE3E7D9BF2BD92606AA6B { [SpecialName] public static class <M>$122DFD95079B0DF699D31D5CC531A3E0 { } [ExtensionMarker("<M>$122DFD95079B0DF699D31D5CC531A3E0")] public bool IsOn() { throw null; } [ExtensionMarker("<M>$122DFD95079B0DF699D31D5CC531A3E0")] public bool IsOff() { throw null; } } public static bool IsOn(this FoglandsPlugin.Toggle value) { return value == FoglandsPlugin.Toggle.On; } public static bool IsOff(this FoglandsPlugin.Toggle value) { return value == FoglandsPlugin.Toggle.Off; } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] public static class RegisterAndCheckVersion { private static void Prefix(ZNetPeer peer, ref ZNet __instance) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown FoglandsPlugin.FoglandsLogger.LogDebug((object)"Registering version RPC handler"); peer.m_rpc.Register<ZPackage>("Foglands_VersionCheck", (Action<ZRpc, ZPackage>)RpcHandlers.RPC_Foglands_Version); FoglandsPlugin.FoglandsLogger.LogInfo((object)"Invoking version check"); ZPackage val = new ZPackage(); val.Write("1.0.3"); peer.m_rpc.Invoke("Foglands_VersionCheck", new object[1] { val }); } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] public static class VerifyClient { private static bool Prefix(ZRpc rpc, ZPackage pkg, ref ZNet __instance) { if (!__instance.IsServer() || RpcHandlers.ValidatedPeers.Contains(rpc)) { return true; } FoglandsPlugin.FoglandsLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") never sent version or couldn't due to previous disconnect, disconnecting")); rpc.Invoke("Error", new object[1] { 3 }); return false; } private static void Postfix(ZNet __instance) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "FoglandsRequestAdminSync", new object[1] { (object)new ZPackage() }); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] public class ShowConnectionError { private static void Postfix(FejdStartup __instance) { if (__instance.m_connectionFailedPanel.activeSelf) { __instance.m_connectionFailedError.fontSizeMax = 25f; __instance.m_connectionFailedError.fontSizeMin = 15f; TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + FoglandsPlugin.ConnectionError; } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] public static class RemoveDisconnectedPeerFromVerified { private static void Prefix(ZNetPeer peer, ref ZNet __instance) { if (__instance.IsServer()) { FoglandsPlugin.FoglandsLogger.LogInfo((object)("Peer (" + peer.m_rpc.m_socket.GetHostName() + ") disconnected, removing from validated list")); RpcHandlers.ValidatedPeers.Remove(peer.m_rpc); } } } public static class RpcHandlers { public static readonly List<ZRpc> ValidatedPeers = new List<ZRpc>(); public static void RPC_Foglands_Version(ZRpc rpc, ZPackage pkg) { string text = pkg.ReadString(); FoglandsPlugin.FoglandsLogger.LogInfo((object)("Version check, local: 1.0.3, remote: " + text)); if (text != "1.0.3") { FoglandsPlugin.ConnectionError = "Foglands Installed: 1.0.3\n Needed: " + text; if (ZNet.instance.IsServer()) { FoglandsPlugin.FoglandsLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") has incompatible version, disconnecting...")); rpc.Invoke("Error", new object[1] { 3 }); } } else if (!ZNet.instance.IsServer()) { FoglandsPlugin.FoglandsLogger.LogInfo((object)"Received same version from server!"); } else { FoglandsPlugin.FoglandsLogger.LogInfo((object)("Adding peer (" + rpc.m_socket.GetHostName() + ") to validated list")); ValidatedPeers.Add(rpc); } } } } namespace ServerSync { [PublicAPI] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry<T> 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; } } } internal 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] internal sealed class CustomSyncedValue<T> : 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] internal 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<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)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<ZNetPeer> 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<string> CurrentList = new List<string>(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List<string>(adminList.GetList()); List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, 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<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>(); public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>(); } [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 = false; public volatile int versionMatchQueued = -1; public readonly List<ZPackage> Package = new List<ZPackage>(); 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 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<Assembly, BufferingSocket>(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary<Assembly, BufferingSocket> __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<PackageEntry> entries = new List<PackageEntry>(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; 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 = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet<ConfigSync> configSyncs; private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>(); private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>(); private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action<bool>? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet<ConfigSync>(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry<T>(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(0L, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry<T>(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry<T>)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<CustomSyncedValueBase>(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_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: 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<long, string> 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 SortedDictionary<int, byte[]> value)) { value = new SortedDictionary<int, byte[]>(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair<long, string>(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) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); 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<OwnConfigEntryBase, object> 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<CustomSyncedValueBase, object> 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<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary<string, CustomSyncedValueBase> 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; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute<ConfigurationManagerAttributes>(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<bool> 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 fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); 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<bool> 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<object>().GetEnumerator(); } List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != 0) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List<IEnumerator<bool>> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); } } private 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<OwnConfigEntryBase>().SingleOrDefault(); } public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config) { return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault(); } private static T configAttribute<T>(ConfigEntryBase config) { return config.Description.Tags.OfType<T>().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>(); List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>()) { 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<string>) && 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<object> source = new List<object>(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [PublicAPI] [HarmonyPatch] internal class VersionCheck { private static readonly HashSet<VersionCheck> versionChecks; private static readonly Dictionary<string, string> 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<ZRpc> ValidatedClients = new List<ZRpc>(); 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 { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: 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<VersionCheck>(); notProcessedNames = new Dictionary<string, string>(); 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 flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion); bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". 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) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } 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<ZRpc, ZPackage>? 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; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.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_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: 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<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)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_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: 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_01de: 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_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0229: 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<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> 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<RectTransform>(); 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<RectTransform>(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } }
plugins/HBK-HBKHEIM/Logo_Changer-1.1.1/LogoChanger.dll
Decompiled 5 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("LogoChanger")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Azumatt")] [assembly: AssemblyProduct("LogoChanger")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")] [assembly: AssemblyFileVersion("1.1.1")] [assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.1.0")] [module: UnverifiableCode] 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; } } } namespace LogoChanger { [BepInPlugin("Azumatt.LogoChanger", "LogoChanger", "1.1.1")] public class LogoChangerPlugin : BaseUnityPlugin { private enum Toggle { On = 1, Off = 0 } internal const string ModName = "LogoChanger"; internal const string ModVersion = "1.1.1"; internal const string Author = "Azumatt"; private const string ModGUID = "Azumatt.LogoChanger"; private static readonly string ConfigFileName = "Azumatt.LogoChanger.cfg"; private static readonly string ConfigFileFullPath; private readonly Harmony _harmony = new Harmony("Azumatt.LogoChanger"); private static readonly ManualLogSource LogoChangerLogger; internal static bool IsAshlandsLogoAdjusted; private static ConfigEntry<Toggle> _modEnabled; private static ConfigEntry<string> _mainMenuLogo; private static Sprite _mainLogoSprite; public void Awake() { _modEnabled = ((BaseUnityPlugin)this).Config.Bind<Toggle>("1 - General", "Mod Enabled?", Toggle.On, "Enable/Disable the mod"); _mainMenuLogo = ((BaseUnityPlugin)this).Config.Bind<string>("2 - Main Menu", "Main Menu Logo", "LogoChanger_LOGO.png", "The logo to use on the main menu to replace \"Valheim\" image, should be found somewhere in the plugins folder and sized at 1000x394"); _modEnabled.SettingChanged += ReloadImagesFromFolder; MoveImagesToConfigFolder(); ReloadImagesFromFolder(null, null); Assembly executingAssembly = Assembly.GetExecutingAssembly(); _harmony.PatchAll(executingAssembly); SetupWatcher(); } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); } private void SetupWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; FileSystemWatcher fileSystemWatcher2 = new FileSystemWatcher(Paths.ConfigPath, "LogoChanger*.png"); fileSystemWatcher2.Changed += ReloadImagesFromFolder; fileSystemWatcher2.Created += ReloadImagesFromFolder; fileSystemWatcher2.Renamed += ReloadImagesFromFolder; fileSystemWatcher2.IncludeSubdirectories = true; fileSystemWatcher2.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher2.EnableRaisingEvents = true; } private static void MoveImagesToConfigFolder() { string text = Path.Combine(Paths.ConfigPath, "Azumatt.LogoChanger_Images"); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } string[] files = Directory.GetFiles(Paths.PluginPath, "LogoChanger*.png", SearchOption.AllDirectories); string[] files2 = Directory.GetFiles(Paths.PluginPath, "DefaultLogos.zip", SearchOption.AllDirectories); if (files2.Length != 0) { string sourceFileName = files2[0]; string text2 = Path.Combine(text, "DefaultLogos.zip"); if (File.Exists(text2)) { File.Delete(text2); } File.Move(sourceFileName, text2); } string[] array = files; foreach (string obj in array) { string fileName = Path.GetFileName(obj); string destFileName = Path.Combine(text, fileName); File.Move(obj, destFileName); } } private void ReadConfigValues(object sender, FileSystemEventArgs e) { if (!File.Exists(ConfigFileFullPath)) { return; } try { LogoChangerLogger.LogDebug((object)"ReadConfigValues called"); ((BaseUnityPlugin)this).Config.Reload(); } catch { LogoChangerLogger.LogError((object)("There was an issue loading your " + ConfigFileName)); LogoChangerLogger.LogError((object)"Please check your config entries for spelling and format!"); } } internal static void ReloadImagesFromFolder(object sender, FileSystemEventArgs e) { if (CheckIfStartScene() && _modEnabled.Value == Toggle.On) { Load("(file system)"); FindMenuLogos(); } } private static void ReloadImagesFromFolder(object sender, EventArgs e) { if (CheckIfStartScene() && _modEnabled.Value == Toggle.On) { Load("(setting changed)"); FindMenuLogos(); } } private static void Load(string calledMethod) { LogoChangerLogger.LogDebug((object)("ReloadImagesFromFolder " + calledMethod + " called")); if ((Object)(object)Player.m_localPlayer != (Object)null) { ((Character)Player.m_localPlayer).Message((MessageType)2, "Reloading images...please wait...", 12, (Sprite)null, false); } if (_modEnabled.Value == Toggle.On) { _mainLogoSprite = LoadSprite(_mainMenuLogo.Value); } } private static Sprite LoadSprite(string name, bool isEmbed = false) { //IL_002c: 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) Texture2D val = LoadTexture(name, isEmbed); if (!((Object)(object)val != (Object)null)) { return null; } return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), Vector2.zero); } private static Texture2D LoadTexture(string name, bool isEmbed) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown Texture2D val = new Texture2D(0, 0); string directoryName = Path.GetDirectoryName(Paths.ConfigPath); if (directoryName == null) { return val; } List<string> list = Directory.GetFiles(directoryName, "LogoChanger*.png", SearchOption.AllDirectories).OrderBy(Path.GetFileName).ToList(); try { byte[] array = File.ReadAllBytes(list.Find((string x) => x.Contains(name))); ImageConversion.LoadImage(val, array); } catch (Exception arg) { LogoChangerLogger.LogWarning((object)("The file " + name + " couldn't be found in the directory path. Please make sure you are naming your files correctly and they are location somewhere in the BepInEx/plugins folder.\n" + $" Optionally, you can turn off 'Use Custom Backgrounds' inside of your configuration file. If you no longer wish to see this error.\n {arg}")); val = null; } return val; } internal static bool CheckIfStartScene() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) Scene activeScene = SceneManager.GetActiveScene(); return ((Scene)(ref activeScene)).name == "start"; } private static void FindMenuLogos() { if ((Object)(object)_mainLogoSprite == (Object)null) { return; } Transform obj = Utils.FindChild(FejdStartup.m_instance.m_mainMenu.transform, "Logo", (IterativeSearchType)0); Transform val = ((obj != null) ? ((Component)obj).transform : null); if (!((Object)(object)val == (Object)null)) { TryUpdateLogo(val, "Logo DeepNorth1 .0", _mainLogoSprite, "Couldn't find Logo DeepNorth1 .0 in hierarchy of the main menu or couldn't assign the Logo DeepNorth1 .0 sprite."); Transform parentTransform = Utils.FindChild(val, "Logo DeepNorth1 .0", (IterativeSearchType)0); string[] obj2 = new string[4] { "Embers", "Embers (1)", "Embers (2)", "Embers (3)" }; TryDisableAllChildren(parentTransform); string[] array = obj2; foreach (string text in array) { TryDisableChild(val, text, "Couldn't find " + text + " in hierarchy of the main menu or couldn't disable " + text + " gameobject."); } } } private static void TryUpdateLogo(Transform parentTransform, string childName, Sprite logoSprite, string errorMessage) { try { ((Component)Utils.FindChild(parentTransform, childName, (IterativeSearchType)0)).GetComponent<Image>().sprite = logoSprite; } catch (Exception arg) { LogoChangerLogger.LogError((object)$"{errorMessage} {arg}"); throw; } } private static void TryDisableChild(Transform parentTransform, string childName, string errorMessage) { try { ((Component)Utils.FindChild(parentTransform, childName, (IterativeSearchType)0)).gameObject.SetActive(false); } catch (Exception arg) { LogoChangerLogger.LogError((object)$"{errorMessage} {arg}"); throw; } } private static void TryDisableAllChildren(Transform parentTransform) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown try { Component[] componentsInChildren = ((Component)parentTransform).GetComponentsInChildren(typeof(Transform), true); for (int i = 0; i < componentsInChildren.Length; i++) { Transform val = (Transform)componentsInChildren[i]; if (!((Object)(object)val == (Object)(object)parentTransform)) { ((Component)val).gameObject.SetActive(false); } } } catch (Exception arg) { LogoChangerLogger.LogError((object)$"$\"Couldn't find disable the children in hierarchy of {((Object)((Component)parentTransform).transform).name}{arg}"); throw; } } static LogoChangerPlugin() { string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName; LogoChangerLogger = Logger.CreateLogSource("LogoChanger"); IsAshlandsLogoAdjusted = false; _modEnabled = null; _mainMenuLogo = null; _mainLogoSprite = null; } } [HarmonyPatch(typeof(Player), "Awake")] internal static class PlayerAwakePatch { private static void Prefix(Player __instance) { if (!LogoChangerPlugin.CheckIfStartScene()) { LogoChangerPlugin.IsAshlandsLogoAdjusted = false; } else { LogoChangerPlugin.ReloadImagesFromFolder(null, null); } } } }
plugins/HBK-HBKHEIM/Mining-1.1.7/Mining.dll
Decompiled 5 hours agousing 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.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using SkillManager; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("Mining")] [assembly: AssemblyDescription("https://valheim.hexium.gg/mods/Smoothbrain/Mining")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Mining")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("7210421B-E30E-4DA5-9140-7751B6A324B7")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.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 Mining { [BepInPlugin("org.bepinex.plugins.mining", "Mining", "1.1.7")] [BepInIncompatibility("org.bepinex.plugins.valheim_plus")] public class Mining : BaseUnityPlugin { private enum Toggle { On = 1, Off = 0 } private class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ShowRangeAsPercent; } [HarmonyPatch(typeof(Player), "Awake")] public class PlayerAwake { private static void Postfix(Player __instance) { ((Character)__instance).m_nview.Register<int>("Mining IncreaseSkill", (Action<long, int>)delegate(long _, int factor) { ((Character)(object)__instance).RaiseSkill("Mining", factor); }); } } [HarmonyPatch(typeof(Player), "Update")] public class PlayerUpdate { private static void Postfix(Player __instance) { if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer) { ((Character)__instance).m_nview.GetZDO().Set("Mining Skill Factor", ((Character)(object)__instance).GetSkillFactor("Mining")); } } } [HarmonyPatch(typeof(SEMan), "ModifyAttack")] private class IncreaseDamageDone { private static void Prefix(SEMan __instance, ref HitData hitData) { Character character = __instance.m_character; Player val = (Player)(object)((character is Player) ? character : null); if (val != null) { hitData.m_damage.m_pickaxe *= 1f + ((Character)(object)val).GetSkillFactor("Mining") * (miningDamageFactor.Value - 1f); } } } [HarmonyPatch(typeof(DropTable), "GetDropList", new Type[] { typeof(int) })] private class IncreaseItemYield { [UsedImplicitly] [HarmonyPriority(100)] private static void Postfix(ref List<GameObject> __result) { if (!SetMiningFlag.IsMining) { return; } List<GameObject> list = new List<GameObject>(); foreach (GameObject item in __result) { float num = 1f + SetMiningFlag.MiningFactor * (miningItemYieldFactor.Value - 1f); for (int num2 = Mathf.FloorToInt(num + Random.Range(0f, 1f)); num2 > 0; num2--) { list.Add(item); } } __result = list; } } [HarmonyPatch(typeof(MineRock5), "RPC_Damage")] public static class SetMiningFlag { public static bool IsMining; public static float MiningFactor; private static bool Prefix(MineRock5 __instance, HitData hit) { return HandleMining(hit, delegate { //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) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: 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_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected O, but got Unknown for (int i = 0; i < __instance.m_hitAreas.Count; i++) { HitArea val = __instance.m_hitAreas[i]; if (val.m_health > 0f) { MineRock5 obj = __instance; int num = i; HitData val2 = new HitData { m_damage = { m_damage = __instance.m_health } }; Bounds bounds = val.m_collider.bounds; val2.m_point = ((Bounds)(ref bounds)).center; val2.m_toolTier = 100; val2.m_attacker = hit.m_attacker; obj.DamageArea(num, val2); } } }, __instance.m_minToolTier, __instance.m_nview); } public static bool HandleMining(HitData hit, Action explode, int minToolTier, ZNetView netView) { Character attacker = hit.GetAttacker(); Player val = (Player)(object)((attacker is Player) ? attacker : null); if (val == null) { return true; } IsMining = true; ZDO zDO = ((Character)val).m_nview.GetZDO(); MiningFactor = ((zDO != null) ? zDO.GetFloat("Mining Skill Factor", 0f) : 0f); if (hit.m_toolTier >= minToolTier && hit.m_damage.m_pickaxe > 0f && netView.IsValid() && netView.IsOwner()) { ((Character)val).m_nview.InvokeRPC("Mining IncreaseSkill", new object[1] { 1 }); if (explosiveMining && explosionMinimumLevel.Value > 0 && MiningFactor >= (float)explosionMinimumLevel.Value / 100f && Random.Range(0f, 1f) <= (MiningFactor - (float)(explosionMinimumLevel.Value - 10) / 100f) / (1f - (float)(explosionMinimumLevel.Value - 10) / 100f) * explosionChance.Value / 100f) { explode(); return false; } } return true; } private static void Finalizer() { IsMining = false; } } [HarmonyPatch(typeof(MineRock), "RPC_Hit")] public static class SetMiningFlagRock { private static bool Prefix(MineRock __instance, HitData hit) { return SetMiningFlag.IsMining || SetMiningFlag.HandleMining(hit, delegate { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006e: 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_0075: 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_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_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown for (int i = 0; i < __instance.m_hitAreas.Length; i++) { Collider val = __instance.m_hitAreas[i]; float num = __instance.m_nview.GetZDO().GetFloat($"Health{i}", __instance.m_health); if (num > 0f) { MineRock obj = __instance; long num2 = 0L; HitData val2 = new HitData { m_damage = { m_damage = num } }; Bounds bounds = val.bounds; val2.m_point = ((Bounds)(ref bounds)).center; val2.m_toolTier = 100; val2.m_attacker = hit.m_attacker; obj.RPC_Hit(num2, val2, i); } } __instance.m_hitAreas = Array.Empty<Collider>(); }, __instance.m_minToolTier, __instance.m_nview); } private static void Finalizer() { SetMiningFlag.IsMining = false; } } [HarmonyPatch(typeof(Destructible), "RPC_Damage")] public static class SetMiningFlagDestructible { private static bool Prefix(Destructible __instance, HitData hit) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Invalid comparison between Unknown and I4 //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Invalid comparison between Unknown and I4 //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Invalid comparison between Unknown and I4 if (!SetMiningFlag.IsMining && (int)__instance.m_damages.m_pickaxe != 3 && (int)__instance.m_damages.m_chop == 3 && (int)__instance.m_destructibleType != 2) { return SetMiningFlag.HandleMining(hit, delegate { //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_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown __instance.Damage(new HitData { m_damage = { m_damage = __instance.m_health }, m_point = hit.m_point, m_toolTier = 100, m_attacker = hit.m_attacker }); }, __instance.m_minToolTier, __instance.m_nview); } return true; } private static void Finalizer() { SetMiningFlag.IsMining = false; } } private const string ModName = "Mining"; private const string ModVersion = "1.1.7"; private const string ModGUID = "org.bepinex.plugins.mining"; private static readonly ConfigSync configSync = new ConfigSync("org.bepinex.plugins.mining") { DisplayName = "Mining", CurrentVersion = "1.1.7", MinimumRequiredVersion = "1.1.7" }; private static ConfigEntry<Toggle> serverConfigLocked = null; private static ConfigEntry<float> miningDamageFactor = null; private static ConfigEntry<float> miningItemYieldFactor = null; private static ConfigEntry<KeyboardShortcut> explosionToggleHotkey = null; private static ConfigEntry<int> explosionMinimumLevel = null; private static ConfigEntry<float> explosionChance = null; private static ConfigEntry<float> experienceGainedFactor = null; private static ConfigEntry<int> experienceLoss = null; private static bool explosiveMining = true; private static Skill mining = null; private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description); SyncedConfigEntry<T> syncedConfigEntry = configSync.AddConfigEntry<T>(val); syncedConfigEntry.SynchronizedConfig = synchronizedSetting; return val; } private ConfigEntry<T> config<T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting); } public void Awake() { //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Expected O, but got Unknown //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Expected O, but got Unknown //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Expected O, but got Unknown //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Expected O, but got Unknown //IL_0195: 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_01b0: Expected O, but got Unknown //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Expected O, but got Unknown //IL_024b: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Expected O, but got Unknown //IL_02a5: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Expected O, but got Unknown mining = new Skill("Mining", "mining.png"); mining.Description.English("Increases damage done while mining and item yield from ore deposits."); mining.Name.German("Bergbau"); mining.Description.German("Erhöht den Schaden während Bergbau-Aktivitäten und erhöht die Ausbeute von Erzvorkommen."); mining.Configurable = false; serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only."); configSync.AddLockingConfigEntry<Toggle>(serverConfigLocked); miningDamageFactor = config("2 - Mining", "Mining Damage Factor", 3f, new ConfigDescription("Mining damage factor at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>())); miningItemYieldFactor = config("2 - Mining", "Mining Yield Factor", 2f, new ConfigDescription("Mining yield factor at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>())); explosionMinimumLevel = config("2 - Mining", "Mining Explosion Level Requirement", 50, new ConfigDescription("Minimum required skill level to have a chance for the deposit to explode. 0 is disabled.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1] { new ConfigurationManagerAttributes { ShowRangeAsPercent = false } })); explosionChance = config("2 - Mining", "Mining Explosion Chance", 1f, new ConfigDescription("Mining explosion chance at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>())); explosionToggleHotkey = config<KeyboardShortcut>("2 - Mining", "Toggle Explosive Mining Hotkey", new KeyboardShortcut((KeyCode)116, (KeyCode[])(object)new KeyCode[1] { (KeyCode)306 }), new ConfigDescription("Shortcut to press to toggle explosion chance off and on. Please note that you have to stand still, to toggle this.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); experienceGainedFactor = config("3 - Other", "Skill Experience Gain Factor", 1f, new ConfigDescription("Factor for experience gained for the mining skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), Array.Empty<object>())); experienceGainedFactor.SettingChanged += delegate { mining.SkillGainFactor = experienceGainedFactor.Value; }; mining.SkillGainFactor = experienceGainedFactor.Value; experienceLoss = config("3 - Other", "Skill Experience Loss", 0, new ConfigDescription("How much experience to lose in the mining skill on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); experienceLoss.SettingChanged += delegate { mining.SkillLoss = experienceLoss.Value; }; mining.SkillLoss = experienceLoss.Value; Assembly executingAssembly = Assembly.GetExecutingAssembly(); Harmony val = new Harmony("org.bepinex.plugins.mining"); val.PatchAll(executingAssembly); } private void Update() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) KeyboardShortcut value = explosionToggleHotkey.Value; if (((KeyboardShortcut)(ref value)).IsDown()) { explosiveMining = !explosiveMining; Debug.Log((object)$"ExplosiveMining: {explosiveMining}"); Player localPlayer = Player.m_localPlayer; if (localPlayer != null) { ((Character)localPlayer).Message((MessageType)1, $"Explosive Mining: {explosiveMining}", 0, (Sprite)null, false); } } } } } namespace SkillManager { [PublicAPI] internal class Skill { public static class LocalizationCache { private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>(); internal static void LocalizationPostfix(Localization __instance, string language) { string key = localizations.FirstOrDefault<KeyValuePair<string, Localization>>((KeyValuePair<string, Localization> l) => l.Value == __instance).Key; if (key != null) { localizations.Remove(key); } if (!localizations.ContainsKey(language)) { localizations.Add(language, __instance); } } public static Localization ForLanguage(string? language = null) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out Localization value)) { return value; } value = new Localization(); if (language != null) { value.SetupLanguage(language); } return value; } } [PublicAPI] public class LocalizeKey { private static readonly List<LocalizeKey> keys = new List<LocalizeKey>(); public readonly string Key; public readonly Dictionary<string, string> Localizations = new Dictionary<string, string>(); public LocalizeKey(string key) { Key = key.Replace("$", ""); keys.Add(this); } public void Alias(string alias) { Localizations.Clear(); if (!alias.Contains("$")) { alias = "$" + alias; } Localizations["alias"] = alias; Localization.instance.AddWord(Key, Localization.instance.Localize(alias)); } public LocalizeKey English(string key) { return addForLang("English", key); } public LocalizeKey Swedish(string key) { return addForLang("Swedish", key); } public LocalizeKey French(string key) { return addForLang("French", key); } public LocalizeKey Italian(string key) { return addForLang("Italian", key); } public LocalizeKey German(string key) { return addForLang("German", key); } public LocalizeKey Spanish(string key) { return addForLang("Spanish", key); } public LocalizeKey Russian(string key) { return addForLang("Russian", key); } public LocalizeKey Romanian(string key) { return addForLang("Romanian", key); } public LocalizeKey Bulgarian(string key) { return addForLang("Bulgarian", key); } public LocalizeKey Macedonian(string key) { return addForLang("Macedonian", key); } public LocalizeKey Finnish(string key) { return addForLang("Finnish", key); } public LocalizeKey Danish(string key) { return addForLang("Danish", key); } public LocalizeKey Norwegian(string key) { return addForLang("Norwegian", key); } public LocalizeKey Icelandic(string key) { return addForLang("Icelandic", key); } public LocalizeKey Turkish(string key) { return addForLang("Turkish", key); } public LocalizeKey Lithuanian(string key) { return addForLang("Lithuanian", key); } public LocalizeKey Czech(string key) { return addForLang("Czech", key); } public LocalizeKey Hungarian(string key) { return addForLang("Hungarian", key); } public LocalizeKey Slovak(string key) { return addForLang("Slovak", key); } public LocalizeKey Polish(string key) { return addForLang("Polish", key); } public LocalizeKey Dutch(string key) { return addForLang("Dutch", key); } public LocalizeKey Portuguese_European(string key) { return addForLang("Portuguese_European", key); } public LocalizeKey Portuguese_Brazilian(string key) { return addForLang("Portuguese_Brazilian", key); } public LocalizeKey Chinese(string key) { return addForLang("Chinese", key); } public LocalizeKey Japanese(string key) { return addForLang("Japanese", key); } public LocalizeKey Korean(string key) { return addForLang("Korean", key); } public LocalizeKey Hindi(string key) { return addForLang("Hindi", key); } public LocalizeKey Thai(string key) { return addForLang("Thai", key); } public LocalizeKey Abenaki(string key) { return addForLang("Abenaki", key); } public LocalizeKey Croatian(string key) { return addForLang("Croatian", key); } public LocalizeKey Georgian(string key) { return addForLang("Georgian", key); } public LocalizeKey Greek(string key) { return addForLang("Greek", key); } public LocalizeKey Serbian(string key) { return addForLang("Serbian", key); } public LocalizeKey Ukrainian(string key) { return addForLang("Ukrainian", key); } private LocalizeKey addForLang(string lang, string value) { Localizations[lang] = value; if (Localization.instance.GetSelectedLanguage() == lang) { Localization.instance.AddWord(Key, value); } else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key)) { Localization.instance.AddWord(Key, value); } return this; } [HarmonyPriority(300)] internal static void AddLocalizedKeys(Localization __instance, string language) { foreach (LocalizeKey key in keys) { string value2; if (key.Localizations.TryGetValue(language, out string value) || key.Localizations.TryGetValue("English", out value)) { __instance.AddWord(key.Key, value); } else if (key.Localizations.TryGetValue("alias", out value2)) { __instance.AddWord(key.Key, Localization.instance.Localize(value2)); } } } } private class ConfigurationManagerAttributes { [UsedImplicitly] public string? Category; } [HarmonyPatch(typeof(Skills), "IsSkillValid")] private static class Patch_Skills_IsSkillValid { private static void Postfix(SkillType type, ref bool __result) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (!__result && skills.ContainsKey(type)) { __result = true; } } } private static readonly Dictionary<SkillType, Skill> skills; internal static readonly Dictionary<string, Skill> skillByName; private readonly string skillName; private readonly string internalSkillName; private readonly SkillDef skillDef; public readonly LocalizeKey Name; public readonly LocalizeKey Description; private float skillEffectFactor = 1f; private int skillLoss = 5; public bool Configurable = false; private static bool InitializedTerminal; private static Localization? _english; private static BaseUnityPlugin? _plugin; private static bool hasConfigSync; private static object? _configSync; public float SkillGainFactor { get { return skillDef.m_increseStep; } set { skillDef.m_increseStep = value; this.SkillGainFactorChanged?.Invoke(value); } } public float SkillEffectFactor { get { return skillEffectFactor; } set { skillEffectFactor = value; this.SkillEffectFactorChanged?.Invoke(value); } } public int SkillLoss { get { return skillLoss; } set { skillLoss = value; this.SkillLossChanged?.Invoke(value); } } private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English")); private static BaseUnityPlugin plugin { get { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown object obj = _plugin; if (obj == null) { BaseUnityPlugin val = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)Assembly.GetExecutingAssembly().DefinedTypes.First((TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); _plugin = val; obj = (object)val; } return (BaseUnityPlugin)obj; } } private static object? configSync { get { if (_configSync == null && hasConfigSync) { Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync"); if ((object)type != null) { _configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " SkillManager"); type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString()); type.GetProperty("IsLocked").SetValue(_configSync, true); } else { hasConfigSync = false; } } return _configSync; } } public event Action<float>? SkillGainFactorChanged; public event Action<float>? SkillEffectFactorChanged; public event Action<float>? SkillLossChanged; public Skill(string englishName, string icon) : this(englishName, loadSprite(icon, 64, 64)) { } public unsafe Skill(string englishName, Sprite icon) { //IL_0022: 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_0043: 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_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0082: 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_008d: Expected O, but got Unknown SkillType val = fromName(englishName); string text = new Regex("[^a-zA-Z]").Replace(englishName, "_"); skills[val] = this; skillByName[englishName] = this; skillDef = new SkillDef { m_description = "$skilldesc_" + text, m_icon = icon, m_increseStep = 1f, m_skill = val }; internalSkillName = text; skillName = englishName; Name = new LocalizeKey("skill_" + ((object)(*(SkillType*)(&val))/*cast due to .constrained prefix*/).ToString()).English(englishName); Description = new LocalizeKey("skilldesc_" + text); } public static SkillType fromName(string englishName) { return (SkillType)Math.Abs(StringExtensionMethods.GetStableHashCode(englishName)); } static Skill() { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Expected O, but got Unknown //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Expected O, but got Unknown //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Expected O, but got Unknown //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Expected O, but got Unknown //IL_0185: 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_01ad: Expected O, but got Unknown //IL_01ad: Expected O, but got Unknown //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Expected O, but got Unknown //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Expected O, but got Unknown //IL_023f: Expected O, but got Unknown skills = new Dictionary<SkillType, Skill>(); skillByName = new Dictionary<string, Skill>(); InitializedTerminal = false; hasConfigSync = true; Harmony val = new Harmony("org.bepinex.helpers.skillmanager"); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "GetSkillDef", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_GetSkillDef", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatRaiseSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatRaiseskill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatResetSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatResetSkill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "OnDeath", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Finalizer", (Type[])null, (Type[])null)), (HarmonyMethod)null); } private static void Patch_FejdStartup() { //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Expected O, but got Unknown //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Expected O, but got Unknown //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Expected O, but got Unknown foreach (Skill skill in skills.Values) { if (skill.Configurable) { string key = skill.Name.Key; string text = new Regex("['[\"\\]]").Replace(english.Localize(key), "").Trim(); string category = Localization.instance.Localize(key).Trim(); ConfigEntry<float> skillGain = config(text, "Skill gain factor", skill.SkillGainFactor, new ConfigDescription("The rate at which you gain experience for the skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1] { new ConfigurationManagerAttributes { Category = category } })); skill.SkillGainFactor = skillGain.Value; skillGain.SettingChanged += delegate { skill.SkillGainFactor = skillGain.Value; }; ConfigEntry<float> skillEffect = config(text, "Skill effect factor", skill.SkillEffectFactor, new ConfigDescription("The power of the skill, based on the default power.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1] { new ConfigurationManagerAttributes { Category = category } })); skill.SkillEffectFactor = skillEffect.Value; skillEffect.SettingChanged += delegate { skill.SkillEffectFactor = skillEffect.Value; }; ConfigEntry<int> skillLoss = config(text, "Skill loss", skill.skillLoss, new ConfigDescription("How much experience to lose on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1] { new ConfigurationManagerAttributes { Category = category } })); skill.skillLoss = skillLoss.Value; skillLoss.SettingChanged += delegate { skill.skillLoss = skillLoss.Value; }; } } } private static void Patch_Skills_GetSkillDef(ref SkillDef? __result, List<SkillDef> ___m_skills, SkillType type) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) if (__result == null) { SkillDef val = GetSkillDef(type); if (val != null) { ___m_skills.Add(val); __result = val; } } } private unsafe static bool Patch_Skills_CheatRaiseskill(Skills __instance, string name, float value, Player ___m_player) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) foreach (SkillType key in skills.Keys) { Skill skill = skills[key]; if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase)) { Skill skill2 = __instance.GetSkill(key); skill2.m_level += value; skill2.m_level = Mathf.Clamp(skill2.m_level, 0f, 100f); ((Character)___m_player).Message((MessageType)1, "Skill increased " + Localization.instance.Localize("$skill_" + ((object)(*(SkillType*)(&key))/*cast due to .constrained prefix*/).ToString()) + ": " + (int)skill2.m_level, 0, skill2.m_info.m_icon, false); Console.instance.Print("Skill " + skill.internalSkillName + " = " + skill2.m_level); return false; } } return true; } private static bool Patch_Skills_CheatResetSkill(Skills __instance, string name) { //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_0022: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) foreach (SkillType key in skills.Keys) { Skill skill = skills[key]; if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase)) { __instance.ResetSkill(key); Console.instance.Print("Skill " + skill.internalSkillName + " reset"); return false; } } return true; } private static void Patch_Skills_OnDeath_Prefix(Skills __instance, ref Dictionary<SkillType, Skill>? __state) { //IL_002e: 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_00a0: Unknown result type (might be due to invalid IL or missing references) if (__state == null) { __state = new Dictionary<SkillType, Skill>(); } foreach (KeyValuePair<SkillType, Skill> skill in skills) { if (__instance.m_skillData.TryGetValue(skill.Key, out var value)) { __state[skill.Key] = value; if (skill.Value.skillLoss > 0) { Skill obj = value; obj.m_level -= value.m_level * (float)skill.Value.SkillLoss / 100f; value.m_accumulator = 0f; } __instance.m_skillData.Remove(skill.Key); } } } private static void Patch_Skills_OnDeath_Finalizer(Skills __instance, ref Dictionary<SkillType, Skill>? __state) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) if (__state == null) { return; } foreach (KeyValuePair<SkillType, Skill> item in __state) { __instance.m_skillData[item.Key] = item.Value; } __state = null; } private static void Patch_Terminal_InitTerminal_Prefix() { InitializedTerminal = Terminal.m_terminalInitialized; } private static void Patch_Terminal_InitTerminal() { if (!InitializedTerminal) { AddSkill(Terminal.commands["raiseskill"]); AddSkill(Terminal.commands["resetskill"]); } static void AddSkill(ConsoleCommand command) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown ConsoleOptionsFetcher fetcher = command.m_tabOptionsFetcher; command.m_tabOptionsFetcher = (ConsoleOptionsFetcher)delegate { List<string> list = fetcher.Invoke(); list.AddRange(skills.Values.Select((Skill skill) => skill.internalSkillName)); return list; }; } } private static SkillDef? GetSkillDef(SkillType skillType) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (!skills.ContainsKey(skillType)) { return null; } Skill skill = skills[skillType]; return skill.skillDef; } private static byte[] ReadEmbeddedFileBytes(string name) { using MemoryStream memoryStream = new MemoryStream(); Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + name).CopyTo(memoryStream); return memoryStream.ToArray(); } private static Texture2D loadTexture(string name) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Expected O, but got Unknown Texture2D val = new Texture2D(0, 0); ImageConversion.LoadImage(val, ReadEmbeddedFileBytes("icons." + name)); return val; } private static Sprite loadSprite(string name, int width, int height) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) return Sprite.Create(loadTexture(name), new Rect(0f, 0f, (float)width, (float)height), Vector2.zero); } private static ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description) { ConfigEntry<T> val = plugin.Config.Bind<T>(group, name, value, description); configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T)) .Invoke(configSync, new object[1] { val }); return val; } private static ConfigEntry<T> config<T>(string group, string name, T value, string description) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())); } } [PublicAPI] internal static class SkillExtensions { public static float GetSkillFactor(this Character character, string name) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return character.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor; } public static float GetSkillFactor(this Skills skills, string name) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return skills.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor; } public static void RaiseSkill(this Character character, string name, float value = 1f) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) character.RaiseSkill(Skill.fromName(name), value); } public static void RaiseSkill(this Skills skill, string name, float value = 1f) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) skill.RaiseSkill(Skill.fromName(name), value); } public static void LowerSkill(this Character character, string name, float factor = 1f) { character.GetSkills().LowerSkill(name, factor); } public static void LowerSkill(this Skills skills, string name, float factor) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (factor > 0f && skills.m_skillData.TryGetValue(Skill.fromName(name), out var value)) { Skill obj = value; obj.m_level -= value.m_level * factor; value.m_accumulator = 0f; } } } } namespace ServerSync { [PublicAPI] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry<T> 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; } } } internal 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] internal sealed class CustomSyncedValue<T> : 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] internal 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<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)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<ZNetPeer> 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<string> CurrentList = new List<string>(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List<string>(adminList.GetList()); List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, 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<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>(); public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>(); } [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 = false; public volatile int versionMatchQueued = -1; public readonly List<ZPackage> Package = new List<ZPackage>(); 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 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<Assembly, BufferingSocket>(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary<Assembly, BufferingSocket> __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<PackageEntry> entries = new List<PackageEntry>(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; 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 = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet<ConfigSync> configSyncs; private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>(); private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>(); private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action<bool>? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet<ConfigSync>(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry<T>(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(0L, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry<T>(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry<T>)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<CustomSyncedValueBase>(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_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: 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<long, string> 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 SortedDictionary<int, byte[]> value)) { value = new SortedDictionary<int, byte[]>(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair<long, string>(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) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); 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<OwnConfigEntryBase, object> 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<CustomSyncedValueBase, object> 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<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary<string, CustomSyncedValueBase> 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; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute<ConfigurationManagerAttributes>(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<bool> 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 fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); 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<bool> 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<object>().GetEnumerator(); } List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != 0) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List<IEnumerator<bool>> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); } } private 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<OwnConfigEntryBase>().SingleOrDefault(); } public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config) { return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault(); } private static T configAttribute<T>(ConfigEntryBase config) { return config.Description.Tags.OfType<T>().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>(); List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>()) { 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<string>) && 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<object> source = new List<object>(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [PublicAPI] [HarmonyPatch] internal class VersionCheck { private static readonly HashSet<VersionCheck> versionChecks; private static readonly Dictionary<string, string> 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<ZRpc> ValidatedClients = new List<ZRpc>(); 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 { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: 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<VersionCheck>(); notProcessedNames = new Dictionary<string, string>(); 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 flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion); bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". 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) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } 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<ZRpc, ZPackage>? 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; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.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_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: 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<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)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_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: 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_01de: 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_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0229: 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<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> 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<RectTransform>(); 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<RectTransform>(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } }
plugins/HBK-HBKHEIM/PortalPreload-1.2.1/PortalPreload.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using Splatform; using TMPro; using UIManager; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using UnityEngine.U2D; using UnityEngine.UI; using Valheim.SettingsGui; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.ObjectPool; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.BufferedDeserialization; using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators; using YamlDotNet.Serialization.Callbacks; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("PortalPreload")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Azumatt")] [assembly: AssemblyProduct("PortalPreload")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")] [assembly: AssemblyFileVersion("1.2.1")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.2.1.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; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class ExtensionMarkerAttribute : Attribute { public ExtensionMarkerAttribute(string name) { } } } namespace PortalPreload { internal static class DestinationEnvironment { private static readonly Dictionary<Vector2s, (long Period, EnvSetup? Env)> _cache = new Dictionary<Vector2s, (long, EnvSetup)>(); private static Quaternion _lightRot; private static float _lightIntensity; private static Color _lightColor; private static Color _fogColor; private static float _fogDensity; private static AmbientMode _ambientMode; private static Color _ambientLight; private static Vector4 _skyboxSunDir; private static Vector4 _sunDir; private static Color _sunFogColor; private static Color _sunColor; private static Color _ambientColor; private static float _wet; private static float _aurora; private static float _cloudRain; private static float _cloudOpacity; internal static EnvSetup? For(Vector3 pos) { //IL_0038: 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) //IL_003e: 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_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) EnvMan instance = EnvMan.instance; if ((Object)(object)instance == (Object)null || WorldGenerator.instance == null || (Object)(object)ZNet.instance == (Object)null) { return null; } long num = (long)ZNet.instance.GetTimeSeconds() / instance.m_environmentDuration; Vector2s zone = ZoneSystem.GetZone(pos); if (_cache.TryGetValue(zone, out (long, EnvSetup) value) && value.Item1 == num) { return value.Item2; } if (_cache.Count > 32) { _cache.Clear(); } EnvSetup val = Pick(instance, pos, num); _cache[zone] = (num, val); return val; } private static EnvSetup? Pick(EnvMan em, Vector3 pos, long period) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_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_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) BiomeSector biomeSector = WorldGenerator.instance.GetBiomeSector(pos, false); foreach (AltBiome altBiome in biomeSector.AltBiomes) { if (!string.IsNullOrEmpty(altBiome.m_forceEnvironment)) { return em.GetEnv(altBiome.m_forceEnvironment); } } bool flag = WorldGenerator.IsAshlands(pos.x, pos.z); bool flag2 = WorldGenerator.IsDeepnorth(pos.x, pos.y); State state = Random.state; try { Random.InitState((int)period); List<EnvEntry> availableEnvironments = em.GetAvailableEnvironments(biomeSector); if (availableEnvironments == null || availableEnvironments.Count == 0) { return null; } EnvSetup result = em.SelectWeightedEnvironment(availableEnvironments); foreach (EnvEntry item in availableEnvironments) { if (item.m_ashlandsOverride && flag) { result = item.m_env; } if (item.m_deepnorthOverride && flag2) { result = item.m_env; } } return result; } finally { Random.state = state; } } internal static bool Apply(EnvSetup? env) { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_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_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: 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_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: 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_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_0284: 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_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Unknown result type (might be due to invalid IL or missing references) //IL_02bb: Unknown result type (might be due to invalid IL or missing references) //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_02c5: Unknown result type (might be due to invalid IL or missing references) //IL_0314: Unknown result type (might be due to invalid IL or missing references) //IL_031b: Unknown result type (might be due to invalid IL or missing references) //IL_0320: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_0304: 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_0366: Unknown result type (might be due to invalid IL or missing references) //IL_036e: 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_037b: Unknown result type (might be due to invalid IL or missing references) //IL_0382: Unknown result type (might be due to invalid IL or missing references) //IL_0387: Unknown result type (might be due to invalid IL or missing references) //IL_038d: Unknown result type (might be due to invalid IL or missing references) //IL_0394: Unknown result type (might be due to invalid IL or missing references) //IL_0399: Unknown result type (might be due to invalid IL or missing references) //IL_039f: Unknown result type (might be due to invalid IL or missing references) //IL_03a6: Unknown result type (might be due to invalid IL or missing references) //IL_03ab: 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_03b7: Unknown result type (might be due to invalid IL or missing references) //IL_03be: Unknown result type (might be due to invalid IL or missing references) //IL_03c3: Unknown result type (might be due to invalid IL or missing references) //IL_032b: Unknown result type (might be due to invalid IL or missing references) //IL_032e: Unknown result type (might be due to invalid IL or missing references) //IL_0335: Unknown result type (might be due to invalid IL or missing references) //IL_033b: Unknown result type (might be due to invalid IL or missing references) //IL_0342: Unknown result type (might be due to invalid IL or missing references) //IL_0347: Unknown result type (might be due to invalid IL or missing references) //IL_034d: Unknown result type (might be due to invalid IL or missing references) //IL_0354: Unknown result type (might be due to invalid IL or missing references) //IL_0359: Unknown result type (might be due to invalid IL or missing references) //IL_035e: Unknown result type (might be due to invalid IL or missing references) //IL_0363: 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_041e: Unknown result type (might be due to invalid IL or missing references) //IL_0423: Unknown result type (might be due to invalid IL or missing references) //IL_0458: Unknown result type (might be due to invalid IL or missing references) //IL_045e: 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_03ce: 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_03d8: Unknown result type (might be due to invalid IL or missing references) //IL_03de: Unknown result type (might be due to invalid IL or missing references) //IL_03e5: 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_03f7: Unknown result type (might be due to invalid IL or missing references) //IL_03fc: 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_0406: Unknown result type (might be due to invalid IL or missing references) //IL_04c0: Unknown result type (might be due to invalid IL or missing references) //IL_04c2: 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_04dc: Unknown result type (might be due to invalid IL or missing references) //IL_04e1: 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_04fd: Unknown result type (might be due to invalid IL or missing references) //IL_0508: Unknown result type (might be due to invalid IL or missing references) //IL_0517: Unknown result type (might be due to invalid IL or missing references) EnvMan instance = EnvMan.instance; if (env == null || (Object)(object)instance == (Object)null || (Object)(object)instance.m_dirLight == (Object)null) { return false; } EnvSetup currentEnvironment = instance.GetCurrentEnvironment(); if (currentEnvironment != null && currentEnvironment.m_name == env.m_name) { return false; } Light dirLight = instance.m_dirLight; Material val = (Object.op_Implicit((Object)(object)instance.m_clouds) ? ((Renderer)instance.m_clouds).sharedMaterial : null); _lightRot = ((Component)dirLight).transform.rotation; _lightIntensity = dirLight.intensity; _lightColor = dirLight.color; _fogColor = RenderSettings.fogColor; _fogDensity = RenderSettings.fogDensity; _ambientMode = RenderSettings.ambientMode; _ambientLight = RenderSettings.ambientLight; _skyboxSunDir = Shader.GetGlobalVector(EnvMan.s_skyboxSunDir); _sunDir = Shader.GetGlobalVector(EnvMan.s_sunDir); _sunFogColor = Shader.GetGlobalColor(EnvMan.s_sunFogColor); _sunColor = Shader.GetGlobalColor(EnvMan.s_sunColor); _ambientColor = Shader.GetGlobalColor(EnvMan.s_ambientColor); _wet = Shader.GetGlobalFloat(EnvMan.s_wet); _aurora = Shader.GetGlobalFloat(EnvMan.s_auroraIntensity); if ((Object)(object)val != (Object)null) { _cloudRain = val.GetFloat(EnvMan.s_rain); _cloudOpacity = val.GetFloat(EnvMan.s_opacity); } float dayFraction = instance.GetDayFraction(); float num = Mathf.Pow(Mathf.Max(1f - Mathf.Clamp01(dayFraction / 0.25f), Mathf.Clamp01((dayFraction - 0.75f) / 0.25f)), 0.5f); float num2 = Mathf.Pow(Mathf.Clamp01(1f - Mathf.Abs(dayFraction - 0.5f) / 0.25f), 0.5f); float num3 = Mathf.Min(Mathf.Clamp01(1f - (dayFraction - 0.26f) / (0f - instance.m_sunHorizonTransitionL)), Mathf.Clamp01(1f - (dayFraction - 0.26f) / instance.m_sunHorizonTransitionH)); float num4 = Mathf.Min(Mathf.Clamp01(1f - (dayFraction - 0.74f) / (0f - instance.m_sunHorizonTransitionH)), Mathf.Clamp01(1f - (dayFraction - 0.74f) / instance.m_sunHorizonTransitionL)); float num5 = 1f / (num + num2 + num3 + num4); num *= num5; num2 *= num5; num3 *= num5; num4 *= num5; ((Component)dirLight).transform.rotation = Quaternion.Euler(env.m_sunAngle - 90f, 0f, 0f) * Quaternion.Euler(0f, -90f, 0f) * Quaternion.Euler(360f * dayFraction - 90f, 0f, 0f); Vector3 val2 = -((Component)dirLight).transform.forward; dirLight.intensity = env.m_lightIntensityDay * num2 + env.m_lightIntensityNight * num; if (num > 0f) { Transform transform = ((Component)dirLight).transform; transform.rotation *= Quaternion.Euler(180f, 0f, 0f); } Color val3 = env.m_sunColorNight * num; if (num2 > 0f) { val3 += env.m_sunColorDay * num2 + env.m_sunColorMorning * num3 + env.m_sunColorEvening * num4; } dirLight.color = val3; Color val4 = (RenderSettings.fogColor = env.m_fogColorNight * num + env.m_fogColorDay * num2 + env.m_fogColorMorning * num3 + env.m_fogColorEvening * num4); Color val6 = env.m_fogColorSunNight * num; if (num2 > 0f) { val6 += env.m_fogColorSunDay * num2 + env.m_fogColorSunMorning * num3 + env.m_fogColorSunEvening * num4; } val6 = Color.Lerp(val4, val6, Mathf.Clamp01(Mathf.Max(num, num2) * 3f)); RenderSettings.fogDensity = env.m_fogDensityNight * num + env.m_fogDensityDay * num2 + env.m_fogDensityMorning * num3 + env.m_fogDensityEvening * num4; RenderSettings.ambientMode = (AmbientMode)3; RenderSettings.ambientLight = Color.Lerp(env.m_ambColorNight, env.m_ambColorDay, num2); if ((Object)(object)val != (Object)null) { val.SetFloat(EnvMan.s_rain, env.m_rainCloudAlpha); val.SetFloat(EnvMan.s_opacity, env.m_cloudOpacityDay * num2 + env.m_cloudOpacityEvening * num4 + env.m_cloudOpacityMorning * num3 + env.m_cloudOpacityNight * num); } Shader.SetGlobalVector(EnvMan.s_skyboxSunDir, Vector4.op_Implicit(val2)); Shader.SetGlobalVector(EnvMan.s_sunDir, Vector4.op_Implicit(-((Component)dirLight).transform.forward)); Shader.SetGlobalColor(EnvMan.s_sunFogColor, val6); Shader.SetGlobalColor(EnvMan.s_sunColor, dirLight.color * dirLight.intensity); Shader.SetGlobalColor(EnvMan.s_ambientColor, RenderSettings.ambientLight); Shader.SetGlobalFloat(EnvMan.s_wet, env.m_isWet ? 1f : 0f); Shader.SetGlobalFloat(EnvMan.s_auroraIntensity, env.m_auroraIntensityDay * num2 + env.m_auroraIntensityEvening * num4 + env.m_auroraIntensityMorning * num3 + env.m_auroraIntensityNight * num); return true; } internal static void Restore() { //IL_002a: 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_0049: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) EnvMan instance = EnvMan.instance; if (!((Object)(object)instance == (Object)null) && !((Object)(object)instance.m_dirLight == (Object)null)) { Light dirLight = instance.m_dirLight; ((Component)dirLight).transform.rotation = _lightRot; dirLight.intensity = _lightIntensity; dirLight.color = _lightColor; RenderSettings.fogColor = _fogColor; RenderSettings.fogDensity = _fogDensity; RenderSettings.ambientMode = _ambientMode; RenderSettings.ambientLight = _ambientLight; Shader.SetGlobalVector(EnvMan.s_skyboxSunDir, _skyboxSunDir); Shader.SetGlobalVector(EnvMan.s_sunDir, _sunDir); Shader.SetGlobalColor(EnvMan.s_sunFogColor, _sunFogColor); Shader.SetGlobalColor(EnvMan.s_sunColor, _sunColor); Shader.SetGlobalColor(EnvMan.s_ambientColor, _ambientColor); Shader.SetGlobalFloat(EnvMan.s_wet, _wet); Shader.SetGlobalFloat(EnvMan.s_auroraIntensity, _aurora); Material val = (Object.op_Implicit((Object)(object)instance.m_clouds) ? ((Renderer)instance.m_clouds).sharedMaterial : null); if (!((Object)(object)val == (Object)null)) { val.SetFloat(EnvMan.s_rain, _cloudRain); val.SetFloat(EnvMan.s_opacity, _cloudOpacity); } } } internal static void Clear() { _cache.Clear(); } } [HarmonyPatch] internal static class DestinationOwnership { internal static bool Releasing; private static readonly List<ZDO> _objects = new List<ZDO>(); private static readonly HashSet<SectorIndex> _visited = new HashSet<SectorIndex>(); private static SpawnSystem? _faking; private static Vector3 _fakeCenter; [HarmonyPatch(typeof(ZDOMan), "ReleaseNearbyZDOS")] [HarmonyPrefix] private static void ReleaseNearbyZDOSPrefix() { Releasing = true; } [HarmonyPatch(typeof(ZDOMan), "ReleaseNearbyZDOS")] [HarmonyFinalizer] private static void ReleaseNearbyZDOSFinalizer() { Releasing = false; } [HarmonyPatch(typeof(ZDOMan), "ReleaseNearbyZDOS")] [HarmonyPostfix] private static void ReleaseNearbyZDOS(ZDOMan __instance, long uid) { //IL_002f: 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_00ba: Unknown result type (might be due to invalid IL or missing references) _objects.Clear(); _visited.Clear(); List<Vector2s> zones; List<int> radii; if (uid == __instance.m_sessionID) { PortalPreloadPlugin.DestinationEntry[] cachedDestinations = PortalPreloadPlugin.CachedDestinations; for (int i = 0; i < cachedDestinations.Length; i++) { Collect(__instance, cachedDestinations[i].Zone, cachedDestinations[i].ZoneRadius); } } else if (ServerDestinationSync.TryGetPeer(uid, out zones, out radii)) { for (int j = 0; j < zones.Count; j++) { Collect(__instance, zones[j], radii[j]); } } for (int k = 0; k < _objects.Count; k++) { ZDO val = _objects[k]; if (val.Persistent && val.GetOwner() != uid && (!val.HasOwner() || !__instance.IsInPeerActiveArea(val.GetPosition(), val.GetOwner()))) { val.SetOwner(uid); } } _objects.Clear(); } private static void Collect(ZDOMan man, Vector2s center, int radius) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) for (int i = -radius; i <= radius; i++) { for (int j = -radius; j <= radius; j++) { man.FindObjects(new Vector2s(center.x + j, center.y + i), _objects, _visited); } } } [HarmonyPatch(typeof(ZDOMan), "IsInPeerActiveArea")] [HarmonyPostfix] private static void IsInPeerActiveArea(ZDOMan __instance, Vector3 point, long uid, ref bool __result) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //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) //IL_0028: 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) //IL_0038: 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_004a: 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_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006e: 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) if (__result || uid == __instance.m_sessionID || !ServerDestinationSync.TryGetPeer(uid, out List<Vector2s> zones, out List<int> radii)) { return; } Vector2s zone = ZoneSystem.GetZone(point); for (int i = 0; i < zones.Count; i++) { Vector2s val = zones[i]; int num = radii[i]; if (zone.x >= val.x - num && zone.x <= val.x + num && zone.y >= val.y - num && zone.y <= val.y + num) { __result = true; break; } } } [HarmonyPatch(typeof(SpawnSystem), "GetPlayersInZone")] [HarmonyPostfix] private static void GetPlayersInZone(SpawnSystem __instance, List<Player> players) { //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) //IL_003e: 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_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0075: 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) _faking = null; if (players.Count > 0 || PortalPreloadPlugin.DestinationSpawning.Value.IsOff() || (Object)(object)Player.m_localPlayer == (Object)null) { return; } Vector2s zone = ZoneSystem.GetZone(((Component)__instance).transform.position); PortalPreloadPlugin.DestinationEntry[] cachedDestinations = PortalPreloadPlugin.CachedDestinations; for (int i = 0; i < cachedDestinations.Length; i++) { if (!(cachedDestinations[i].Zone != zone)) { players.Add(Player.m_localPlayer); _faking = __instance; _fakeCenter = cachedDestinations[i].Position; break; } } } [HarmonyPatch(typeof(SpawnSystem), "UpdateSpawnList")] [HarmonyPrefix] private static bool UpdateSpawnList(SpawnSystem __instance, bool eventSpawners) { if (eventSpawners) { return (Object)(object)_faking != (Object)(object)__instance; } return true; } [HarmonyPatch(typeof(SpawnSystem), "FindBaseSpawnPoint")] [HarmonyPrefix] private static bool FindBaseSpawnPoint(SpawnSystem __instance, SpawnData spawn, out Vector3 spawnCenter, out Player targetPlayer, ref bool __result) { //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_005b: 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_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_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) spawnCenter = Vector3.zero; targetPlayer = null; if ((Object)(object)_faking != (Object)(object)__instance) { return true; } float num = ((spawn.m_spawnRadiusMin > 0f) ? spawn.m_spawnRadiusMin : 40f); float num2 = ((spawn.m_spawnRadiusMax > 0f) ? spawn.m_spawnRadiusMax : 80f); __result = false; for (int i = 0; i < 20; i++) { Vector3 val = _fakeCenter + Quaternion.Euler(0f, Random.Range(0f, 360f), 0f) * Vector3.forward * Random.Range(num, num2); if (__instance.IsSpawnPointGood(spawn, ref val)) { spawnCenter = val; __result = true; break; } } return false; } [HarmonyPatch(typeof(SpawnSystem), "UpdateSpawning")] [HarmonyFinalizer] private static void UpdateSpawningFinalizer() { _faking = null; } } [HarmonyPatch] internal static class FasterTeleporting { private static bool _destinationPreloaded = false; private static Vector3 _teleportDestination = Vector3.zero; [HarmonyPatch(typeof(Player), "TeleportTo")] [HarmonyPostfix] private static void TeleportTo_Postfix(Player __instance, Vector3 pos, bool __result) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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_006c: Unknown result type (might be due to invalid IL or missing references) if (__result && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && PortalPreloadPlugin.EnableFasterTeleport.Value.IsOn()) { _teleportDestination = pos; Vector2s zone = ZoneSystem.GetZone(pos); _destinationPreloaded = PortalPreloadPlugin.ProtectedZones.Contains(zone) || PortalPreloadPlugin.HasDestinationNear(pos); if (_destinationPreloaded) { __instance.m_teleportTimer = 2.1f; PortalPreloadPlugin.PortalPreloadLogger.LogDebug((object)$"Destination {zone} is preloaded - fast teleport enabled"); } } } [HarmonyPatch(typeof(Player), "UpdateTeleport")] [HarmonyPrefix] private static bool UpdateTeleport_Prefix(Player __instance, float dt) { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: 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_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer) { return true; } if (!PortalPreloadPlugin.EnableFasterTeleport.Value.IsOn()) { return true; } if (!__instance.m_teleporting) { return true; } if (!_destinationPreloaded) { return true; } __instance.m_teleportCooldown = 0f; __instance.m_teleportTimer += dt; if (__instance.m_teleportTimer <= 0.5f) { return false; } Vector3 val = __instance.m_teleportTargetRot * Vector3.forward; ((Component)__instance).transform.position = __instance.m_teleportTargetPos; ((Component)__instance).transform.rotation = __instance.m_teleportTargetRot; ((Character)__instance).m_body.linearVelocity = Vector3.zero; ((Character)__instance).m_maxAirAltitude = ((Component)__instance).transform.position.y; ((Character)__instance).SetLookDir(val, 0f); if ((Object)(object)ZoneSystem.instance == (Object)null) { return true; } float num = default(float); if (ZNetScene.instance.IsAreaReady(__instance.m_teleportTargetPos) && ZoneSystem.instance.FindFloor(__instance.m_teleportTargetPos, ref num)) { float teleportTimer = __instance.m_teleportTimer; __instance.m_teleportTimer = 0f; __instance.m_teleporting = false; ((Character)__instance).ResetCloth(); _destinationPreloaded = false; PortalPreloadPlugin.PortalPreloadLogger.LogDebug((object)$"Fast teleport completed in {teleportTimer:F2}s"); return false; } if (__instance.m_teleportTimer > 5f) { _destinationPreloaded = false; PortalPreloadPlugin.PortalPreloadLogger.LogDebug((object)"Fast teleport timeout - falling back to vanilla"); return true; } return false; } internal static void Reset() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) _destinationPreloaded = false; _teleportDestination = Vector3.zero; } } [BepInPlugin("Azumatt.PortalPreload", "PortalPreload", "1.2.1")] public class PortalPreloadPlugin : BaseUnityPlugin { public enum ViewStyle { Clear, Wavy, CrystalBall, Ethereal, Shield } public enum CreatureTraversal { Off, Tames, NotHostile, All } public enum RevealStyle { Fade, Iris, Spiral } public enum Toggle { On = 1, Off = 0 } internal struct DestinationEntry { public Vector3 Position; public Vector2s Zone; public int ZoneRadius; public int NextScanFrame; } [HarmonyPatch(typeof(TeleportWorld), "RPC_SetTag")] public static class TeleportWorld_RPC_SetTag_Patch { private static void Postfix(TeleportWorld __instance) { ((MonoBehaviour)__instance).StartCoroutine(DelayedPreload(__instance)); } private static IEnumerator DelayedPreload(TeleportWorld portal) { int i = 0; while (i < 100) { yield return null; int num = i + 1; i = num; } if (!portal.HaveTarget() || !portal.TargetFound()) { yield break; } ZNetView nview = portal.m_nview; if ((Object)(object)nview == (Object)null) { yield break; } ZDO zDO = nview.GetZDO(); if (zDO == null) { yield break; } ZDOID connectionZDOID = zDO.GetConnectionZDOID((ConnectionType)1); if (connectionZDOID != ZDOID.None) { ZDO zDO2 = ZDOMan.instance.GetZDO(connectionZDOID); if (zDO2 != null) { Vector3 position = zDO2.GetPosition(); PortalPreloadLogger.LogInfo((object)$"RPC_SetTag patch: remote portal at {position} found. Preloading..."); PreloadPortalDestination(position); } } } } [HarmonyPatch(typeof(TeleportWorld), "Awake")] public static class TeleportWorld_Awake_Patch { private static void Postfix(TeleportWorld __instance) { if (!Player.IsPlacementGhost(((Component)__instance).gameObject) && (Object)(object)((Component)__instance).GetComponent<PortalPreview>() == (Object)null) { ((Component)__instance).gameObject.AddComponent<PortalPreview>(); PortalPreloadLogger.LogInfo((object)"Added PortalPreview component to TeleportWorld."); } } } [HarmonyPatch(typeof(Game), "Start")] private static class RegisterRPCGameStartPatch { private static void Postfix(Game __instance) { ZRoutedRpc.instance.Register<ZPackage>("PortalPreload_Destinations", (Action<long, ZPackage>)ServerDestinationSync.RPC_Destinations); } } [HarmonyPatch(typeof(ZNetScene), "OnDestroy")] private static class ZNetSceneOnDestroyCleanupPatch { private static void Postfix() { ClearAllDestinations(); ProtectedZones.Clear(); IsPlayerTeleporting = false; PortalViews.Clear(); PreloadScheduler.Clear(); ServerDestinationSync.Clear(); FasterTeleporting.Reset(); PortalItems.Clear(); PortalCreatures.Clear(); TargetPortalCompat.Clear(); PortalPreloadLogger.LogDebug((object)"World unloading - cleared all static state"); } } [HarmonyPatch(typeof(Player), "TeleportTo")] private static class PlayerTeleportToPatch { private static void Postfix(Player __instance, bool __result) { if (__result && (Object)(object)__instance == (Object)(object)Player.m_localPlayer) { IsPlayerTeleporting = true; PortalPreloadLogger.LogDebug((object)"Player started teleporting - protecting zones"); } } } [HarmonyPatch(typeof(Player), "UpdateTeleport")] private static class PlayerUpdateTeleportPatch { private static void Postfix(Player __instance) { //IL_003a: 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_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0056: 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_0066: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || !IsPlayerTeleporting || ((Character)__instance).IsTeleporting()) { return; } IsPlayerTeleporting = false; PortalPreloadLogger.LogDebug((object)"Player finished teleporting"); Vector3 position = ((Component)__instance).transform.position; Vector2s zone = ZoneSystem.GetZone(position); for (int i = -2; i <= 2; i++) { for (int j = -2; j <= 2; j++) { ProtectedZones.Add(new Vector2s(zone.x + i, zone.y + j)); } } AddDestination(position, 3); ((MonoBehaviour)__instance).StartCoroutine(DelayedZoneCleanup(position, zone)); } private static IEnumerator DelayedZoneCleanup(Vector3 landingPos, Vector2s landingZone) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) yield return (object)new WaitForSeconds(5f); RemoveDestination(landingPos); if ((Object)(object)Player.m_localPlayer != (Object)null) { Vector2s zone = ZoneSystem.GetZone(((Component)Player.m_localPlayer).transform.position); Vector2s val = default(Vector2s); for (int i = -2; i <= 2; i++) { for (int j = -2; j <= 2; j++) { ((Vector2s)(ref val))..ctor(landingZone.x + i, landingZone.y + j); if (Mathf.Abs(zone.x - val.x) > 3 || Mathf.Abs(zone.y - val.y) > 3) { ProtectedZones.Remove(val); } } } } PortalPreloadLogger.LogDebug((object)"Cleaned up post-teleport zone protection"); } } internal const string ModName = "PortalPreload"; internal const string ModVersion = "1.2.1"; internal const string Author = "Azumatt"; private const string ModGUID = "Azumatt.PortalPreload"; private static string ConfigFileName = "Azumatt.PortalPreload.cfg"; private static string ConfigFileFullPath; public static readonly ManualLogSource PortalPreloadLogger; private readonly Harmony _harmony = new Harmony("Azumatt.PortalPreload"); private static readonly ConfigSync ConfigSync; internal static ConfigEntry<Toggle> EnablePreloading; internal static ConfigEntry<Toggle> EnableFasterTeleport; internal static ConfigEntry<int> MaxPreloadedPortals; internal static ConfigEntry<float> PreloadRadius; internal static ConfigEntry<int> MaxZoneRadius; internal static ConfigEntry<Toggle> EnablePreview; internal static ConfigEntry<float> PreviewDistance; internal static ConfigEntry<int> MaxVisiblePreviews; internal static ConfigEntry<int> ExtraRendersPerFrame; internal static ConfigEntry<int> IdleRefreshRate; internal static ConfigEntry<int> PreviewMaxResolution; internal static ConfigEntry<float> PreviewResolutionScale; internal static ConfigEntry<Toggle> SmoothFiltering; internal static ConfigEntry<int> AdaptiveTargetFps; internal static ConfigEntry<float> DrawDistance; internal static ConfigEntry<float> PreviewShadowDistance; internal static ConfigEntry<Toggle> PreviewGrass; internal static ConfigEntry<Toggle> PreviewDestinationWeather; internal static ConfigEntry<Toggle> HideVanillaSwirl; internal static ConfigEntry<ViewStyle> PreviewStyle; internal static ConfigEntry<float> ViewEffectStrength; internal static ConfigEntry<RevealStyle> Reveal; internal static ConfigEntry<Toggle> ProjectilesThroughPortals; internal static ConfigEntry<Toggle> ItemsThroughPortals; internal static ConfigEntry<CreatureTraversal> CreaturesThroughPortals; internal static ConfigEntry<Toggle> DestinationSpawning; internal static ConfigEntry<Toggle> TargetPortalMapPreview; internal static HashSet<Vector2s> ProtectedZones; internal const float ObjectLoadRadius = 40f; internal const float CloseDistance = 5f; internal const float MediumDistance = 10f; internal const float FarDistance = 15f; internal static bool IsPlayerTeleporting; internal static DestinationEntry[] CachedDestinations; private static readonly Dictionary<Vector3, int> _destRadii; private static readonly Dictionary<Vector3, int> _destRefCounts; private float _preloadTimer; internal static bool HasDestinations => CachedDestinations.Length != 0; internal static int GetZoneRadiusForDistance(float distance) { if (distance <= 5f) { return 3; } if (distance <= 10f) { return 2; } return 1; } internal static void AddDestination(Vector3 pos, int zoneRadius) { //IL_0005: 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_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0014: 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_0030: Unknown result type (might be due to invalid IL or missing references) if (_destRefCounts.TryGetValue(pos, out var value)) { _destRefCounts[pos] = value + 1; if (zoneRadius > _destRadii[pos]) { _destRadii[pos] = zoneRadius; } } else { _destRefCounts[pos] = 1; _destRadii[pos] = zoneRadius; } RebuildCachedDestinations(); } internal static void UpdateDestinationRadius(Vector3 pos, int zoneRadius) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) if (_destRadii.ContainsKey(pos) && _destRadii[pos] != zoneRadius) { _destRadii[pos] = zoneRadius; RebuildCachedDestinations(); } } internal static void RemoveDestination(Vector3 pos) { //IL_0005: 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_0019: 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) if (_destRefCounts.TryGetValue(pos, out var value)) { if (value <= 1) { _destRefCounts.Remove(pos); _destRadii.Remove(pos); } else { _destRefCounts[pos] = value - 1; } RebuildCachedDestinations(); } } internal static bool HasDestinationNear(Vector3 pos, float tolerance = 10f) { //IL_0015: 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_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) float num = tolerance * tolerance; DestinationEntry[] cachedDestinations = CachedDestinations; for (int i = 0; i < cachedDestinations.Length; i++) { Vector3 val = cachedDestinations[i].Position - pos; if (((Vector3)(ref val)).sqrMagnitude < num) { return true; } } return false; } private static void RebuildCachedDestinations() { //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_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: 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_007c: Unknown result type (might be due to invalid IL or missing references) if (_destRadii.Count == 0) { CachedDestinations = Array.Empty<DestinationEntry>(); return; } DestinationEntry[] array = new DestinationEntry[_destRadii.Count]; int num = 0; foreach (KeyValuePair<Vector3, int> destRadius in _destRadii) { array[num++] = new DestinationEntry { Position = destRadius.Key, Zone = (((Object)(object)ZoneSystem.instance != (Object)null) ? ZoneSystem.GetZone(destRadius.Key) : Vector2s.zero), ZoneRadius = destRadius.Value }; } CachedDestinations = array; } internal static void ClearAllDestinations() { _destRadii.Clear(); _destRefCounts.Clear(); CachedDestinations = Array.Empty<DestinationEntry>(); } public void Awake() { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Expected O, but got Unknown //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Expected O, but got Unknown //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Expected O, but got Unknown //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Expected O, but got Unknown //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Expected O, but got Unknown //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Expected O, but got Unknown //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Expected O, but got Unknown //IL_0240: Unknown result type (might be due to invalid IL or missing references) //IL_024a: Expected O, but got Unknown //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_0280: Expected O, but got Unknown //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_02dd: Expected O, but got Unknown //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_031a: Expected O, but got Unknown //IL_03cd: Unknown result type (might be due to invalid IL or missing references) //IL_03d7: Expected O, but got Unknown EnablePreloading = ((BaseUnityPlugin)this).Config.Bind<Toggle>("General", "EnablePreloading", Toggle.On, "If on, the mod preloads portal destinations."); EnableFasterTeleport = ((BaseUnityPlugin)this).Config.Bind<Toggle>("General", "EnableFasterTeleport", Toggle.On, "If on, the teleportation is faster."); MaxPreloadedPortals = ((BaseUnityPlugin)this).Config.Bind<int>("Preloading", "MaxPreloadedPortals", 2, new ConfigDescription("How many portal destinations can be loaded at once. The portals you are closest to and looking at win. Keeps big portal rooms from loading every destination together.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 8), Array.Empty<object>())); PreloadRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Preloading", "PreloadRadius", 15f, new ConfigDescription("How close you need to be to a portal, in metres, before its destination starts loading.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 40f), Array.Empty<object>())); MaxZoneRadius = ((BaseUnityPlugin)this).Config.Bind<int>("Preloading", "MaxZoneRadius", 2, new ConfigDescription("Largest ring of zones loaded around a destination. 1 = 3x3 zones, 2 = 5x5, 3 = 7x7.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 3), Array.Empty<object>())); EnablePreview = ((BaseUnityPlugin)this).Config.Bind<Toggle>("Preview", "EnablePreview", Toggle.On, "If on, portals show a live view of their destination."); PreviewDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Preview", "PreviewDistance", 12f, new ConfigDescription("How close you need to be to a portal, in metres, to see through it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(3f, 40f), Array.Empty<object>())); MaxVisiblePreviews = ((BaseUnityPlugin)this).Config.Bind<int>("Preview", "MaxVisiblePreviews", 4, new ConfigDescription("Most portals showing a view at the same time. The nearest ones win.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 16), Array.Empty<object>())); ExtraRendersPerFrame = ((BaseUnityPlugin)this).Config.Bind<int>("Preview", "ExtraRendersPerFrame", 1, new ConfigDescription("The nearest portal updates every frame. This many of the others update per frame on top of that, taking turns.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 8), Array.Empty<object>())); IdleRefreshRate = ((BaseUnityPlugin)this).Config.Bind<int>("Preview", "IdleRefreshRate", 20, new ConfigDescription("Updates per second while your view of a portal isn't moving, for creatures, fire and water on the far side. 0 = only update when you move.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 144), Array.Empty<object>())); PreviewMaxResolution = ((BaseUnityPlugin)this).Config.Bind<int>("Preview", "MaxResolution", 1536, new ConfigDescription("Largest texture a portal view renders at, in pixels. Views are sized to how big the portal is on your screen, this caps it.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(256, 4096), Array.Empty<object>())); PreviewResolutionScale = ((BaseUnityPlugin)this).Config.Bind<float>("Preview", "ResolutionScale", 1f, new ConfigDescription("View resolution relative to the portal's size on your screen. 1 = pixel for pixel. Above 1 renders extra detail and shrinks it down (supersampling), which gets rid of grain and jagged edges at a cost. 1.5 is a good sharp setting.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 2f), Array.Empty<object>())); AdaptiveTargetFps = ((BaseUnityPlugin)this).Config.Bind<int>("Preview", "AdaptiveTargetFPS", 50, new ConfigDescription("While views are showing and the game runs below this frame rate, views lower their resolution (down to 40%) and update less, then sharpen back up once it recovers. 0 = off, always full quality.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 240), Array.Empty<object>())); SmoothFiltering = ((BaseUnityPlugin)this).Config.Bind<Toggle>("Preview", "SmoothFiltering", Toggle.On, "If on, views are filtered like a normal game texture (mipmaps, trilinear, anisotropic). Smoother, and needed for ResolutionScale above 1 to look its best."); DrawDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Preview", "DrawDistance", 400f, new ConfigDescription("How far the view draws on the far side, in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(50f, 2000f), Array.Empty<object>())); PreviewShadowDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Preview", "ShadowDistance", 40f, new ConfigDescription("How far past the portal the view draws shadows, in metres. Shadows are the most expensive part of a view. 0 turns them off.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 150f), Array.Empty<object>())); PreviewGrass = ((BaseUnityPlugin)this).Config.Bind<Toggle>("Preview", "Grass", Toggle.On, "If on, grass is grown around the far side of the nearest portal view. The game normally only grows it around you."); HideVanillaSwirl = ((BaseUnityPlugin)this).Config.Bind<Toggle>("Preview", "HideVanillaSwirl", Toggle.On, "If on, the dark swirl and blue flames of the vanilla portal effect are hidden while a view is showing. The sparks, runes, glow and sound stay."); PreviewStyle = ((BaseUnityPlugin)this).Config.Bind<ViewStyle>("Preview", "Style", ViewStyle.Clear, "How the view looks. Clear = the plain live render. Wavy = ripples rolling across it like water. CrystalBall = the middle magnified like a glass orb, with a dark glassy rim. Ethereal = a slow warm-air drift with a misty blue edge. Shield = a rippling force field bubble over it, using the game's own ForceField material."); Reveal = ((BaseUnityPlugin)this).Config.Bind<RevealStyle>("Preview", "Reveal", RevealStyle.Iris, "How a view opens when you walk up to a portal. Fade = fades in. Iris = opens from the middle out. Spiral = opens from the middle with a swirling edge."); ViewEffectStrength = ((BaseUnityPlugin)this).Config.Bind<float>("Preview", "StyleStrength", 1f, new ConfigDescription("How strongly the style bends the view. 1 = default.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 3f), Array.Empty<object>())); ViewEffectStrength.SettingChanged += delegate { PortalPreview.ApplyLensStrength(); }; PreviewDestinationWeather = ((BaseUnityPlugin)this).Config.Bind<Toggle>("Preview", "DestinationWeather", Toggle.On, "If on, views are lit with the weather, fog and light of the destination's biome instead of yours."); ProjectilesThroughPortals = ((BaseUnityPlugin)this).Config.Bind<Toggle>("Traversal", "Projectiles", Toggle.On, "If on, arrows, bolts, spears and spells fly through a portal whose destination is loaded and come out the other side with the same speed and direction. Synced from the server."); ConfigSync.AddConfigEntry<Toggle>(ProjectilesThroughPortals); ItemsThroughPortals = ((BaseUnityPlugin)this).Config.Bind<Toggle>("Traversal", "Items", Toggle.On, "If on, dropped or thrown items that go into a portal whose destination is loaded come out the other side still moving. Items the portal would not let you carry (ore and the like) just fall through the frame like normal. Synced from the server."); ConfigSync.AddConfigEntry<Toggle>(ItemsThroughPortals); CreaturesThroughPortals = ((BaseUnityPlugin)this).Config.Bind<CreatureTraversal>("Traversal", "Creatures", CreatureTraversal.NotHostile, "Which creatures walk through a portal whose destination is loaded. Off = none. Tames = only tamed ones. NotHostile = tames, wild animals like deer, and anything that won't attack you (Dvergr). All = everything, monsters included. Bosses and anything being ridden never go through. Synced from the server."); ConfigSync.AddConfigEntry<CreatureTraversal>(CreaturesThroughPortals); DestinationSpawning = ((BaseUnityPlugin)this).Config.Bind<Toggle>("Traversal", "SpawnAtDestination", Toggle.On, "If on, creatures spawn around a portal's loaded destination as if you were standing at it, so there is something alive on the other side. Off = the far side only has what was already there. Synced from the server."); ConfigSync.AddConfigEntry<Toggle>(DestinationSpawning); TargetPortalMapPreview = ((BaseUnityPlugin)this).Config.Bind<Toggle>("TargetPortal", "MapPreview", Toggle.On, "Only matters with TargetPortal installed. If on, resting the mouse on a portal on the destination map loads it and shows a live view of it next to the cursor, and the jump is near instant once it has loaded. Portals always remember where you last went from them and show that view."); Assembly executingAssembly = Assembly.GetExecutingAssembly(); _harmony.PatchAll(executingAssembly); } private void FixedUpdate() { PortalItems.FixedUpdate(); PortalCreatures.FixedUpdate(); } private void Update() { if (!((_preloadTimer -= Time.deltaTime) > 0f)) { _preloadTimer = 0.2f; PreloadScheduler.Tick(); } } public static void PreloadPortalDestination(Vector3 destinationPos) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_004b: 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_0065: Unknown result type (might be due to invalid IL or missing references) if (EnablePreloading.Value == Toggle.Off) { PortalPreloadLogger.LogDebug((object)"Preloading disabled by config."); return; } PortalPreloadLogger.LogInfo((object)$"Preloading destination at {destinationPos}"); Vector2s zone = ZoneSystem.GetZone(destinationPos); int num = 5; Vector2s item = default(Vector2s); for (int i = -num; i <= num; i++) { for (int j = -num; j <= num; j++) { ((Vector2s)(ref item))..ctor(zone.x + i, zone.y + j); ProtectedZones.Add(item); } } } static PortalPreloadPlugin() { string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName; PortalPreloadLogger = Logger.CreateLogSource("PortalPreload"); ConfigSync = new ConfigSync("Azumatt.PortalPreload") { DisplayName = "PortalPreload", CurrentVersion = "1.2.1", MinimumRequiredVersion = "1.2.1" }; EnablePreloading = null; EnableFasterTeleport = null; MaxPreloadedPortals = null; PreloadRadius = null; MaxZoneRadius = null; EnablePreview = null; PreviewDistance = null; MaxVisiblePreviews = null; ExtraRendersPerFrame = null; IdleRefreshRate = null; PreviewMaxResolution = null; PreviewResolutionScale = null; SmoothFiltering = null; AdaptiveTargetFps = null; DrawDistance = null; PreviewShadowDistance = null; PreviewGrass = null; PreviewDestinationWeather = null; HideVanillaSwirl = null; PreviewStyle = null; ViewEffectStrength = null; Reveal = null; ProjectilesThroughPortals = null; ItemsThroughPortals = null; CreaturesThroughPortals = null; DestinationSpawning = null; TargetPortalMapPreview = null; ProtectedZones = new HashSet<Vector2s>(); IsPlayerTeleporting = false; CachedDestinations = Array.Empty<DestinationEntry>(); _destRadii = new Dictionary<Vector3, int>(); _destRefCounts = new Dictionary<Vector3, int>(); } } public static class ToggleExtensions { [SpecialName] public sealed class <G>$F0761429328CE66EDE8B39DE93B80CE2 { [SpecialName] public static class <M>$76059A2A9DE173D12B656BE2E483953E { } [ExtensionMarker("<M>$76059A2A9DE173D12B656BE2E483953E")] public bool IsOn() { throw null; } [ExtensionMarker("<M>$76059A2A9DE173D12B656BE2E483953E")] public bool IsOff() { throw null; } } public static bool IsOn(this PortalPreloadPlugin.Toggle toggle) { return toggle == PortalPreloadPlugin.Toggle.On; } public static bool IsOff(this PortalPreloadPlugin.Toggle toggle) { return toggle == PortalPreloadPlugin.Toggle.Off; } } public class PortalPreview : MonoBehaviour { internal static readonly List<PortalPreview> All = new List<PortalPreview>(); private static readonly Dictionary<ZDOID, PortalPreview> ById = new Dictionary<ZDOID, PortalPreview>(); private ZDOID _id; private static readonly Dictionary<string, (Vector3 Center, Vector2 Size)> Openings = new Dictionary<string, (Vector3, Vector2)> { ["portal_wood"] = (new Vector3(0f, 1.31f, 0.01f), new Vector2(2.85f, 2.85f)), ["portal_stone"] = (new Vector3(0f, 2.33f, 0.01f), new Vector2(3.84f, 4f)) }; private const int Segments = 64; private const int Rings = 20; private const float Feather = 0.06f; internal TeleportWorld Portal; internal Transform Opening; internal float HalfWidth; internal float HalfHeight; private MeshRenderer _rend; private Material _mat; private Renderer[]? _renderers; private Light[]? _lights; private PortalPreview? _remote; internal RenderTexture? Rt; internal bool HasFrame; internal Vector3 EyeLocal; internal Vector3 LastRenderedEye; internal float LastRenderTime; internal float Distance; private float _hiddenSince; private float _fade; private Renderer[]? _swirl; private bool _swirlHidden; private MeshRenderer? _lens; private bool _lensTried; private static Material? _lensMaterial; private static bool _lensLookedUp; private Mesh? _mesh; private Vector2[] _baseUv; private Vector2[] _uv; private float[] _radius; private float[] _angle; private float _reveal; private Color[] _baseColors; private Color[] _colors; private bool _animated; private float _phase; private static readonly HashSet<string> SwirlParts = new HashSet<string> { "Black_suck", "blue flames" }; private static readonly Color RimTint = new Color(0.72f, 0.88f, 1f, 1f); private static readonly Color GlassEdge = new Color(0.5f, 0.58f, 0.75f, 1f); private static readonly Color Mist = new Color(0.62f, 0.7f, 0.95f, 1f); private const float LensOffset = 0.03f; private const float LensBulge = 0.18f; private static float _baseRefraction = -1f; private const float RevealSeconds = 0.7f; internal Quaternion EntryRotation => Quaternion.LookRotation(-((Component)Portal).transform.forward, ((Component)Portal).transform.up); internal Quaternion ExitRotation => Quaternion.LookRotation(((Component)Portal).transform.forward, ((Component)Portal).transform.up); internal ZDOID Id => ((Object.op_Implicit((Object)(object)Portal) && Object.op_Implicit((Object)(object)Portal.m_nview)) ? Portal.m_nview.GetZDO() : null)?.m_uid ?? ZDOID.None; internal ZDOID RemoteId { get { //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_0036: 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_0054: 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_004b: Unknown result type (might be due to invalid IL or missing references) ZDO val = ((Object.op_Implicit((Object)(object)Portal) && Object.op_Implicit((Object)(object)Portal.m_nview)) ? Portal.m_nview.GetZDO() : null); if (val == null) { return ZDOID.None; } ZDOID connectionZDOID = val.GetConnectionZDOID((ConnectionType)1); if (!TargetPortalCompat.Active) { return connectionZDOID; } return TargetPortalCompat.TargetFor(this, val.m_uid, connectionZDOID); } } internal bool Linked { get { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) if (!TargetPortalCompat.Active) { if (Portal.HaveTarget()) { return Portal.TargetFound(); } return false; } return RemoteId != ZDOID.None; } } internal Renderer[] Renderers => _renderers ?? (_renderers = ((Component)Portal).GetComponentsInChildren<Renderer>(true)); internal Light[] Lights => _lights ?? (_lights = ((Component)Portal).GetComponentsInChildren<Light>(true)); internal Bounds Bounds => new Bounds(Opening.position, Vector3.one * (2f * Mathf.Max(HalfWidth, HalfHeight))); internal bool Showing { get { if ((Object)(object)_rend != (Object)null) { return ((Renderer)_rend).enabled; } return false; } } private void Awake() { Portal = ((Component)this).GetComponent<TeleportWorld>(); _phase = Random.value * 100f; } private void Start() { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_0073: 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_0094: 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_00ae: 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_00f1: 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_0115: Expected O, but got Unknown //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) Transform val = (Object.op_Implicit((Object)(object)Portal.m_model) ? ((Component)Portal.m_model).transform : ((Component)this).transform); GameObject val2 = new GameObject("PortalPreviewPlane"); val2.transform.SetParent(val, false); if (!Openings.TryGetValue(Utils.GetPrefabName(((Component)this).gameObject), out (Vector3, Vector2) value)) { value = Openings["portal_wood"]; } val2.transform.localPosition = value.Item1; val2.transform.localRotation = Quaternion.identity; val2.transform.localScale = new Vector3(value.Item2.x, value.Item2.y, 1f); Opening = val2.transform; val2.AddComponent<MeshFilter>().sharedMesh = BuildOpeningMesh(); _rend = val2.AddComponent<MeshRenderer>(); _mat = new Material(Shader.Find("Sprites/Default")) { color = new Color(1f, 1f, 1f, 0f) }; ((Renderer)_rend).sharedMaterial = _mat; ((Renderer)_rend).shadowCastingMode = (ShadowCastingMode)0; ((Renderer)_rend).receiveShadows = false; ((Renderer)_rend).enabled = false; All.Add(this); _id = Id; if (_id != ZDOID.None) { ById[_id] = this; } } private Mesh BuildOpeningMesh() { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: 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_021a: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Unknown result type (might be due to invalid IL or missing references) //IL_0245: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_025a: 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_0315: 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_0359: Unknown result type (might be due to invalid IL or missing references) //IL_035e: Unknown result type (might be due to invalid IL or missing references) //IL_0369: 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_037c: 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_0390: Expected O, but got Unknown int num = 64; int num2 = 1 + 20 * num; Vector3[] array = (Vector3[])(object)new Vector3[num2]; Color[] array2 = (Color[])(object)new Color[num2]; _radius = new float[num2]; _angle = new float[num2]; int[] array3 = new int[(num + 19 * num * 2) * 3]; array[0] = Vector3.zero; array2[0] = Color.white; for (int i = 1; i <= 20; i++) { float num3 = ((i == 20) ? 1f : ((float)i / 19f * 0.94f)); for (int j = 0; j < num; j++) { float num4 = (float)j * (float)Math.PI * 2f / (float)num; int num5 = 1 + (i - 1) * num + j; array[num5] = new Vector3(Mathf.Cos(num4) * 0.5f * num3, Mathf.Sin(num4) * 0.5f * num3, 0f); array2[num5] = (Color)((i == 20) ? new Color(1f, 1f, 1f, 0f) : Color.white); _radius[num5] = num3; _angle[num5] = num4; } } int num6 = 0; for (int k = 0; k < num; k++) { array3[num6++] = 0; array3[num6++] = 1 + k; array3[num6++] = 1 + (k + 1) % num; } for (int l = 1; l < 20; l++) { int num7 = 1 + (l - 1) * num; int num8 = 1 + l * num; for (int m = 0; m < num; m++) { int num9 = (m + 1) % num; array3[num6++] = num7 + m; array3[num6++] = num8 + m; array3[num6++] = num8 + num9; array3[num6++] = num7 + m; array3[num6++] = num8 + num9; array3[num6++] = num7 + num9; } } Quaternion val = Quaternion.Inverse(EntryRotation); Vector3[] array4 = (Vector3[])(object)new Vector3[num2]; for (int n = 0; n < num2; n++) { array4[n] = val * (Opening.TransformPoint(array[n]) - Opening.position); HalfWidth = Mathf.Max(HalfWidth, Mathf.Abs(array4[n].x)); HalfHeight = Mathf.Max(HalfHeight, Mathf.Abs(array4[n].y)); } _baseUv = (Vector2[])(object)new Vector2[num2]; for (int num10 = 0; num10 < num2; num10++) { _baseUv[num10] = new Vector2(0.5f + array4[num10].x / (2f * HalfWidth), 0.5f + array4[num10].y / (2f * HalfHeight)); } _uv = (Vector2[])_baseUv.Clone(); _baseColors = array2; _colors = (Color[])array2.Clone(); _mesh = new Mesh { name = "PortalPreviewOpening", vertices = array, uv = _baseUv, colors = array2, triangles = array3 }; _mesh.MarkDynamic(); _mesh.RecalculateBounds(); return _mesh; } private static float Smooth(float a, float b, float x) { return Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(a, b, x)); } private void Animate(PortalPreloadPlugin.ViewStyle style, PortalPreloadPlugin.RevealStyle reveal) { //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_0220: 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_0225: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0231: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_028d: 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_02ac: Unknown result type (might be due to invalid IL or missing references) //IL_02db: Unknown result type (might be due to invalid IL or missing references) //IL_02e0: Unknown result type (might be due to invalid IL or missing references) //IL_036d: Unknown result type (might be due to invalid IL or missing references) //IL_036f: Unknown result type (might be due to invalid IL or missing references) //IL_037c: Unknown result type (might be due to invalid IL or missing references) //IL_037e: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0139: 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_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_mesh == (Object)null) { return; } bool flag = reveal != PortalPreloadPlugin.RevealStyle.Fade && _reveal < 1f; if (style == PortalPreloadPlugin.ViewStyle.Clear && !flag) { if (_animated) { _animated = false; _mesh.SetUVs(0, _baseUv); _mesh.SetColors(_baseColors); } return; } _animated = true; float num = Time.time + _phase; float value = PortalPreloadPlugin.ViewEffectStrength.Value; Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(0.5f, 0.5f); for (int i = 0; i < _baseUv.Length; i++) { Vector2 val2 = _baseUv[i]; Vector2 val3 = val2 - val; float num2 = _radius[i]; Vector2 val4 = val2; Color val5 = Color.white; float num4; float num5; Vector2 val6; switch (style) { case PortalPreloadPlugin.ViewStyle.Wavy: num4 = 0.011f; goto IL_00f1; case PortalPreloadPlugin.ViewStyle.Shield: num4 = 0.004f; goto IL_00f1; case PortalPreloadPlugin.ViewStyle.CrystalBall: { float num3 = 1f - value * (0.26f * (1f - num2 * num2) + 0.012f * Mathf.Sin(num * 0.8f) * (1f - num2)); val4 = val + val3 * num3; val5 = Color.Lerp(val5, GlassEdge, Mathf.Pow(num2, 5f)); break; } case PortalPreloadPlugin.ViewStyle.Ethereal: { val4.x += 0.006f * value * Mathf.Sin(val2.y * 6f + num * 0.6f); val4.y += 0.006f * value * Mathf.Sin(val2.x * 5f - num * 0.5f); val5 = Color.Lerp(val5, Mist, Smooth(0.45f, 1f, num2) * (0.8f + 0.2f * Mathf.Sin(num * 0.9f))); break; } IL_00f1: num5 = num4 * value; val6 = ((num2 > 0.001f) ? ((Vector2)(ref val3)).normalized : Vector2.zero); val4 += val6 * (num5 * Mathf.Sin(num2 * 22f - num * 3.2f) * (0.35f + 0.65f * num2)); val4.x += num5 * 0.5f * Mathf.Sin(val2.y * 17f + num * 1.7f); val4.y += num5 * 0.5f * Mathf.Cos(val2.x * 15f - num * 1.3f); if (style == PortalPreloadPlugin.ViewStyle.Shield) { val5 = Color.Lerp(val5, RimTint, Mathf.Pow(num2, 6f) * (0.75f + 0.25f * Mathf.Sin(num * 2.1f + num2 * 9f))); } break; } float num6 = _baseColors[i].a; if (flag) { float num7 = _reveal * 1.2f; if (reveal == PortalPreloadPlugin.RevealStyle.Spiral) { num7 += 0.12f * Mathf.Sin(_angle[i] * 3f + num2 * 8f - _reveal * 10f); } num6 *= 1f - Smooth(num7 - 0.12f, num7, num2); } val5.a = num6; _uv[i] = val4; _colors[i] = val5; } _mesh.SetUVs(0, _uv); _mesh.SetColors(_colors); } private void BuildLens() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: 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_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0132: 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_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_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_0251: Unknown result type (might be due to invalid IL or missing references) //IL_0258: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Expected O, but got Unknown //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Expected O, but got Unknown Material val = LensMaterial(); if ((Object)(object)val == (Object)null) { return; } float num = Mathf.Sign(Opening.InverseTransformDirection(((Component)Portal).transform.forward).z); int num2 = 64; Vector3[] array = (Vector3[])(object)new Vector3[1 + 8 * num2]; Vector2[] array2 = (Vector2[])(object)new Vector2[array.Length]; int[] array3 = new int[(num2 + 7 * num2 * 2) * 3]; array[0] = new Vector3(0f, 0f, num * 0.21000001f); array2[0] = new Vector2(0.5f, 0.5f); Vector2 val2 = default(Vector2); for (int i = 1; i <= 8; i++) { float num3 = (float)i / 8f; for (int j = 0; j < num2; j++) { float num4 = (float)j * (float)Math.PI * 2f / (float)num2; ((Vector2)(ref val2))..ctor(Mathf.Cos(num4) * 0.5f * num3, Mathf.Sin(num4) * 0.5f * num3); array[(i - 1) * num2 + j + 1] = new Vector3(val2.x, val2.y, num * (0.03f + 0.18f * (1f - num3 * num3))); array2[(i - 1) * num2 + j + 1] = val2 + new Vector2(0.5f, 0.5f); } } int num5 = 0; for (int k = 0; k < num2; k++) { array3[num5++] = 0; array3[num5++] = 1 + k; array3[num5++] = 1 + (k + 1) % num2; } for (int l = 1; l < 8; l++) { int num6 = (l - 1) * num2 + 1; int num7 = l * num2 + 1; for (int m = 0; m < num2; m++) { int num8 = (m + 1) % num2; array3[num5++] = num6 + m; array3[num5++] = num7 + m; array3[num5++] = num7 + num8; array3[num5++] = num6 + m; array3[num5++] = num7 + num8; array3[num5++] = num6 + num8; } } Mesh val3 = new Mesh { name = "PortalPreviewLens", vertices = array, uv = array2, triangles = array3 }; val3.RecalculateNormals(); val3.RecalculateTangents(); val3.RecalculateBounds(); GameObject val4 = new GameObject("PortalPreviewLens"); val4.transform.SetParent(Opening, false); val4.AddComponent<MeshFilter>().sharedMesh = val3; _lens = val4.AddComponent<MeshRenderer>(); ((Renderer)_lens).sharedMaterial = val; ((Renderer)_lens).shadowCastingMode = (ShadowCastingMode)0; ((Renderer)_lens).receiveShadows = false; ((Renderer)_lens).enabled = false; _renderers = null; } private static Material? LensMaterial() { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: 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_0082: Expected O, but got Unknown if (_lensLookedUp) { return _lensMaterial; } _lensLookedUp = true; Material[] array = Resources.FindObjectsOfTypeAll<Material>(); foreach (Material val in array) { if (!((Object)(object)val == (Object)null) && !(((Object)val).name != "ForceField") && !((Object)(object)val.shader == (Object)null) && !(((Object)val.shader).name != "Custom/Distortion")) { _lensMaterial = new Material(val) { name = "PortalPreviewLens", renderQueue = 3100 }; ApplyLensStrength(); break; } } if ((Object)(object)_lensMaterial == (Object)null) { PortalPreloadPlugin.PortalPreloadLogger.LogDebug((object)"ForceField material not found, portal views get no shield lens"); } return _lensMaterial; } internal static void ApplyLensStrength() { if (!((Object)(object)_lensMaterial == (Object)null) && _lensMaterial.HasProperty("_RefractionIntensity")) { if (_baseRefraction < 0f) { _baseRefraction = _lensMaterial.GetFloat("_RefractionIntensity"); } _lensMaterial.SetFloat("_RefractionIntensity", _baseRefraction * PortalPreloadPlugin.ViewEffectStrength.Value); } } internal PortalPreview? FindRemote() { //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_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0057: 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) ZDOID remoteId = RemoteId; if (remoteId == ZDOID.None) { return null; } if ((Object)(object)_remote != (Object)null && (Object)(object)_remote.Opening != (Object)null && _remote._id == remoteId) { return _remote; } _remote = ((ById.TryGetValue(remoteId, out PortalPreview value) && (Object)(object)value != (Object)null && (Object)(object)value != (Object)(object)this && (Object)(object)value.Opening != (Object)null) ? value : null); return _remote; } internal void Show(float dt) { //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) _hiddenSince = -1f; if (!HasFrame) { ((Renderer)_rend).enabled = false; return; } ((Renderer)_rend).enabled = true; SetSwirlHidden(PortalPreloadPlugin.HideVanillaSwirl.Value.IsOn()); PortalPreloadPlugin.RevealStyle value = PortalPreloadPlugin.Reveal.Value; if (value == PortalPreloadPlugin.RevealStyle.Fade) { _reveal = 1f; if (_fade < 1f) { _fade = Mathf.Min(1f, _fade + dt * 4f); _mat.color = new Color(1f, 1f, 1f, _fade); } } else { _fade = 1f; _mat.color = Color.white; _reveal = Mathf.Min(1f, _reveal + dt / 0.7f); } PortalPreloadPlugin.ViewStyle value2 = PortalPreloadPlugin.PreviewStyle.Value; Animate(value2, value); if (value2 == PortalPreloadPlugin.ViewStyle.Shield && !_lensTried) { _lensTried = true; BuildLens(); } if ((Object)(object)_lens != (Object)null) { ((Renderer)_lens).enabled = value2 == PortalPreloadPlugin.ViewStyle.Shield && _fade > 0.5f && _reveal > 0.6f; } } internal void Hide() { //IL_0079: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_rend == (Object)null)) { SetSwirlHidden(hidden: false); if ((Object)(object)_lens != (Object)null) { ((Renderer)_lens).enabled = false; } if (((Renderer)_rend).enabled) { ((Renderer)_rend).enabled = false; _fade = 0f; _reveal = 0f; _mat.color = new Color(1f, 1f, 1f, 0f); } if (_hiddenSince < 0f) { _hiddenSince = Time.time; } else if ((Object)(object)Rt != (Object)null && Time.time - _hiddenSince > 5f) { ReleaseTexture(); } } } private void SetSwirlHidden(bool hidden) { if (hidden == _swirlHidden) { return; } _swirlHidden = hidden; if (_swirl == null) { List<Renderer> list = new List<Renderer>(); if ((Object)(object)Portal.m_target_found != (Object)null) { Renderer[] componentsInChildren = ((Component)Portal.m_target_found).GetComponentsInChildren<Renderer>(true); foreach (Renderer val in componentsInChildren) { if (SwirlParts.Contains(((Object)((Component)val).gameObject).name)) { list.Add(val); } } } _swirl = list.ToArray(); } for (int j = 0; j < _swirl.Length; j++) { if ((Object)(object)_swirl[j] != (Object)null) { _swirl[j].enabled = !hidden; } } } internal void EnsureTexture(int size, bool smooth) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006b: 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_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown if (!((Object)(object)Rt != (Object)null) || Rt.useMipMap != smooth || size > ((Texture)Rt).width || !((float)size > (float)((Texture)Rt).width * 0.7f)) { ReleaseTexture(); Rt = new RenderTexture(size, size, 24, (RenderTextureFormat)0) { name = "PortalPreviewRT", antiAliasing = 1, wrapMode = (TextureWrapMode)1, useMipMap = smooth, autoGenerateMips = smooth, filterMode = (FilterMode)((!smooth) ? 1 : 2), anisoLevel = (smooth ? 4 : 0) }; Rt.Create(); _mat.mainTexture = (Texture)(object)Rt; } } private void ReleaseTexture() { HasFrame = false; if (!((Object)(object)Rt == (Object)null)) { if ((Object)(object)_mat != (Object)null) { _mat.mainTexture = null; } Rt.Release(); Object.Destroy((Object)(object)Rt); Rt = null; } } private void OnDestroy() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) All.Remove(this); if (_id != ZDOID.None && ById.TryGetValue(_id, out PortalPreview value) && (Object)(object)value == (Object)(object)this) { ById.Remove(_id); } ReleaseTexture(); if ((Object)(object)_mat != (Object)null) { Object.Destroy((Object)(object)_mat); } } } [HarmonyPatch] internal static class PortalViews { private static Camera? _cam; private const float CenteredEyeBack = 1.4f; private const int CenteredSize = 512; private static readonly Plane[] _frustum = (Plane[])(object)new Plane[6]; private static readonly List<PortalPreview> _visible = new List<PortalPreview>(); private static readonly List<bool> _savedEnabled = new List<bool>(); private static readonly List<LightShadows> _savedShadows = new List<LightShadows>(); private static float _quality = 1f; private static float _frameMs = 16f; private static readonly Vector3[] _corners = (Vector3[])(object)new Vector3[4]; internal static Vector3? GrassCenter; private static readonly Plane[] _grassFrustum = (Plane[])(object)new Plane[6]; [HarmonyPatch(typeof(GameCamera), "LateUpdate")] [HarmonyPostfix] private static void GameCameraLateUpdate() { RenderAll(); } private static void RenderAll() { //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: 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_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: 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_013c: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_018f: 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_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: 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_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_01d5: Unknown result type (might be due to invalid IL or missing references) GrassCenter = null; List<PortalPreview> all = PortalPreview.All; if (all.Count == 0) { return; } Camera mainCamera = Utils.GetMainCamera(); Player localPlayer = Player.m_localPlayer; if (PortalPreloadPlugin.EnablePreview.Value.IsOff() || (Object)(object)mainCamera == (Object)null || (Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsTeleporting()) { for (int i = 0; i < all.Count; i++) { all[i].Hide(); } return; } GeometryUtility.CalculateFrustumPlanes(mainCamera, _frustum); Vector3 position = ((Component)mainCamera).transform.position; Vector3 val = (Object.op_Implicit((Object)(object)((Character)localPlayer).m_eye) ? ((Character)localPlayer).m_eye.position : ((Component)localPlayer).transform.position); float value = PortalPreloadPlugin.PreviewDistance.Value; _visible.Clear(); for (int j = 0; j < all.Count; j++) { PortalPreview portalPreview = all[j]; if ((Object)(object)portalPreview == (Object)null || (Object)(object)portalPreview.Opening == (Object)null) { continue; } if (!portalPreview.Linked) { portalPreview.Hide(); continue; } if ((Object)(object)portalPreview.FindRemote() == (Object)null) { portalPreview.Hide(); portalPreview.HasFrame = false; continue; } portalPreview.Distance = Vector3.Distance(val, portalPreview.Opening.position); if (TargetPortalCompat.WantsCenteredView(portalPreview)) { portalPreview.EyeLocal = new Vector3(0f, 0f, (0f - portalPreview.HalfHeight) * 1.4f); _visible.Add(portalPreview); continue; } portalPreview.EyeLocal = Quaternion.Inverse(portalPreview.EntryRotation) * (position - portalPreview.Opening.position); if (portalPreview.Distance > value || portalPreview.EyeLocal.z > -0.05f || !GeometryUtility.TestPlanesAABB(_frustum, portalPreview.Bounds)) { portalPreview.Hide(); } else { _visible.Add(portalPreview); } } _visible.Sort(ByDistance); UpdateQuality(_visible.Count > 0); int num = Mathf.Min(_visible.Count, PortalPreloadPlugin.MaxVisiblePreviews.Value); for (int k = num; k < _visible.Count; k++) { _visible[k].Hide(); } if (num > 0) { PortalPreview? portalPreview2 = _visible[0].FindRemote(); GrassCenter = ((portalPreview2 != null) ? new Vector3?(portalPreview2.Opening.position) : ((Vector3?)null)); } float time = Time.time; float idleInterval = ((PortalPreloadPlugin.IdleRefreshRate.Value > 0) ? (1f / (float)PortalPreloadPlugin.IdleRefreshRate.Value) : float.MaxValue); if (num > 0 && NeedsRender(_visible[0], time, idleInterval)) { Render(mainCamera, _visible[0]); } for (int num2 = ((!(_quality < 0.7f)) ? PortalPreloadPlugin.ExtraRendersPerFrame.Value : 0); num2 > 0; num2--) { PortalPreview portalPreview3 = null; for (int l = 1; l < num; l++) { PortalPreview portalPreview4 = _visible[l]; if (portalPreview4.LastRenderTime < time && NeedsRender(portalPreview4, time, idleInterval) && ((Object)(object)portalPreview3 == (Object)null || portalPreview4.LastRenderTime < portalPreview3.LastRenderTime)) { portalPreview3 = portalPreview4; } } if ((Object)(object)portalPreview3 == (Object)null) { break; } Render(mainCamera, portalPreview3); } float deltaTime = Time.deltaTime; for (int m = 0; m < num; m++) { _visible[m].Show(deltaTime); } } [HarmonyPatch(typeof(ClutterSystem), "UpdateGrass")] [HarmonyPostfix] private static void UpdateGrass(ClutterSystem __instance, Vector3 center) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0032: 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_0047: 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_0060: Unknown result type (might be due to invalid IL or missing references) Vector3? grassCenter = GrassCenter; if (grassCenter.HasValue) { Vector3 valueOrDefault = grassCenter.GetValueOrDefault(); if (!PortalPreloadPlugin.PreviewGrass.Value.IsOff() && (int)__instance.m_quality != 0 && !(Utils.DistanceXZ(valueOrDefault, center) < __instance.m_distance) && ZoneSystem.instance.IsZoneLoaded(valueOrDefault) && !Heightmap.HaveQueuedRebuild(valueOrDefault, __instance.m_distance)) { __instance.GeneratePatches(false, valueOrDefault); } } } private static void DrawGrass(Camera cam, Vector3 dest) { //IL_003a: 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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) ClutterSystem instance = ClutterSystem.instance; if ((Object)(object)instance == (Object)null || PortalPreloadPlugin.PreviewGrass.Value.IsOff() || InstanceRenderer.s_layer < 0) { return; } GeometryUtility.CalculateFrustumPlanes(cam, _grassFrustum); Vector3 position = ((Component)cam).transform.position; float num = instance.m_distance + instance.m_grassPatchSize; Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(instance.m_grassPatchSize, 4000f, instance.m_grassPatchSize); InstanceRenderer val3 = default(InstanceRenderer); foreach (PatchData value in instance.m_patches.Values) { if (Utils.DistanceXZ(value.center, dest) > num || !GeometryUtility.TestPlanesAABB(_grassFrustum, new Bounds(value.center, val))) { continue; } for (int i = 0; i < value.m_objects.Count; i++) { GameObject val2 = value.m_objects[i]; if ((Object)(object)val2 == (Object)null || !val2.TryGetComponent<InstanceRenderer>(ref val3) || val3.m_instanceCount == 0) { continue; } int num2 = val3.m_instanceCount; if (val3.m_useLod) { float num3 = (val3.m_useXZLodDistance ? Utils.DistanceXZ(position, ((Component)val3).transform.position) : Vector3.Distance(position, ((Component)val3).transform.position)); num2 = (int)((1f - Utils.LerpStep(val3.m_lodMinDistance, val3.m_lodMaxDistance, num3)) * (float)val3.m_instanceCount); if (num2 <= 0) { continue; } } Graphics.DrawMeshInstanced(val3.m_mesh, 0, val3.m_material, val3.m_instances, num2, (MaterialPropertyBlock)null, val3.m_shadowCasting, true,
plugins/HBK-HBKHEIM/Sailing-1.1.12/Sailing.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using HarmonyLib; using JetBrains.Annotations; using LocalizationManager; using Microsoft.CodeAnalysis; using ServerSync; using SkillManager; using TMPro; using UnityEngine; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("Sailing")] [assembly: AssemblyDescription("https://valheim.hexium.gg/mods/Smoothbrain/Sailing")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sailing")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("F7B25B5A-5CFB-43CA-934A-440CDB9CB1A9")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.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 Sailing { [BepInPlugin("org.bepinex.plugins.sailing", "Sailing", "1.1.12")] [BepInIncompatibility("org.bepinex.plugins.valheim_plus")] public class Sailing : BaseUnityPlugin { private enum Toggle { On = 1, Off = 0 } private class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ShowRangeAsPercent; [UsedImplicitly] public int? Order; [UsedImplicitly] public string? Description; [UsedImplicitly] public string? DispName; } [HarmonyPatch(typeof(WearNTear), "OnPlaced")] private class AddZDO { [UsedImplicitly] private static void Postfix(WearNTear __instance) { if (Object.op_Implicit((Object)(object)((Component)__instance).GetComponent<Ship>())) { ((Component)__instance).GetComponent<ZNetView>().GetZDO().Set("Sailing Skill Level", ((Character)(object)Player.m_localPlayer).GetSkillFactor("Sailing")); __instance.m_health *= 1f + ((Component)__instance).GetComponent<ZNetView>().GetZDO().GetFloat("Sailing Skill Level", 0f) * shipHealthIncrease.Value; ((Character)(object)Player.m_localPlayer).RaiseSkill("Sailing", 35f); } } } [HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")] private class FetchShipPiecesObjectDB { [HarmonyPriority(0)] private static void Postfix(ObjectDB __instance) { GameObject itemPrefab = __instance.GetItemPrefab("Hammer"); PieceTable val = ((itemPrefab == null) ? null : itemPrefab.GetComponent<ItemDrop>()?.m_itemData.m_shared.m_buildPieces); if (val != null) { FetchShipPieces(val.m_pieces); } } } [HarmonyPatch(typeof(ZNetScene), "Awake")] private class FetchShipPiecesZNetScene { [HarmonyPriority(0)] private static void Postfix(ZNetScene __instance) { FetchShipPieces(__instance.m_prefabs); } } [HarmonyPatch(typeof(Ladder), "Interact")] private static class NudgeShip { private static DateTime lastNudge = DateTime.UtcNow; private static bool Prefix(Ladder __instance) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0033: 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_0049: 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_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) if (allowShipNudge.Value == Toggle.Off || ((Character)Player.m_localPlayer).IsSwimming()) { return true; } KeyboardShortcut value = shipNudgeModifierkey.Value; if (Input.GetKey(((KeyboardShortcut)(ref value)).MainKey)) { value = shipNudgeModifierkey.Value; if (((KeyboardShortcut)(ref value)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey)) { if ((DateTime.UtcNow - lastNudge).TotalSeconds < 1.0) { return false; } lastNudge = DateTime.UtcNow; Rigidbody componentInParent = ((Component)__instance).GetComponentInParent<Rigidbody>(); if (Math.Abs(Vector3.SignedAngle(((Component)componentInParent).transform.position - ((Component)Player.m_localPlayer).transform.position, ((Component)Player.m_localPlayer).transform.forward, ((Component)Player.m_localPlayer).transform.up)) < 90f) { componentInParent.AddForce(((Component)Player.m_localPlayer).transform.forward * componentInParent.mass * nudgeForce.Value, (ForceMode)1); } else { ((Character)Player.m_localPlayer).Message((MessageType)2, Localization.instance.Localize("$sailing_nudge_failed"), 0, (Sprite)null, false); } return false; } } return true; } } [HarmonyPatch(typeof(Ladder), "GetHoverText")] private class OverrideHoverText { public static void Postfix(ref string __result) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (allowShipNudge.Value != Toggle.Off && !((Character)Player.m_localPlayer).IsSwimming()) { __result += Localization.instance.Localize($"\n[<b><color=yellow>{shipNudgeModifierkey.Value}</color> + <color=yellow>$KEY_Use</color></b>] $sailing_nudge_interact"); } } } [HarmonyPatch(typeof(WearNTear), "Awake")] private class IncreaseHealth { [UsedImplicitly] private static void Prefix(WearNTear __instance) { float health = __instance.m_health; ZDO zDO = ((Component)__instance).GetComponent<ZNetView>().GetZDO(); __instance.m_health = health * (1f + ((zDO != null) ? zDO.GetFloat("Sailing Skill Level", 0f) : (Object.op_Implicit((Object)(object)((Component)__instance).GetComponent<Ship>()) ? ((Character)(object)Player.m_localPlayer).GetSkillFactor("Sailing") : 1f)) * shipHealthIncrease.Value); } } [HarmonyPatch(typeof(Minimap), "Explore", new Type[] { typeof(Vector3), typeof(float) })] private class IncreaseExplorationRadius { [UsedImplicitly] private static void Prefix(Minimap __instance, ref float radius) { Player localPlayer = Player.m_localPlayer; if (localPlayer != null && localPlayer.m_attached && localPlayer.m_attachedToShip) { radius *= 1f + ((Character)(object)localPlayer).GetSkillFactor("Sailing") * explorationRadiusIncrease.Value; } } } [HarmonyPatch(typeof(Ship), "GetSailForce")] private class ChangeShipSpeed { [UsedImplicitly] private class Timer { public float UpdateDelta = 0f; public float lastUpdate = Time.fixedTime; } private static readonly ConditionalWeakTable<Ship, Timer> timers = new ConditionalWeakTable<Ship, Timer>(); private static void Postfix(Ship __instance, ref Vector3 __result) { //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Invalid comparison between Unknown and I4 //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) Timer orCreateValue = timers.GetOrCreateValue(__instance); Player val = ((IEnumerable<Player>)Player.s_players).FirstOrDefault((Func<Player, bool>)((Player p) => p.GetPlayerID() == __instance.m_shipControlls.GetUser())); if (val != null) { if (shipSpeedIncrease.TryGetValue(((Component)__instance).GetComponent<Piece>().m_name, out ConfigEntry<float> value)) { __result *= 1f + ((Character)val).m_nview.GetZDO().GetFloat("Sailing Skill", 0f) * value.Value; } if ((int)__instance.m_speed != 0) { orCreateValue.UpdateDelta += Time.fixedTime - orCreateValue.lastUpdate; if (orCreateValue.UpdateDelta > 1f) { ((Character)val).m_nview.InvokeRPC("Sailing Skill Increase", new object[1] { 0.5f }); orCreateValue.UpdateDelta -= 1f; } } } orCreateValue.lastUpdate = Time.fixedTime; } } [HarmonyPatch(typeof(Ship), "Forward")] private class PreventShipSpeeds { private static bool Prefix(Ship __instance) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Invalid comparison between Unknown and I4 if ((int)__instance.m_speed == 2 && shipHalfRequirement.TryGetValue(((Component)__instance).GetComponent<Piece>().m_name, out ConfigEntry<int> value) && value.Value > Mathf.RoundToInt(((Character)(object)Player.m_localPlayer).GetSkillFactor("Sailing") * 100f)) { ((Character)Player.m_localPlayer).Message((MessageType)2, Localization.instance.Localize("$sailing_no_reduced_sail"), 0, (Sprite)null, false); return false; } if ((int)__instance.m_speed == 3 && shipFullRequirement.TryGetValue(((Component)__instance).GetComponent<Piece>().m_name, out ConfigEntry<int> value2) && value2.Value > Mathf.RoundToInt(((Character)(object)Player.m_localPlayer).GetSkillFactor("Sailing") * 100f)) { ((Character)Player.m_localPlayer).Message((MessageType)2, Localization.instance.Localize("$sailing_no_full_sail"), 0, (Sprite)null, false); return false; } return true; } } [HarmonyPatch(typeof(ShipControlls), "Interact")] private class BlockSailing { private static bool Prefix(ShipControlls __instance) { if (!shipPaddleRequirement.TryGetValue(((Component)__instance.m_ship).GetComponent<Piece>().m_name, out ConfigEntry<int> value) || value.Value <= Mathf.RoundToInt(((Character)(object)Player.m_localPlayer).GetSkillFactor("Sailing") * 100f)) { return true; } ((Character)Player.m_localPlayer).Message((MessageType)2, Localization.instance.Localize("$sailing_no_sail"), 0, (Sprite)null, false); return false; } } [HarmonyPatch(typeof(Player), "Awake")] private class ExposeSailingSkill { private static void Postfix(Player __instance) { ((Character)__instance).m_nview.Register<float>("Sailing Skill Increase", (Action<long, float>)delegate(long _, float amount) { ((Character)(object)__instance).RaiseSkill("Sailing", amount); }); } } [HarmonyPatch(typeof(Player), "Update")] public class PlayerUpdate { private static void Postfix(Player __instance) { if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer) { ((Character)__instance).m_nview.GetZDO().Set("Sailing Skill", ((Character)(object)__instance).GetSkillFactor("Sailing")); } } } private const string ModName = "Sailing"; private const string ModVersion = "1.1.12"; private const string ModGUID = "org.bepinex.plugins.sailing"; private static readonly ConfigSync configSync = new ConfigSync("org.bepinex.plugins.sailing") { DisplayName = "Sailing", CurrentVersion = "1.1.12", MinimumRequiredVersion = "1.1.12" }; private static ConfigEntry<Toggle> serverConfigLocked = null; private static ConfigEntry<float> explorationRadiusIncrease = null; private static ConfigEntry<float> shipHealthIncrease = null; private static ConfigEntry<float> experienceGainedFactor = null; private static ConfigEntry<int> experienceLoss = null; private static ConfigEntry<KeyboardShortcut> shipNudgeModifierkey = null; private static ConfigEntry<Toggle> allowShipNudge = null; private static ConfigEntry<float> nudgeForce = null; private static readonly Dictionary<string, ConfigEntry<float>> shipSpeedIncrease = new Dictionary<string, ConfigEntry<float>>(); private static readonly Dictionary<string, ConfigEntry<int>> shipPaddleRequirement = new Dictionary<string, ConfigEntry<int>>(); private static readonly Dictionary<string, ConfigEntry<int>> shipHalfRequirement = new Dictionary<string, ConfigEntry<int>>(); private static readonly Dictionary<string, ConfigEntry<int>> shipFullRequirement = new Dictionary<string, ConfigEntry<int>>(); private static Skill sailing = null; private static Sailing mod = null; private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description); SyncedConfigEntry<T> syncedConfigEntry = configSync.AddConfigEntry<T>(val); syncedConfigEntry.SynchronizedConfig = synchronizedSetting; return val; } private ConfigEntry<T> config<T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting); } public void Awake() { //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Expected O, but got Unknown //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Expected O, but got Unknown //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Expected O, but got Unknown //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Expected O, but got Unknown //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Expected O, but got Unknown //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Expected O, but got Unknown //IL_024a: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Expected O, but got Unknown //IL_0265: Unknown result type (might be due to invalid IL or missing references) //IL_026b: Expected O, but got Unknown Localizer.Load(); sailing = new Skill("Sailing", "sailing.png"); sailing.Name.Alias("sailing_skill"); sailing.Description.Alias("sailing_skill_description"); sailing.Configurable = false; serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only."); configSync.AddLockingConfigEntry<Toggle>(serverConfigLocked); shipNudgeModifierkey = config<KeyboardShortcut>("1 - General", "Ship Nudge Modifier Key", new KeyboardShortcut((KeyCode)304, Array.Empty<KeyCode>()), new ConfigDescription("Modifier key to hold, to nudge your ship. Clear value to disable this.", (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting: false); explorationRadiusIncrease = config("3 - Other", "Exploration Radius Factor", 5f, new ConfigDescription("Exploration radius factor while on ships at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>())); shipHealthIncrease = config("3 - Other", "Ship Health Factor", 2f, new ConfigDescription("Health factor for ships at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>())); experienceGainedFactor = config("3 - Other", "Skill Experience Gain Factor", 1f, new ConfigDescription("Factor for experience gained for the sailing skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), Array.Empty<object>())); experienceGainedFactor.SettingChanged += delegate { sailing.SkillGainFactor = experienceGainedFactor.Value; }; sailing.SkillGainFactor = experienceGainedFactor.Value; experienceLoss = config("3 - Other", "Skill Experience Loss", 0, new ConfigDescription("How much experience to lose in the sailing skill on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); experienceLoss.SettingChanged += delegate { sailing.SkillLoss = experienceLoss.Value; }; sailing.SkillLoss = experienceLoss.Value; allowShipNudge = config("3 - Other", "Allow Ship Nudge", Toggle.On, new ConfigDescription("If on, players can press a hotkey, to give their ship a nudge, if it is stuck.", (AcceptableValueBase)null, Array.Empty<object>())); nudgeForce = config("3 - Other", "Ship Nudge Force", 10f, new ConfigDescription("Impulse force for ship nudge.", (AcceptableValueBase)null, Array.Empty<object>())); Assembly executingAssembly = Assembly.GetExecutingAssembly(); Harmony val = new Harmony("org.bepinex.plugins.sailing"); val.PatchAll(executingAssembly); mod = this; } private static void FetchShipPieces(IEnumerable<GameObject> prefabs) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: 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_035e: Unknown result type (might be due to invalid IL or missing references) //IL_0369: Expected O, but got Unknown //IL_0426: Unknown result type (might be due to invalid IL or missing references) //IL_0431: Expected O, but got Unknown Localization val = new Localization(); val.SetupLanguage("English"); Regex regex = new Regex("['[\"\\]]"); List<string> shipOrder = new List<string> { "$ship_longship_ashlands", "$ship_longship", "$ship_karve", "$ship_raft" }; foreach (Ship item in from p in prefabs select p.GetComponent<Ship>() into s where (Object)(object)((s != null) ? ((Component)s).GetComponent<Piece>() : null) != (Object)null orderby shipOrder.IndexOf(((Component)s).GetComponent<Piece>().m_name) descending select s) { int num = -shipSpeedIncrease.Count * 4; string name = ((Component)item).GetComponent<Piece>().m_name; if (!shipSpeedIncrease.ContainsKey(name)) { shipSpeedIncrease[name] = mod.config("2 - Ship Speed", regex.Replace(val.Localize(name), "") + " Speed Factor", 1.5f, new ConfigDescription("Speed factor for " + val.Localize(name) + " at skill level 100.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 3f), new object[1] { new ConfigurationManagerAttributes { Order = (num -= 1), DispName = Localization.instance.Localize(name) + " Speed Factor", Description = "Speed factor for " + Localization.instance.Localize(name) + " at skill level 100." } })); shipPaddleRequirement[name] = mod.config("2 - Ship Speed", regex.Replace(val.Localize(name), "") + " Paddle Requirement", 0, new ConfigDescription("Required sailing skill level to be able to paddle a " + val.Localize(name) + ".", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1] { new ConfigurationManagerAttributes { Order = (num -= 1), ShowRangeAsPercent = false, DispName = Localization.instance.Localize(name) + " Paddle Requirement", Description = "Required sailing skill level to be able to paddle a " + Localization.instance.Localize(name) + "." } })); shipHalfRequirement[name] = mod.config("2 - Ship Speed", regex.Replace(val.Localize(name), "") + " Half Requirement", 0, new ConfigDescription("Required sailing skill level to be able to sail a " + val.Localize(name) + " with reduced sail.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1] { new ConfigurationManagerAttributes { Order = (num -= 1), ShowRangeAsPercent = false, DispName = Localization.instance.Localize(name) + " Half Requirement", Description = "Required sailing skill level to be able to sail a " + Localization.instance.Localize(name) + " with reduced sail." } })); shipFullRequirement[name] = mod.config("2 - Ship Speed", regex.Replace(val.Localize(name), "") + " Full Requirement", 0, new ConfigDescription("Required sailing skill level to be able to sail a " + val.Localize(name) + " with full sail.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1] { new ConfigurationManagerAttributes { Order = (num -= 1), ShowRangeAsPercent = false, DispName = Localization.instance.Localize(name) + " Full Requirement", Description = "Required sailing skill level to be able to sail a " + Localization.instance.Localize(name) + " with full sail." } })); } } } } } namespace SkillManager { [PublicAPI] internal class Skill { public static class LocalizationCache { private static readonly Dictionary<string, Localization> localizations = new Dictionary<string, Localization>(); internal static void LocalizationPostfix(Localization __instance, string language) { string key = localizations.FirstOrDefault<KeyValuePair<string, Localization>>((KeyValuePair<string, Localization> l) => l.Value == __instance).Key; if (key != null) { localizations.Remove(key); } if (!localizations.ContainsKey(language)) { localizations.Add(language, __instance); } } public static Localization ForLanguage(string? language = null) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out Localization value)) { return value; } value = new Localization(); if (language != null) { value.SetupLanguage(language); } return value; } } [PublicAPI] public class LocalizeKey { private static readonly List<LocalizeKey> keys = new List<LocalizeKey>(); public readonly string Key; public readonly Dictionary<string, string> Localizations = new Dictionary<string, string>(); public LocalizeKey(string key) { Key = key.Replace("$", ""); keys.Add(this); } public void Alias(string alias) { Localizations.Clear(); if (!alias.Contains("$")) { alias = "$" + alias; } Localizations["alias"] = alias; Localization.instance.AddWord(Key, Localization.instance.Localize(alias)); } public LocalizeKey English(string key) { return addForLang("English", key); } public LocalizeKey Swedish(string key) { return addForLang("Swedish", key); } public LocalizeKey French(string key) { return addForLang("French", key); } public LocalizeKey Italian(string key) { return addForLang("Italian", key); } public LocalizeKey German(string key) { return addForLang("German", key); } public LocalizeKey Spanish(string key) { return addForLang("Spanish", key); } public LocalizeKey Russian(string key) { return addForLang("Russian", key); } public LocalizeKey Romanian(string key) { return addForLang("Romanian", key); } public LocalizeKey Bulgarian(string key) { return addForLang("Bulgarian", key); } public LocalizeKey Macedonian(string key) { return addForLang("Macedonian", key); } public LocalizeKey Finnish(string key) { return addForLang("Finnish", key); } public LocalizeKey Danish(string key) { return addForLang("Danish", key); } public LocalizeKey Norwegian(string key) { return addForLang("Norwegian", key); } public LocalizeKey Icelandic(string key) { return addForLang("Icelandic", key); } public LocalizeKey Turkish(string key) { return addForLang("Turkish", key); } public LocalizeKey Lithuanian(string key) { return addForLang("Lithuanian", key); } public LocalizeKey Czech(string key) { return addForLang("Czech", key); } public LocalizeKey Hungarian(string key) { return addForLang("Hungarian", key); } public LocalizeKey Slovak(string key) { return addForLang("Slovak", key); } public LocalizeKey Polish(string key) { return addForLang("Polish", key); } public LocalizeKey Dutch(string key) { return addForLang("Dutch", key); } public LocalizeKey Portuguese_European(string key) { return addForLang("Portuguese_European", key); } public LocalizeKey Portuguese_Brazilian(string key) { return addForLang("Portuguese_Brazilian", key); } public LocalizeKey Chinese(string key) { return addForLang("Chinese", key); } public LocalizeKey Japanese(string key) { return addForLang("Japanese", key); } public LocalizeKey Korean(string key) { return addForLang("Korean", key); } public LocalizeKey Hindi(string key) { return addForLang("Hindi", key); } public LocalizeKey Thai(string key) { return addForLang("Thai", key); } public LocalizeKey Abenaki(string key) { return addForLang("Abenaki", key); } public LocalizeKey Croatian(string key) { return addForLang("Croatian", key); } public LocalizeKey Georgian(string key) { return addForLang("Georgian", key); } public LocalizeKey Greek(string key) { return addForLang("Greek", key); } public LocalizeKey Serbian(string key) { return addForLang("Serbian", key); } public LocalizeKey Ukrainian(string key) { return addForLang("Ukrainian", key); } private LocalizeKey addForLang(string lang, string value) { Localizations[lang] = value; if (Localization.instance.GetSelectedLanguage() == lang) { Localization.instance.AddWord(Key, value); } else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key)) { Localization.instance.AddWord(Key, value); } return this; } [HarmonyPriority(300)] internal static void AddLocalizedKeys(Localization __instance, string language) { foreach (LocalizeKey key in keys) { string value2; if (key.Localizations.TryGetValue(language, out string value) || key.Localizations.TryGetValue("English", out value)) { __instance.AddWord(key.Key, value); } else if (key.Localizations.TryGetValue("alias", out value2)) { __instance.AddWord(key.Key, Localization.instance.Localize(value2)); } } } } private class ConfigurationManagerAttributes { [UsedImplicitly] public string? Category; } [HarmonyPatch(typeof(Skills), "IsSkillValid")] private static class Patch_Skills_IsSkillValid { private static void Postfix(SkillType type, ref bool __result) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (!__result && skills.ContainsKey(type)) { __result = true; } } } private static readonly Dictionary<SkillType, Skill> skills; internal static readonly Dictionary<string, Skill> skillByName; private readonly string skillName; private readonly string internalSkillName; private readonly SkillDef skillDef; public readonly LocalizeKey Name; public readonly LocalizeKey Description; private float skillEffectFactor = 1f; private int skillLoss = 5; public bool Configurable = false; private static bool InitializedTerminal; private static Localization? _english; private static BaseUnityPlugin? _plugin; private static bool hasConfigSync; private static object? _configSync; public float SkillGainFactor { get { return skillDef.m_increseStep; } set { skillDef.m_increseStep = value; this.SkillGainFactorChanged?.Invoke(value); } } public float SkillEffectFactor { get { return skillEffectFactor; } set { skillEffectFactor = value; this.SkillEffectFactorChanged?.Invoke(value); } } public int SkillLoss { get { return skillLoss; } set { skillLoss = value; this.SkillLossChanged?.Invoke(value); } } private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English")); private static BaseUnityPlugin plugin { get { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown object obj = _plugin; if (obj == null) { BaseUnityPlugin val = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)Assembly.GetExecutingAssembly().DefinedTypes.First((TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); _plugin = val; obj = (object)val; } return (BaseUnityPlugin)obj; } } private static object? configSync { get { if (_configSync == null && hasConfigSync) { Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync"); if ((object)type != null) { _configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " SkillManager"); type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString()); type.GetProperty("IsLocked").SetValue(_configSync, true); } else { hasConfigSync = false; } } return _configSync; } } public event Action<float>? SkillGainFactorChanged; public event Action<float>? SkillEffectFactorChanged; public event Action<float>? SkillLossChanged; public Skill(string englishName, string icon) : this(englishName, loadSprite(icon, 64, 64)) { } public unsafe Skill(string englishName, Sprite icon) { //IL_0022: 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_0043: 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_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0082: 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_008d: Expected O, but got Unknown SkillType val = fromName(englishName); string text = new Regex("[^a-zA-Z]").Replace(englishName, "_"); skills[val] = this; skillByName[englishName] = this; skillDef = new SkillDef { m_description = "$skilldesc_" + text, m_icon = icon, m_increseStep = 1f, m_skill = val }; internalSkillName = text; skillName = englishName; Name = new LocalizeKey("skill_" + ((object)(*(SkillType*)(&val))/*cast due to .constrained prefix*/).ToString()).English(englishName); Description = new LocalizeKey("skilldesc_" + text); } public static SkillType fromName(string englishName) { return (SkillType)Math.Abs(StringExtensionMethods.GetStableHashCode(englishName)); } static Skill() { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Expected O, but got Unknown //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Expected O, but got Unknown //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Expected O, but got Unknown //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Expected O, but got Unknown //IL_0185: 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_01ad: Expected O, but got Unknown //IL_01ad: Expected O, but got Unknown //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Expected O, but got Unknown //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Expected O, but got Unknown //IL_023f: Expected O, but got Unknown skills = new Dictionary<SkillType, Skill>(); skillByName = new Dictionary<string, Skill>(); InitializedTerminal = false; hasConfigSync = true; Harmony val = new Harmony("org.bepinex.helpers.skillmanager"); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "GetSkillDef", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_GetSkillDef", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatRaiseSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatRaiseskill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "CheatResetSkill", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_CheatResetSkill", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Terminal), "InitTerminal", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Terminal_InitTerminal", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Skills), "OnDeath", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Skill), "Patch_Skills_OnDeath_Finalizer", (Type[])null, (Type[])null)), (HarmonyMethod)null); } private static void Patch_FejdStartup() { //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Expected O, but got Unknown //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Expected O, but got Unknown //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Expected O, but got Unknown foreach (Skill skill in skills.Values) { if (skill.Configurable) { string key = skill.Name.Key; string text = new Regex("['[\"\\]]").Replace(english.Localize(key), "").Trim(); string category = Localization.instance.Localize(key).Trim(); ConfigEntry<float> skillGain = config(text, "Skill gain factor", skill.SkillGainFactor, new ConfigDescription("The rate at which you gain experience for the skill.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1] { new ConfigurationManagerAttributes { Category = category } })); skill.SkillGainFactor = skillGain.Value; skillGain.SettingChanged += delegate { skill.SkillGainFactor = skillGain.Value; }; ConfigEntry<float> skillEffect = config(text, "Skill effect factor", skill.SkillEffectFactor, new ConfigDescription("The power of the skill, based on the default power.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 5f), new object[1] { new ConfigurationManagerAttributes { Category = category } })); skill.SkillEffectFactor = skillEffect.Value; skillEffect.SettingChanged += delegate { skill.SkillEffectFactor = skillEffect.Value; }; ConfigEntry<int> skillLoss = config(text, "Skill loss", skill.skillLoss, new ConfigDescription("How much experience to lose on death.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), new object[1] { new ConfigurationManagerAttributes { Category = category } })); skill.skillLoss = skillLoss.Value; skillLoss.SettingChanged += delegate { skill.skillLoss = skillLoss.Value; }; } } } private static void Patch_Skills_GetSkillDef(ref SkillDef? __result, List<SkillDef> ___m_skills, SkillType type) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) if (__result == null) { SkillDef val = GetSkillDef(type); if (val != null) { ___m_skills.Add(val); __result = val; } } } private unsafe static bool Patch_Skills_CheatRaiseskill(Skills __instance, string name, float value, Player ___m_player) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) foreach (SkillType key in skills.Keys) { Skill skill = skills[key]; if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase)) { Skill skill2 = __instance.GetSkill(key); skill2.m_level += value; skill2.m_level = Mathf.Clamp(skill2.m_level, 0f, 100f); ((Character)___m_player).Message((MessageType)1, "Skill increased " + Localization.instance.Localize("$skill_" + ((object)(*(SkillType*)(&key))/*cast due to .constrained prefix*/).ToString()) + ": " + (int)skill2.m_level, 0, skill2.m_info.m_icon, false); Console.instance.Print("Skill " + skill.internalSkillName + " = " + skill2.m_level); return false; } } return true; } private static bool Patch_Skills_CheatResetSkill(Skills __instance, string name) { //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_0022: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) foreach (SkillType key in skills.Keys) { Skill skill = skills[key]; if (string.Equals(skill.internalSkillName, name, StringComparison.CurrentCultureIgnoreCase)) { __instance.ResetSkill(key); Console.instance.Print("Skill " + skill.internalSkillName + " reset"); return false; } } return true; } private static void Patch_Skills_OnDeath_Prefix(Skills __instance, ref Dictionary<SkillType, Skill>? __state) { //IL_002e: 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_00a0: Unknown result type (might be due to invalid IL or missing references) if (__state == null) { __state = new Dictionary<SkillType, Skill>(); } foreach (KeyValuePair<SkillType, Skill> skill in skills) { if (__instance.m_skillData.TryGetValue(skill.Key, out var value)) { __state[skill.Key] = value; if (skill.Value.skillLoss > 0) { Skill obj = value; obj.m_level -= value.m_level * (float)skill.Value.SkillLoss / 100f; value.m_accumulator = 0f; } __instance.m_skillData.Remove(skill.Key); } } } private static void Patch_Skills_OnDeath_Finalizer(Skills __instance, ref Dictionary<SkillType, Skill>? __state) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) if (__state == null) { return; } foreach (KeyValuePair<SkillType, Skill> item in __state) { __instance.m_skillData[item.Key] = item.Value; } __state = null; } private static void Patch_Terminal_InitTerminal_Prefix() { InitializedTerminal = Terminal.m_terminalInitialized; } private static void Patch_Terminal_InitTerminal() { if (!InitializedTerminal) { AddSkill(Terminal.commands["raiseskill"]); AddSkill(Terminal.commands["resetskill"]); } static void AddSkill(ConsoleCommand command) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown ConsoleOptionsFetcher fetcher = command.m_tabOptionsFetcher; command.m_tabOptionsFetcher = (ConsoleOptionsFetcher)delegate { List<string> list = fetcher.Invoke(); list.AddRange(skills.Values.Select((Skill skill) => skill.internalSkillName)); return list; }; } } private static SkillDef? GetSkillDef(SkillType skillType) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (!skills.ContainsKey(skillType)) { return null; } Skill skill = skills[skillType]; return skill.skillDef; } private static byte[] ReadEmbeddedFileBytes(string name) { using MemoryStream memoryStream = new MemoryStream(); Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + name).CopyTo(memoryStream); return memoryStream.ToArray(); } private static Texture2D loadTexture(string name) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Expected O, but got Unknown Texture2D val = new Texture2D(0, 0); ImageConversion.LoadImage(val, ReadEmbeddedFileBytes("icons." + name)); return val; } private static Sprite loadSprite(string name, int width, int height) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) return Sprite.Create(loadTexture(name), new Rect(0f, 0f, (float)width, (float)height), Vector2.zero); } private static ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description) { ConfigEntry<T> val = plugin.Config.Bind<T>(group, name, value, description); configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T)) .Invoke(configSync, new object[1] { val }); return val; } private static ConfigEntry<T> config<T>(string group, string name, T value, string description) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())); } } [PublicAPI] internal static class SkillExtensions { public static float GetSkillFactor(this Character character, string name) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return character.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor; } public static float GetSkillFactor(this Skills skills, string name) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return skills.GetSkillFactor(Skill.fromName(name)) * Skill.skillByName[name].SkillEffectFactor; } public static void RaiseSkill(this Character character, string name, float value = 1f) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) character.RaiseSkill(Skill.fromName(name), value); } public static void RaiseSkill(this Skills skill, string name, float value = 1f) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) skill.RaiseSkill(Skill.fromName(name), value); } public static void LowerSkill(this Character character, string name, float factor = 1f) { character.GetSkills().LowerSkill(name, factor); } public static void LowerSkill(this Skills skills, string name, float factor) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (factor > 0f && skills.m_skillData.TryGetValue(Skill.fromName(name), out var value)) { Skill obj = value; obj.m_level -= value.m_level * factor; value.m_accumulator = 0f; } } } } namespace ServerSync { [PublicAPI] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry<T> 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; } } } internal 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] internal sealed class CustomSyncedValue<T> : 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] internal 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<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)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<ZNetPeer> 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<string> CurrentList = new List<string>(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List<string>(adminList.GetList()); List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, 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<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>(); public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>(); } [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 = false; public volatile int versionMatchQueued = -1; public readonly List<ZPackage> Package = new List<ZPackage>(); 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 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<Assembly, BufferingSocket>(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary<Assembly, BufferingSocket> __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<PackageEntry> entries = new List<PackageEntry>(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; 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 = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet<ConfigSync> configSyncs; private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>(); private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>(); private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action<bool>? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet<ConfigSync>(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry<T>(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(0L, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry<T>(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry<T>)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<CustomSyncedValueBase>(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_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: 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<long, string> 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 SortedDictionary<int, byte[]> value)) { value = new SortedDictionary<int, byte[]>(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair<long, string>(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) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); 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<OwnConfigEntryBase, object> 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<CustomSyncedValueBase, object> 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<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary<string, CustomSyncedValueBase> 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; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute<ConfigurationManagerAttributes>(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<bool> 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 fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); 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<bool> 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<object>().GetEnumerator(); } List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != 0) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List<IEnumerator<bool>> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); } } private 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<OwnConfigEntryBase>().SingleOrDefault(); } public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config) { return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault(); } private static T configAttribute<T>(ConfigEntryBase config) { return config.Description.Tags.OfType<T>().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>(); List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>()) { 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<string>) && 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<object> source = new List<object>(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [PublicAPI] [HarmonyPatch] internal class VersionCheck { private static readonly HashSet<VersionCheck> versionChecks; private static readonly Dictionary<string, string> 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<ZRpc> ValidatedClients = new List<ZRpc>(); 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 { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: 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<VersionCheck>(); notProcessedNames = new Dictionary<string, string>(); 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 flag = new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion); bool flag2 = new System.Version(ReceivedCurrentVersion) >= new System.Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". 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) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } 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<ZRpc, ZPackage>? 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; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.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_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: 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<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)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_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: 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_01de: 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_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0229: 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<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> 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<RectTransform>(); 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<RectTransform>(); 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 Microsoft.CodeAnalysis { [CompilerGenerated] [<a96445f2-f391-4bec-a0d9-d109fe62c77d>Embedded] internal sealed class <a96445f2-f391-4bec-a0d9-d109fe62c77d>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [<a96445f2-f391-4bec-a0d9-d109fe62c77d>Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class <145a22ed-9344-4425-972a-832a63fae591>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <145a22ed-9344-4425-972a-832a63fae591>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <145a22ed-9344-4425-972a-832a63fae591>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [<a96445f2-f391-4bec-a0d9-d109fe62c77d>Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class <b0f39518-4c09-4a56-94f5-b8ba4b158972>NullableContextAttribute : Attribute { public readonly byte Flag; public <b0f39518-4c09-4a56-94f5-b8ba4b158972>NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace LocalizationManager { [PublicAPI] [<b0f39518-4c09-4a56-94f5-b8ba4b158972>NullableContext(1)] [<145a22ed-9344-4425-972a-832a63fae591>Nullable(0)] internal class Localizer { private static readonly Dictionary<string, Dictionary<string, Func<string>>> PlaceholderProcessors; private static readonly Dictionary<string, Dictionary<string, string>> loadedTexts; private static readonly ConditionalWeakTable<Localization, string> localizationLanguage; private static readonly List<WeakReference<Localization>> localizationObjects; [<145a22ed-9344-4425-972a-832a63fae591>Nullable(2)] private static BaseUnityPlugin _plugin; private static readonly List<string> fileExtensions; private static Dictionary<string, string> customTexts; private static BaseUnityPlugin plugin { get { //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Expected O, but got Unknown if (_plugin =
plugins/HBK-HBKHEIM/SaveCrossbowState-1.0.4/SaveCrossbowState.dll
Decompiled 5 hours agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("SaveCrossbowState")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Azumatt")] [assembly: AssemblyProduct("SaveCrossbowState")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")] [assembly: AssemblyFileVersion("1.0.4")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.4.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 SaveCrossbowState { [BepInPlugin("Azumatt.SaveCrossbowState", "SaveCrossbowState", "1.0.4")] public class SaveCrossbowStatePlugin : BaseUnityPlugin { internal const string ModName = "SaveCrossbowState"; internal const string ModVersion = "1.0.4"; internal const string Author = "Azumatt"; private const string ModGUID = "Azumatt.SaveCrossbowState"; private readonly Harmony _harmony = new Harmony("Azumatt.SaveCrossbowState"); public static readonly ManualLogSource SaveCrossbowStateLogger = Logger.CreateLogSource("SaveCrossbowState"); public const string CrossbowLoaded = "crossbowLoaded"; public const string CrossbowLoadedChanged = "crossbowLoaded_changed"; public void Awake() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 if ((int)SystemInfo.graphicsDeviceType == 4) { SaveCrossbowStateLogger.LogWarning((object)"This mod is client-side only and is not needed on a dedicated server. Plugin patches will not be applied."); } else { _harmony.PatchAll(Assembly.GetExecutingAssembly()); } } public static bool IsCrossbowItem(ItemData? possibleCrossbow) { //IL_0023: 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) //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_0042: Invalid comparison between Unknown and I4 //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Invalid comparison between Unknown and I4 SkillType? val = possibleCrossbow?.m_shared?.m_skillType; bool flag; if (val.HasValue) { SkillType valueOrDefault = val.GetValueOrDefault(); if ((int)valueOrDefault == 9 || (int)valueOrDefault == 14) { flag = true; goto IL_004f; } } flag = false; goto IL_004f; IL_004f: if (!flag) { return possibleCrossbow?.m_shared?.m_name == "$item_graplinghook"; } return true; } } [HarmonyPatch(typeof(Attack), "OnAttackTrigger")] internal static class ResetLoaded { private static void Prefix(Attack __instance) { ItemData currentWeapon = __instance.m_character.GetCurrentWeapon(); if (((Character)__instance.m_character).IsPlayer() && !((Object)(object)__instance.m_character != (Object)(object)Player.m_localPlayer) && SaveCrossbowStatePlugin.IsCrossbowItem(currentWeapon)) { currentWeapon.m_customData["crossbowLoaded"] = "false"; if (currentWeapon.m_customData.TryGetValue("crossbowLoaded_changed", out var value) && bool.TryParse(value, out var result) && result) { currentWeapon.m_customData.Remove("crossbowLoaded_changed"); currentWeapon.m_shared.m_attack.m_requiresReload = true; } } } } [HarmonyPatch(typeof(Humanoid), "UnequipItem")] internal static class CheckIfCrossbowWasUnequipped { private static void Prefix(Humanoid __instance, ItemData? item, bool triggerEquipEffects = true) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) if (((Character)__instance).IsPlayer() && !((Object)(object)Player.m_localPlayer == (Object)null) && !Player.m_localPlayer.m_isLoading && SaveCrossbowStatePlugin.IsCrossbowItem(item) && ((Humanoid)(Player)__instance).IsWeaponLoaded()) { item.m_customData["crossbowLoaded"] = "true"; if (item.m_shared.m_attack.m_requiresReload) { item.m_customData["crossbowLoaded_changed"] = "true"; item.m_shared.m_attack.m_requiresReload = false; } } } } }
plugins/HBK-HBKHEIM/Unshamed-1.0.8/Unshamed.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.UI; using Unshamed.Guide; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Unshamed")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Azumatt")] [assembly: AssemblyProduct("Unshamed")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("E0E2F92E-557C-4A05-9D89-AA92A0BD75C4")] [assembly: AssemblyFileVersion("1.0.8")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.8.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 Unshamed { internal static class Audit { private const int Raw = 0; private const int Any = 1; private static readonly int FirstProgressKey = 42; private static readonly HashSet<string> LooksLikeCheating = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "nobuildcost", "nocraftcost", "allrecipesunlocked", "allpiecesunlocked", "noworkbench", "dungeonbuild", "teleportall", "passivemobs" }; internal static List<string> Run(PlayerProfile profile) { List<string> list = new List<string>(); PlayerStats val = profile.m_playerStats[0]; list.Add("--- eligibility ---"); list.Add("Can earn achievements: " + Eligibility.CanEarn() + " (vanilla would say " + Eligibility.VanillaCanEarn() + ")"); list.Add(" " + Eligibility.Describe()); string bypassWarning = Eligibility.BypassWarning; if (bypassWarning != null) { list.Add(bypassWarning); } list.Add("Cheats stat: " + (val.m_stats.TryGetValue((PlayerStatType)4, out var value) ? value : 0f)); List<string> list2 = CheatFlags.CheatCommandsUsed(profile).ToList(); list.Add("Cheat commands in history: " + ((list2.Count == 0) ? "none" : string.Join(", ", list2))); list.Add("Commands in history overall: " + val.m_knownCommands.Count + " (vanilla records every command you run, not just cheats)"); Buckets(profile, list); Keys(val, list); return list; } private static void Buckets(PlayerProfile profile, List<string> report) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Invalid comparison between Unknown and I4 //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Expected I4, but got Unknown //IL_00cc: Unknown result type (might be due to invalid IL or missing references) report.Add(""); report.Add("--- stat buckets ---"); foreach (DifficultyRequirement item in Enum.GetValues(typeof(DifficultyRequirement)).Cast<DifficultyRequirement>()) { if ((int)item != 10) { PlayerStats val = profile.m_playerStats[item]; int num = val.m_enemyStats.Sum((Dictionary<string, float> d) => d.Count) + val.m_itemPickupStats.Count + val.m_itemCraftStats.Count + val.m_pickableStats.Count + val.m_foodEatenStats.Count + val.m_piecesPlacedStats.Count; report.Add($"{(int)item,2} {item,-12} {val.m_stats.Count((KeyValuePair<PlayerStatType, float> s) => s.Value > 0f),4} counters, {num,5} named entries"); } } StatSync.Result result = StatSync.Apply(profile, preview: true); report.Add(result.Any ? ("RawStats is ahead of Any by " + result.ToString() + ". 'unshamed retro' copies that forward.") : "Any is level with RawStats, nothing to copy forward."); } private static void Keys(PlayerStats raw, List<string> report) { //IL_00bd: 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_00fc: Invalid comparison between Unknown and I4 List<string> list = new List<string>(); List<string> list2 = new List<string>(); List<string> list3 = new List<string>(); List<string> list4 = new List<string>(); List<string> list5 = new List<string>(); foreach (KeyValuePair<string, float> knownWorldKey in raw.m_knownWorldKeys) { Split(knownWorldKey.Key, out string key, out string value); string item = $"{knownWorldKey.Key} ({TimeSpan.FromSeconds(knownWorldKey.Value):c})"; GlobalKeys result; if (key.Length > 0 && key.All(char.IsDigit)) { list4.Add(item); } else if (!Enum.TryParse<GlobalKeys>(key, ignoreCase: true, out result) || !Enum.IsDefined(typeof(GlobalKeys), result)) { (key.Contains("7656119") ? list5 : list3).Add(item); } else if (!(value == "default") && (int)result < FirstProgressKey) { (LooksLikeCheating.Contains(key) ? list2 : list).Add(item); } } report.Add(""); report.Add("--- world keys (" + raw.m_knownWorldKeys.Count + " entries, and vanilla never clears this) ---"); Section(report, "Most likely to be read as cheating", list2); Section(report, "Other non-default modifiers", list); Section(report, "No vanilla GlobalKeys member matches, so a mod put them there", list3); Section(report, "Entries carrying somebody's SteamID", list5); Section(report, "Bare numbers, which vanilla wrote itself", list4); report.Add(""); report.Add("These are your character's keys. What actually marks a world cheated in 1.0 is the world's own m_startingGlobalKeys, checked by ServerOptionsGUI.WorldContainsCheatedModifiers: anything you cannot set through the World Modifiers menu counts."); } private static void Section(List<string> report, string title, List<string> lines) { report.Add(title + ": " + ((lines.Count == 0) ? "none" : lines.Count.ToString())); foreach (string item in lines.OrderBy((string l) => l)) { report.Add(" " + item); } } internal static void Split(string entry, out string key, out string? value) { int num = entry.IndexOf(' '); if (num < 0) { key = entry; value = null; } else { key = entry.Substring(0, num); value = entry.Substring(num + 1); } } } [HarmonyPatch(typeof(Achievements), "CanGetAchievements")] internal static class Achievements_CanGetAchievements_Patch { private static void Postfix(ref bool __result) { if (!__result && UnshamedPlugin.On(UnshamedPlugin.IgnoreCheatFlags)) { __result = true; } } } internal static class Eligibility { internal static bool VanillaBypass => PlayerProfile.s_bypassCheatChecks; internal static string? BypassWarning { get { if (!VanillaBypass) { return null; } return "<color=orange>Vanilla's cheat bypass is ON for this character. Anything spawned while it's on is NOT flagged as cheated. Unshamed doesn't need it, 'yesiuseddevcommandsbutiwantmyachievementsanyway 0' turns it off.</color>"; } } internal static bool CanEarn() { return Achievements.CanGetAchievements(false); } internal static bool VanillaCanEarn() { if (Achievements.IsCheatedAtAll()) { return VanillaBypass; } return true; } private static bool WorldCheated() { try { return Achievements.IsWorldCheated(); } catch (Exception) { return false; } } internal static string Describe() { if (!Object.op_Implicit((Object)(object)Game.instance)) { return "no game instance yet"; } bool usedCheats = Game.instance.GetPlayerProfile().m_usedCheats; bool flag = Object.op_Implicit((Object)(object)Player.m_localPlayer) && ((Humanoid)Player.m_localPlayer).GetInventory().AnyCheatedItem(); return $"m_usedCheats {usedCheats}, cheated world {WorldCheated()}, cheated items {flag}, Game.isModded {Game.isModded}, vanilla bypass {VanillaBypass}" + (UnshamedPlugin.On(UnshamedPlugin.IgnoreCheatFlags) ? " (recorded, ignored, never cleared)" : ""); } } internal sealed class Evidence { private readonly struct Kind { internal readonly string? Piece; internal readonly int Slots; internal readonly bool Single; internal readonly bool Items; internal Kind(string? piece, int slots, bool single, bool items) { Piece = piece; Slots = slots; Single = single; Items = items; } } internal readonly Dictionary<string, float> Crafted = new Dictionary<string, float>(StringComparer.Ordinal); internal readonly Dictionary<string, float> PickedUp = new Dictionary<string, float>(StringComparer.Ordinal); internal readonly Dictionary<string, float> Placed = new Dictionary<string, float>(StringComparer.Ordinal); internal readonly Dictionary<string, float> Eaten = new Dictionary<string, float>(StringComparer.Ordinal); private const float MaxAge = 60f; private const float SliceSeconds = 0.002f; private static readonly int[] SlotKeys; private static Evidence? _cached; private static Game? _cachedFor; private static float _cachedAt; private static Evidence? _building; private static Game? _buildingFor; private static long _buildingMe; private static List<ZDO>? _pending; private static int _cursor; private static readonly Dictionary<int, Kind> Kinds; internal int Count => Crafted.Count + PickedUp.Count + Placed.Count + Eaten.Count; static Evidence() { SlotKeys = new int[16]; Kinds = new Dictionary<int, Kind>(); for (int i = 0; i < SlotKeys.Length; i++) { SlotKeys[i] = StringExtensionMethods.GetStableHashCode(i + "_itemData"); } } internal static Evidence For(PlayerProfile profile) { if (_cached != null && (Object)(object)_cachedFor == (Object)(object)Game.instance) { if (Time.realtimeSinceStartup - _cachedAt >= 60f) { Begin(profile); } return _cached; } Begin(profile); Step(float.MaxValue); return _cached ?? new Evidence(); } internal static bool Ready(PlayerProfile profile) { if (_cached != null && (Object)(object)_cachedFor == (Object)(object)Game.instance) { return true; } Begin(profile); return false; } internal static void Tick() { if (_building != null) { Step(0.002f); } } private static void Begin(PlayerProfile profile) { if (_building != null && (Object)(object)_buildingFor == (Object)(object)Game.instance) { return; } _building = new Evidence(); _buildingFor = Game.instance; _buildingMe = profile.GetPlayerID(); _cursor = 0; _pending = null; Kinds.Clear(); if (_buildingMe != 0L) { _building.FromPlayer(_buildingMe); if (ZDOMan.instance != null && Object.op_Implicit((Object)(object)ZNetScene.instance) && Object.op_Implicit((Object)(object)ObjectDB.instance)) { _pending = new List<ZDO>(ZDOMan.instance.m_objectsByID.Values); } } } private static void Step(float budget) { if (_building == null) { return; } if ((Object)(object)_buildingFor != (Object)(object)Game.instance || !Object.op_Implicit((Object)(object)ZNetScene.instance) || !Object.op_Implicit((Object)(object)ObjectDB.instance)) { _building = null; _pending = null; return; } if (_pending != null) { float num = Time.realtimeSinceStartup + budget; while (_cursor < _pending.Count) { _building.Visit(_pending[_cursor++], _buildingMe); if ((_cursor & 0xFF) == 0 && Time.realtimeSinceStartup > num) { return; } } } _cached = _building; _cachedFor = _buildingFor; _cachedAt = Time.realtimeSinceStartup; _building = null; _pending = null; } private void FromPlayer(long me) { Player localPlayer = Player.m_localPlayer; if (!Object.op_Implicit((Object)(object)localPlayer)) { return; } foreach (string trophy in localPlayer.m_trophies) { object obj; if (!Object.op_Implicit((Object)(object)ObjectDB.instance)) { obj = null; } else { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(trophy); obj = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null); } ItemDrop val = (ItemDrop)obj; if (Object.op_Implicit((Object)(object)val)) { Add(PickedUp, val.m_itemData.m_shared.m_name, 1f); } } foreach (ItemData allItem in ((Humanoid)localPlayer).GetInventory().GetAllItems()) { CraftedBy(allItem, me); } foreach (Food food in localPlayer.m_foods) { if (food.m_item != null) { Add(Eaten, food.m_item.m_shared.m_name, 1f); } } } private void Visit(ZDO zdo, long me) { try { Kind kind = KindOf(zdo.GetPrefab()); if (kind.Piece != null && zdo.GetLong(ZDOVars.s_creator, 0L) == me) { Add(Placed, kind.Piece, 1f); } if (kind.Single) { ReadOne(zdo, ZDOVars.s_itemData, me); } for (int i = 0; i < kind.Slots; i++) { ReadOne(zdo, (i < SlotKeys.Length) ? SlotKeys[i] : StringExtensionMethods.GetStableHashCode(i + "_itemData"), me); } if (kind.Items) { byte[] byteArray = zdo.GetByteArray(ZDOVars.s_items, (byte[])null); if (byteArray != null && byteArray.Length != 0) { ReadItems(byteArray, me); } } } catch (Exception) { } } private static Kind KindOf(int hash) { if (Kinds.TryGetValue(hash, out var value)) { return value; } GameObject prefab = ZNetScene.instance.GetPrefab(hash); if (!Object.op_Implicit((Object)(object)prefab)) { value = new Kind(null, 0, single: true, items: true); } else { Piece component = prefab.GetComponent<Piece>(); ArmorStand componentInChildren = prefab.GetComponentInChildren<ArmorStand>(true); bool single = Object.op_Implicit((Object)(object)prefab.GetComponentInChildren<ItemDrop>(true)) || Object.op_Implicit((Object)(object)prefab.GetComponentInChildren<ItemStand>(true)); bool items = Object.op_Implicit((Object)(object)prefab.GetComponentInChildren<Container>(true)); value = new Kind(Object.op_Implicit((Object)(object)component) ? component.m_name : null, Object.op_Implicit((Object)(object)componentInChildren) ? componentInChildren.m_slots.Count : 0, single, items); } Kinds[hash] = value; return value; } private void ReadItems(byte[] bytes, long me) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_0072: Unknown result type (might be due to invalid IL or missing references) ZPackage val = new ZPackage(bytes); Item val2 = (Item)val.ReadInt(); if ((int)val2 < 108) { Inventory val3 = new Inventory("", (Sprite)null, 8, 4); val3.Load(new ZPackage(bytes)); { foreach (ItemData allItem in val3.GetAllItems()) { CraftedBy(allItem, me); } return; } } int num = val.ReadUShort(); for (int i = 0; i < num; i++) { var (num2, val4) = ItemData.Load(val, val2); if (num2 != 0 && val4.m_crafterID == me) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(num2); ItemDrop val5 = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null); if (Object.op_Implicit((Object)(object)val5)) { Add(Crafted, val5.m_itemData.m_shared.m_name, Math.Max(1, val4.m_stack)); } } } } private void ReadOne(ZDO zdo, int key, long me) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown byte[] byteArray = zdo.GetByteArray(key, (byte[])null); if (byteArray == null || byteArray.Length <= 2) { return; } ZPackage val = new ZPackage(byteArray); Item val2 = (Item)val.ReadByte(); ItemData val3 = new ItemData(); int num = ItemData.Load(val, val3, val2); if (val3.m_crafterID == me) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab((num != 0) ? num : zdo.GetPrefab()); ItemDrop val4 = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null); if (Object.op_Implicit((Object)(object)val4)) { Add(Crafted, val4.m_itemData.m_shared.m_name, Math.Max(1, val3.m_stack)); } } } private void CraftedBy(ItemData item, long me) { if (item.m_crafterID == me) { Add(Crafted, item.m_shared.m_name, Math.Max(1, item.m_stack)); } } private static void Add(Dictionary<string, float> to, string name, float amount) { if (!string.IsNullOrEmpty(name)) { to.TryGetValue(name, out var value); to[name] = value + amount; } } } internal static class StatSync { internal readonly struct Result { internal readonly int Stats; internal readonly int Entries; internal readonly int Found; internal bool Any => Stats + Entries + Found > 0; internal Result(int stats, int entries, int found) { Stats = stats; Entries = entries; Found = found; } public override string ToString() { return $"{Stats} counters, {Entries} named entries and {Found} found in your world and gear"; } } internal sealed class Wanted { internal readonly HashSet<PlayerStatType> Stats = new HashSet<PlayerStatType>(); internal readonly HashSet<string> Names = new HashSet<string>(StringComparer.Ordinal); internal Wanted(IEnumerable<Achievement> achievements) { //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) //IL_0050: 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_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) foreach (Achievement achievement in achievements) { foreach (PlayerStatRequirement item in achievement.m_statTrigger) { Stats.Add(item.m_stat); } foreach (EnemyStatRequirement enemyStatsTrigger in achievement.m_enemyStatsTriggers) { Names.Add(enemyStatsTrigger.m_stat); } Add(achievement.m_itemCraftTriggers); Add(achievement.m_itemPickupTriggers); Add(achievement.m_pickableTriggers); Add(achievement.m_foodEatenTriggers); Add(achievement.m_piecePlacedTriggers); Add(achievement.m_knownCommandsTriggers); Add(achievement.m_knownWorldTriggers); Add(achievement.m_knownWorldKeysTriggers); foreach (Achievement otherAchievementTrigger in achievement.m_otherAchievementTriggers) { if ((Object)(object)otherAchievementTrigger != (Object)null) { Merge(otherAchievementTrigger); } } } } private void Merge(Achievement a) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) foreach (PlayerStatRequirement item in a.m_statTrigger) { Stats.Add(item.m_stat); } foreach (EnemyStatRequirement enemyStatsTrigger in a.m_enemyStatsTriggers) { Names.Add(enemyStatsTrigger.m_stat); } Add(a.m_itemCraftTriggers); Add(a.m_itemPickupTriggers); Add(a.m_pickableTriggers); Add(a.m_foodEatenTriggers); Add(a.m_piecePlacedTriggers); Add(a.m_knownCommandsTriggers); Add(a.m_knownWorldTriggers); Add(a.m_knownWorldKeysTriggers); } private void Add(List<DictStatRequirement> triggers) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) foreach (DictStatRequirement trigger in triggers) { Names.Add(trigger.m_stat); } } } private sealed class Snapshot { private readonly Dictionary<PlayerStatType, float> _stats; private readonly Dictionary<string, float>[] _enemy; private readonly Dictionary<string, float>[] _named; internal Snapshot(PlayerStats from) { _stats = new Dictionary<PlayerStatType, float>(from.m_stats); _enemy = from.m_enemyStats.Select((Dictionary<string, float> d) => new Dictionary<string, float>(d)).ToArray(); _named = (from d in Named(@from) select new Dictionary<string, float>(d)).ToArray(); } internal void RestoreTo(PlayerStats to) { Replace(to.m_stats, _stats); for (int i = 0; i < _enemy.Length; i++) { Replace(to.m_enemyStats[i], _enemy[i]); } Dictionary<string, float>[] array = Named(to); for (int j = 0; j < array.Length; j++) { Replace(array[j], _named[j]); } } private static Dictionary<string, float>[] Named(PlayerStats s) { return new Dictionary<string, float>[8] { s.m_itemPickupStats, s.m_itemCraftStats, s.m_pickableStats, s.m_foodEatenStats, s.m_piecesPlacedStats, s.m_knownWorlds, s.m_knownWorldKeys, s.m_knownCommands }; } private static void Replace<TKey>(Dictionary<TKey, float> live, Dictionary<TKey, float> saved) { live.Clear(); foreach (KeyValuePair<TKey, float> item in saved) { live[item.Key] = item.Value; } } } private const int Raw = 0; private const int Any = 1; internal static Result Apply(PlayerProfile profile, bool preview, Wanted? only = null) { //IL_004d: 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) //IL_0071: Unknown result type (might be due to invalid IL or missing references) int num = 0; int num2 = 0; PlayerStats val = profile.m_playerStats[0]; PlayerStats val2 = profile.m_playerStats[1]; foreach (KeyValuePair<PlayerStatType, float> stat in val.m_stats) { if ((only == null || only.Stats.Contains(stat.Key)) && (!val2.m_stats.TryGetValue(stat.Key, out var value) || !(value >= stat.Value))) { if (!preview) { val2.m_stats[stat.Key] = stat.Value; } num++; } } for (int i = 0; i < val.m_enemyStats.Length; i++) { num2 += Merge(val.m_enemyStats[i], val2.m_enemyStats[i], preview, only); } num2 += Merge(val.m_itemPickupStats, val2.m_itemPickupStats, preview, only); num2 += Merge(val.m_itemCraftStats, val2.m_itemCraftStats, preview, only); num2 += Merge(val.m_pickableStats, val2.m_pickableStats, preview, only); num2 += Merge(val.m_foodEatenStats, val2.m_foodEatenStats, preview, only); num2 += Merge(val.m_piecesPlacedStats, val2.m_piecesPlacedStats, preview, only); num2 += Merge(val.m_knownWorlds, val2.m_knownWorlds, preview, only); num2 += Merge(val.m_knownWorldKeys, val2.m_knownWorldKeys, preview, only); num2 += Merge(val.m_knownCommands, val2.m_knownCommands, preview, only); Evidence evidence = Evidence.For(profile); int found = Fill(evidence.Crafted, val.m_itemCraftStats, val2.m_itemCraftStats, preview, only) + Fill(evidence.PickedUp, val.m_itemPickupStats, val2.m_itemPickupStats, preview, only) + Fill(evidence.Placed, val.m_piecesPlacedStats, val2.m_piecesPlacedStats, preview, only) + Fill(evidence.Eaten, val.m_foodEatenStats, val2.m_foodEatenStats, preview, only); return new Result(num, num2, found); } private static int Fill(Dictionary<string, float> from, Dictionary<string, float> raw, Dictionary<string, float> to, bool preview, Wanted? only) { int num = 0; foreach (KeyValuePair<string, float> item in from) { if ((only == null || only.Names.Contains(item.Key)) && !raw.ContainsKey(item.Key) && !to.ContainsKey(item.Key)) { if (!preview) { to[item.Key] = item.Value; } num++; } } return num; } private static int Merge(Dictionary<string, float> from, Dictionary<string, float> to, bool preview, Wanted? only) { int num = 0; foreach (KeyValuePair<string, float> item in from) { if ((only == null || only.Names.Contains(item.Key)) && (!to.TryGetValue(item.Key, out var value) || !(value >= item.Value))) { if (!preview) { to[item.Key] = item.Value; } num++; } } return num; } internal static List<Achievement> Preview(PlayerProfile profile) { List<Achievement> list = new List<Achievement>(); PlayerStats val = profile.m_playerStats[1]; Snapshot snapshot = new Snapshot(val); try { Achievements.MarkAchievementDifficultyDirty(); Apply(profile, preview: false); foreach (Achievement item in All()) { if (!item.m_unlocked && Earned(item)) { item.m_unlocked = false; list.Add(item); } } } finally { snapshot.RestoreTo(val); foreach (Achievement item2 in list) { item2.m_unlocked = false; } Achievements.MarkAchievementDifficultyDirty(); } return list; } internal static List<Achievement> Sweep() { List<Achievement> list = new List<Achievement>(); if (!Object.op_Implicit((Object)(object)Achievements.m_instance)) { return list; } Achievements.MarkAchievementDifficultyDirty(); foreach (Achievement item in All()) { if (!item.m_unlocked && Earned(item)) { Achievements.AchievementEvent(item, false, UnshamedPlugin.On(UnshamedPlugin.ShowPopups)); list.Add(item); } } return list; } private static bool Earned(Achievement a) { if (a.CheckUnlocked()) { return true; } if (!a.m_lenientBuildAchievement) { return false; } var (num, num2) = Requirements.Lenient(a); if (num <= num2) { return false; } a.m_unlocked = true; return true; } internal static IEnumerable<Achievement> All() { if (!Object.op_Implicit((Object)(object)Achievements.m_instance)) { yield break; } foreach (AchievementList achievementList in Achievements.m_instance.m_achievementLists) { if ((Object)(object)achievementList == (Object)null) { continue; } foreach (Achievement achievement in achievementList.m_achievements) { if ((Object)(object)achievement != (Object)null) { yield return achievement; } } } } internal static string Name(Achievement a) { string text = Localization.instance.Localize(a.m_name); if (!string.IsNullOrEmpty(text)) { return text; } return a.m_id; } internal static Achievement? Find(string id) { return All().FirstOrDefault((Func<Achievement, bool>)((Achievement a) => string.Equals(a.m_id, id, StringComparison.OrdinalIgnoreCase))); } } internal static class AutoRetro { private static bool _done; private static bool _announced; private static float _next; private static float _nextAnnounce; private static float _tellAt; private static string? _tell; internal static void Tick() { Announce(); Tell(); if (_done || !UnshamedPlugin.On(UnshamedPlugin.Retroactive) || Time.realtimeSinceStartup < _next) { return; } _next = Time.realtimeSinceStartup + 3f; if (!Object.op_Implicit((Object)(object)Game.instance) || !Object.op_Implicit((Object)(object)Player.m_localPlayer) || !Object.op_Implicit((Object)(object)Achievements.m_instance)) { return; } PlayerProfile playerProfile = Game.instance.GetPlayerProfile(); if (playerProfile == null || !Evidence.Ready(playerProfile)) { return; } if (!Eligibility.CanEarn()) { _done = true; UnshamedPlugin.UnshamedLogger.LogInfo((object)("Retroactive skipped, this character still counts as cheated: " + Eligibility.Describe())); return; } StatSync.Result result = StatSync.Apply(playerProfile, preview: true); _done = true; if (!result.Any) { return; } StatSync.Apply(playerProfile, preview: false); List<Achievement> list = StatSync.Sweep(); playerProfile.Save(); UnshamedPlugin.UnshamedLogger.LogInfo((object)$"Retroactive copied {result}, vanilla unlocked {list.Count}"); foreach (Achievement item in list) { UnshamedPlugin.UnshamedLogger.LogInfo((object)(" " + item.m_id + " - " + StatSync.Name(item))); } if (list.Count > 0) { Later($"Unshamed gave back {list.Count} achievement(s) you'd already earned."); } } private static void Later(string text) { _tell = text; _tellAt = Time.realtimeSinceStartup + 12f; } private static void Tell() { if (_tell != null && !(Time.realtimeSinceStartup < _tellAt) && Object.op_Implicit((Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)MessageHud.instance)) { MessageHud.instance.ShowMessage((MessageType)2, _tell, 0, (Sprite)null, false, true); _tell = null; } } private static void Announce() { if (_announced || Time.realtimeSinceStartup < _nextAnnounce) { return; } _nextAnnounce = Time.realtimeSinceStartup + 0.5f; if (!Object.op_Implicit((Object)(object)Game.instance) || !Object.op_Implicit((Object)(object)Player.m_localPlayer) || !Object.op_Implicit((Object)(object)Achievements.m_instance)) { return; } PlayerProfile playerProfile = Game.instance.GetPlayerProfile(); if (!Evidence.Ready(playerProfile)) { return; } _announced = true; int num = StatSync.All().Count((Achievement a) => a.m_unlocked); int num2 = StatSync.All().Count(); UnshamedPlugin.UnshamedLogger.LogInfo((object)$"Eligible for achievements: {Eligibility.CanEarn()} ({Eligibility.Describe()})"); if (Eligibility.VanillaBypass) { UnshamedPlugin.UnshamedLogger.LogWarning((object)"Vanilla's cheat bypass is on for this character. Items spawned now won't be flagged."); } UnshamedPlugin.UnshamedLogger.LogInfo((object)$"Achievements {num}/{num2} unlocked."); if (!Eligibility.CanEarn()) { return; } List<Achievement> list = StatSync.Preview(playerProfile); if (list.Count == 0) { UnshamedPlugin.UnshamedLogger.LogInfo((object)"Nothing waiting, this character has already been credited with what it earned."); return; } UnshamedPlugin.UnshamedLogger.LogInfo((object)$"{list.Count} achievement(s) you already earned are waiting. Run 'unshamed retro' to see them, or 'unshamed retro apply' to take them."); foreach (Achievement item in list) { UnshamedPlugin.UnshamedLogger.LogInfo((object)(" " + item.m_id + " - " + StatSync.Name(item))); } if (!UnshamedPlugin.On(UnshamedPlugin.Retroactive)) { Later($"{list.Count} achievement(s) you already earned are waiting.\nPress F5 and type 'unshamed retro' to see them."); } } } internal static class CheatFlags { internal static IEnumerable<string> CheatCommandsUsed(PlayerProfile profile) { ConsoleCommand value; return profile.m_playerStats[0].m_knownCommands.Keys.Where((string k) => Terminal.commands.TryGetValue(k.ToLower(), out value) && value.IsCheat); } } [HarmonyPatch(typeof(Terminal), "InitTerminal")] internal static class Commands { [CompilerGenerated] private static class <>O { public static ConsoleEvent <0>__Run; public static Func<PlayerProfile, List<string>> <1>__Run; } [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static ConsoleOptionsFetcher <>9__1_0; public static Func<Achievement, bool> <>9__8_0; public static Func<Achievement, bool> <>9__9_0; public static Func<string, bool> <>9__12_0; internal List<string> <Postfix>b__1_0() { return new List<string> { "status", "audit", "list", "retro", "guide", "recon" }; } internal bool <Status>b__8_0(Achievement a) { return a.m_unlocked; } internal bool <List>b__9_0(Achievement a) { return a.m_unlocked; } internal bool <Pick>b__12_0(string t) { return t.Length > 0; } } private static bool _registered; private static PlayerProfile? Profile { get { if (!Object.op_Implicit((Object)(object)Game.instance)) { return null; } return Game.instance.GetPlayerProfile(); } } private static void Postfix() { //IL_0028: 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) //IL_0033: Expected O, but got Unknown //IL_005b: 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_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown if (_registered) { return; } _registered = true; object obj = <>O.<0>__Run; if (obj == null) { ConsoleEvent val = Run; <>O.<0>__Run = val; obj = (object)val; } object obj2 = <>c.<>9__1_0; if (obj2 == null) { ConsoleOptionsFetcher val2 = () => new List<string> { "status", "audit", "list", "retro", "guide", "recon" }; <>c.<>9__1_0 = val2; obj2 = (object)val2; } new ConsoleCommand("unshamed", "status | audit | list | retro [apply [n|id ...]] | guide [id] | recon", (ConsoleEvent)obj, false, false, false, false, false, false, (ConsoleOptionsFetcher)obj2, false, false, false); } private static void Out(ConsoleEventArgs args, string line) { args.Context.AddString(line); UnshamedPlugin.UnshamedLogger.LogInfo((object)Strip(line)); } private static string Strip(string line) { return Regex.Replace(line, "<[^>]+>", ""); } private static void Run(ConsoleEventArgs args) { string text = ((args.Length > 1) ? args[1].ToLower() : "status"); switch (text) { case "status": Status(args); break; case "audit": Report(args, Audit.Run); break; case "list": List(args); break; case "retro": Retroactive(args); break; case "guide": GuideCommand(args); break; case "recon": Out(args, "Wrote " + Recon.Run()); break; default: Out(args, "Don't know '" + text + "'. Try status, audit, list, retro, guide or recon."); break; } } private static void Report(ConsoleEventArgs args, Func<PlayerProfile, List<string>> build) { PlayerProfile profile = Profile; if (profile == null) { Out(args, "No profile loaded yet."); return; } foreach (string item in build(profile)) { Out(args, item); } } private static void Status(ConsoleEventArgs args) { PlayerProfile profile = Profile; if (profile == null) { Out(args, "No profile loaded yet."); return; } Out(args, "Eligible for achievements: " + Eligibility.CanEarn()); Out(args, " " + Eligibility.Describe()); string bypassWarning = Eligibility.BypassWarning; if (bypassWarning != null) { Out(args, bypassWarning); } List<Achievement> list = StatSync.All().ToList(); Out(args, (list.Count == 0) ? "Achievements: none loaded yet, get into a world first." : ("Achievements: " + list.Count((Achievement a) => a.m_unlocked) + " / " + list.Count + " unlocked")); StatSync.Result result = StatSync.Apply(profile, preview: true); Out(args, result.Any ? ("Retroactive: " + result.ToString() + " waiting, run 'unshamed retro'") : "Retroactive: nothing to copy forward"); } private static void List(ConsoleEventArgs args) { //IL_00ae: Unknown result type (might be due to invalid IL or missing references) List<Achievement> list = StatSync.All().ToList(); if (list.Count == 0) { Out(args, "No achievements loaded. Get into a world first."); return; } string filter = ((args.Length > 2) ? args[2].ToLower() : ""); foreach (Achievement item in list.Where((Achievement a) => filter.Length == 0 || a.m_id.ToLower().Contains(filter))) { Out(args, string.Format("{0} {1} ({2}) - {3}", item.m_unlocked ? "<color=green>[x]</color>" : "[ ]", item.m_id, item.m_difficultyRequirement, StatSync.Name(item))); } Out(args, list.Count((Achievement a) => a.m_unlocked) + " / " + list.Count + " unlocked"); } private static void GuideCommand(ConsoleEventArgs args) { if (Profile == null || !Object.op_Implicit((Object)(object)Achievements.m_instance)) { Out(args, "Achievements aren't loaded yet. Get into a world first."); return; } if (args.Length < 3) { Out(args, "Wrote " + GuideDump.Write()); return; } Achievement val = StatSync.Find(args[2]); if ((Object)(object)val == (Object)null) { Out(args, "Don't know '" + args[2] + "'. 'unshamed list' has the ids."); return; } Out(args, "<color=yellow>" + StatSync.Name(val) + "</color> (" + val.m_id + ")"); string[] array = AchievementsPanel.Compose(val, rich: false).Split(new char[1] { '\n' }); foreach (string text in array) { Out(args, text.TrimEnd(new char[1] { '\r' })); } foreach (Requirement item in Requirements.Sorted(val)) { Out(args, " " + (item.Met ? "<color=green>[x]</color>" : "[ ]") + " " + item.Label + " (" + item.Progress + ")"); } } private static void Retroactive(ConsoleEventArgs args) { PlayerProfile profile = Profile; if (profile == null) { Out(args, "No profile loaded yet."); return; } if (!Object.op_Implicit((Object)(object)Achievements.m_instance)) { Out(args, "Achievements aren't loaded yet. Get into a world first."); return; } if (!Eligibility.CanEarn()) { Out(args, "<color=orange>This character still counts as cheated, so vanilla would refuse the unlocks.</color>"); Out(args, " " + Eligibility.Describe()); return; } List<Achievement> list = StatSync.Preview(profile); if (list.Count == 0) { StatSync.Result result = StatSync.Apply(profile, preview: true); Out(args, result.Any ? ("Nothing new would unlock, though there is still " + result.ToString() + " to copy forward.") : "Nothing to copy forward and nothing new to unlock."); return; } if (args.Length <= 2 || !(args[2].ToLower() == "apply")) { Out(args, list.Count + " achievement(s) your character already earned:"); for (int i = 0; i < list.Count; i++) { Out(args, $" <color=yellow>{i + 1,2}</color> {list[i].m_id,-28} {StatSync.Name(list[i])}"); } Out(args, "'unshamed retro apply' takes all of them."); Out(args, "'unshamed retro apply 1 3 4' or 'unshamed retro apply <id>' takes only those."); return; } List<string> unknown; List<Achievement> list2 = Pick(args, list, out unknown); foreach (string item in unknown) { Out(args, "<color=orange>Don't know '" + item + "', skipping it.</color>"); } if (list2.Count == 0) { Out(args, "Nothing selected, nothing done."); return; } StatSync.Wanted only = new StatSync.Wanted(list2); StatSync.Result result2 = StatSync.Apply(profile, preview: false, only); List<Achievement> list3 = StatSync.Sweep(); profile.Save(); Out(args, "Copied " + result2.ToString() + "."); Out(args, "Vanilla unlocked " + list3.Count + ":"); foreach (Achievement item2 in list3) { Out(args, " " + item2.m_id + " - " + StatSync.Name(item2)); } int num = list.Count - list3.Count; if (num > 0) { Out(args, num + " left on the table, run 'unshamed retro' again to see them."); } } private static List<Achievement> Pick(ConsoleEventArgs args, List<Achievement> would, out List<string> unknown) { unknown = new List<string>(); List<string> list = (from t in args.Args.Skip(3) where t.Length > 0 select t).ToList(); if (list.Count == 0) { return would; } List<Achievement> list2 = new List<Achievement>(); foreach (string token in list) { if (int.TryParse(token, out var result)) { if (result >= 1 && result <= would.Count) { list2.Add(would[result - 1]); } else { unknown.Add(token); } continue; } Achievement val = ((IEnumerable<Achievement>)would).FirstOrDefault((Func<Achievement, bool>)((Achievement a) => string.Equals(a.m_id, token, StringComparison.OrdinalIgnoreCase))); if ((Object)(object)val != (Object)null) { list2.Add(val); } else { unknown.Add(token); } } return list2.Distinct().ToList(); } } internal static class Messaging { [HarmonyPatch(typeof(Localization), "SetupLanguage")] private static class SetupLanguage_Patch { private static void Postfix() { Vanilla.Clear(); Refresh(); } } private static readonly Dictionary<string, string> Rewrites = new Dictionary<string, string> { ["achievements_confirm_cheat"] = "That command is a cheat, please enter 'confirmcheats' in the console to use cheats. <color=orange>Unshamed keeps your achievements working. Vanilla will still mark this character and this world as cheated.</color>", ["achievements_permanently_cheated_character"] = "Vanilla has this character marked as cheated. Unshamed ignores that, so achievements still count.", ["achievements_permanently_cheated_world"] = "Vanilla has this world marked as cheated. Unshamed ignores that, so achievements still count.", ["achievements_temporarily_cheated"] = "You are carrying a cheated item. Unshamed ignores that, so achievements still count.", ["achievements_picked_up_cheated_item"] = "Picked up a cheated item. Achievements still count.", ["achievements_dropped_cheated_item"] = "No more cheated items in your inventory." }; private static readonly Dictionary<string, string> Vanilla = new Dictionary<string, string>(); internal static void Refresh() { Localization instance = Localization.m_instance; if (instance == null) { return; } bool flag = UnshamedPlugin.On(UnshamedPlugin.IgnoreCheatFlags); foreach (KeyValuePair<string, string> rewrite in Rewrites) { if (instance.m_translations.TryGetValue(rewrite.Key, out var value)) { if (!Vanilla.ContainsKey(rewrite.Key)) { Vanilla[rewrite.Key] = value; } instance.m_translations[rewrite.Key] = (flag ? rewrite.Value : Vanilla[rewrite.Key]); } } instance.m_cache.EvictAll(); } } [HarmonyPatch(typeof(Game), "Awake")] internal static class Game_Awake_Patch { private static void Prefix() { Game.isModded = true; } } [BepInPlugin("Azumatt.Unshamed", "Unshamed", "1.0.8")] public class UnshamedPlugin : BaseUnityPlugin { public enum Toggle { On = 1, Off = 0 } private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [UsedImplicitly] public string? Category; [UsedImplicitly] public Action<ConfigEntryBase>? CustomDrawer; } internal const string ModName = "Unshamed"; internal const string ModVersion = "1.0.8"; internal const string Author = "Azumatt"; private const string ModGUID = "Azumatt.Unshamed"; private static string ConfigFileName = "Azumatt.Unshamed.cfg"; private static string ConfigFileFullPath; private readonly Harmony _harmony = new Harmony("Azumatt.Unshamed"); public static readonly ManualLogSource UnshamedLogger; internal static UnshamedPlugin Instance; internal static ConfigEntry<Toggle> Enabled; internal static ConfigEntry<Toggle> IgnoreCheatFlags; internal static ConfigEntry<Toggle> ShowPopups; internal static ConfigEntry<string> ForceTrue; internal static ConfigEntry<string> ForceFalse; internal static ConfigEntry<Toggle> Retroactive; internal static ConfigEntry<Toggle> RevealRequirements; internal static ConfigEntry<Toggle> GuidePanel; public void Awake() { Instance = this; bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; Enabled = config("1 - General", "Enabled", Toggle.On, "Master switch. Off means the mod touches nothing."); IgnoreCheatFlags = config("1 - General", "Ignore Cheat Flags", Toggle.On, "The fix. Achievements.CanGetAchievements is forced true, so none of the four cheat checks can stop you earning: Game.isModded, m_usedCheats, cheated items, cheated worlds. Nothing gets cleared. Vanilla still records all four, spawned items still carry m_cheated onto the server, and the warnings that used to say achievements were disabled get reworded instead of hidden. Turn this off and you are back to vanilla, disqualified for having BepInEx."); ShowPopups = config("1 - General", "Show Popups", Toggle.Off, "Show the vanilla unlock popup for each achievement the retroactive pass grants. Off because a big backlog means a lot of popups at once."); ForceTrue = config("2 - Overrides", "Force True Methods", "", "Comma separated Type::Method whose bool return gets forced true. A compatibility hatch for when a game patch moves something and the mod stops working."); ForceFalse = config("2 - Overrides", "Force False Methods", "", "Same thing the other way, bool return forced false."); Retroactive = config("3 - Retroactive", "Enable Retroactive", Toggle.Off, "Automatically grant EVERY achievement your character already earned, once, next time you load into a world. Off by default, and you do not need it: 'unshamed retro' in the console previews the list and lets you pick individual ones whether this is on or off. Turn this on only if you want the lot without looking."); RevealRequirements = config("4 - Guide", "Reveal Requirements", Toggle.Off, "The achievements panel stops hiding things. Secret achievements show, every achievement opens its details, rows you haven't finished show their real name and numbers instead of ??? / ???, and unfinished ones sort to the top. Spoilers, obviously."); GuidePanel = config("4 - Guide", "Guide Panel", Toggle.Off, "Show a panel next to the achievement details explaining in plain English what the achievement actually checks, the difficulty it needs and how far along you are."); Enabled.SettingChanged += delegate { Messaging.Refresh(); }; IgnoreCheatFlags.SettingChanged += delegate { Messaging.Refresh(); }; Assembly executingAssembly = Assembly.GetExecutingAssembly(); _harmony.PatchAll(executingAssembly); ReturnOverrides.Apply(_harmony, ForceTrue.Value, ForceFalse.Value); Messaging.Refresh(); SetupWatcher(); if (saveOnConfigSet) { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; ((BaseUnityPlugin)this).Config.Save(); } UnshamedLogger.LogInfo((object)"Unshamed 1.0.8 loaded. Achievements ignore the cheat flags, nothing clears them."); } private void Update() { Evidence.Tick(); AutoRetro.Tick(); } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); } private void SetupWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private void ReadConfigValues(object sender, FileSystemEventArgs e) { if (!File.Exists(ConfigFileFullPath)) { return; } try { UnshamedLogger.LogDebug((object)"ReadConfigValues called"); ((BaseUnityPlugin)this).Config.Reload(); } catch { UnshamedLogger.LogError((object)("There was an issue loading your " + ConfigFileName)); UnshamedLogger.LogError((object)"Please check your config entries for spelling and format!"); } } internal static bool On(ConfigEntry<Toggle> entry) { if (Enabled.Value == Toggle.On) { return entry.Value == Toggle.On; } return false; } private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description) { return ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description); } private ConfigEntry<T> config<T>(string group, string name, T value, string description) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())); } static UnshamedPlugin() { string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName; UnshamedLogger = Logger.CreateLogSource("Unshamed"); Instance = null; Enabled = null; IgnoreCheatFlags = null; ShowPopups = null; ForceTrue = null; ForceFalse = null; Retroactive = null; RevealRequirements = null; GuidePanel = null; } } public static class KeyboardExtensions { public static bool IsKeyDown(this KeyboardShortcut shortcut) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKeyDown(((KeyboardShortcut)(ref shortcut)).MainKey)) { return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey); } return false; } public static bool IsKeyHeld(this KeyboardShortcut shortcut) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKey(((KeyboardShortcut)(ref shortcut)).MainKey)) { return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func<KeyCode, bool>)Input.GetKey); } return false; } } internal static class Recon { private static readonly string[] Interesting = new string[5] { "achiev", "trophy", "unlock", "cheat", "milestone" }; private static readonly string[] GameAssemblies = new string[6] { "assembly_valheim", "assembly_utils", "assembly_guiutils", "Splatform", "Splatform.Steam", "SoftReferenceableAssets" }; internal static string Run() { StringBuilder stringBuilder = new StringBuilder(); Versions(stringBuilder); Flags(stringBuilder); Symbols(stringBuilder); Enums(stringBuilder); CheatCommands(stringBuilder); Achievements(stringBuilder); string text = Path.Combine(Paths.ConfigPath, "Unshamed_recon.txt"); File.WriteAllText(text, stringBuilder.ToString()); return text; } private static void Versions(StringBuilder sb) { //IL_0052: 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_0094: 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) sb.AppendLine("=== versions ==="); sb.AppendLine("game " + Version.GetVersionString(false)); sb.AppendLine("mod 1.0.8"); sb.AppendLine("network " + 40u); sb.AppendLine("player " + ((object)(Player)46/*cast due to .constrained prefix*/).ToString()); sb.AppendLine("world " + ((object)(World)41/*cast due to .constrained prefix*/).ToString()); sb.AppendLine("item data " + ((object)(Item)109/*cast due to .constrained prefix*/).ToString()); sb.AppendLine("player data " + ((object)(PlayerData)33/*cast due to .constrained prefix*/).ToString()); sb.AppendLine("isModded " + Game.isModded); sb.AppendLine(); } private static void Flags(StringBuilder sb) { sb.AppendLine("=== bool fields worth a look ==="); Type[] array = new Type[4] { typeof(PlayerProfile), typeof(World), typeof(ItemData), typeof(ConsoleCommand) }; foreach (Type type in array) { foreach (FieldInfo item in from f in type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where f.FieldType == typeof(bool) && Matches(f.Name) select f) { sb.AppendLine(type.Name + "." + item.Name); } } sb.AppendLine(); } private static void Symbols(StringBuilder sb) { sb.AppendLine("=== types and members matching " + string.Join("/", Interesting) + " ==="); foreach (Assembly item in from a in AppDomain.CurrentDomain.GetAssemblies() where GameAssemblies.Contains<string>(a.GetName().Name) select a) { foreach (Type item2 in Types(item)) { bool flag = Matches(item2.Name); if (flag) { sb.AppendLine("type " + item2.FullName); } foreach (MemberInfo item3 in from m in item2.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where Matches(m.Name) select m) { if (!flag || item3.MemberType != MemberTypes.Method || !item3.Name.StartsWith("get_")) { sb.AppendLine("member " + item2.FullName + "." + Signature(item3)); } } } } sb.AppendLine(); } private static string Signature(MemberInfo member) { if (!(member is MethodInfo methodInfo)) { return member.Name; } return methodInfo.Name + "(" + string.Join(", ", from p in methodInfo.GetParameters() select p.ParameterType.Name) + ") -> " + methodInfo.ReturnType.Name; } private static void Enums(StringBuilder sb) { //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected I4, but got Unknown //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Expected I4, but got Unknown //IL_014a: Unknown result type (might be due to invalid IL or missing references) PlayerProfile obj = (Object.op_Implicit((Object)(object)Game.instance) ? Game.instance.GetPlayerProfile() : null); Dictionary<PlayerStatType, float> dictionary = ((obj != null) ? obj.m_playerStats[0].m_stats : null); sb.AppendLine("=== PlayerStatType (" + Enum.GetValues(typeof(PlayerStatType)).Length + " members) ==="); foreach (PlayerStatType item in Enum.GetValues(typeof(PlayerStatType)).Cast<PlayerStatType>()) { float value; float num = ((dictionary != null && dictionary.TryGetValue(item, out value)) ? value : 0f); sb.AppendLine($"{(int)item,4} {item,-28} {num}"); } sb.AppendLine(); sb.AppendLine("=== GlobalKeys ==="); string text = default(string); foreach (GlobalKeys item2 in Enum.GetValues(typeof(GlobalKeys)).Cast<GlobalKeys>()) { string arg = ((Object.op_Implicit((Object)(object)ZoneSystem.instance) && ZoneSystem.instance.GetGlobalKey(item2, ref text)) ? (" = " + text) : ""); sb.AppendLine($"{(int)item2,4} {item2}{arg}"); } sb.AppendLine(); } private static void CheatCommands(StringBuilder sb) { sb.AppendLine("=== commands that set the flag ==="); foreach (KeyValuePair<string, ConsoleCommand> item in from c in Terminal.commands where c.Value.IsCheat orderby c.Key select c) { sb.AppendLine(item.Key); } sb.AppendLine(); } private static void Achievements(StringBuilder sb) { //IL_00e0: Unknown result type (might be due to invalid IL or missing references) sb.AppendLine("=== achievements ==="); List<Achievement> list = StatSync.All().ToList(); if (list.Count == 0) { sb.AppendLine("none loaded, get into a world first"); return; } sb.AppendLine(list.Count + " defined, " + list.Count((Achievement a) => a.m_unlocked) + " unlocked"); foreach (Achievement item in list.OrderBy((Achievement a) => a.m_id)) { sb.AppendLine(string.Format("{0} {1,-32} {2,-10} {3,-28} {4}", item.m_unlocked ? "[x]" : "[ ]", item.m_id, item.m_difficultyRequirement, item.m_name, StatSync.Name(item))); } } private static IEnumerable<Type> Types(Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { return ex.Types.Where((Type t) => t != null); } } private static bool Matches(string name) { return Interesting.Any((string i) => name.IndexOf(i, StringComparison.OrdinalIgnoreCase) >= 0); } } internal static class ReturnOverrides { private static readonly HarmonyMethod TruePostfix = new HarmonyMethod(AccessTools.Method(typeof(ReturnOverrides), "ReturnTrue", (Type[])null, (Type[])null)); private static readonly HarmonyMethod FalsePostfix = new HarmonyMethod(AccessTools.Method(typeof(ReturnOverrides), "ReturnFalse", (Type[])null, (Type[])null)); internal static void Apply(Harmony harmony, string forceTrue, string forceFalse) { foreach (MethodInfo item in Resolve(forceTrue)) { Patch(harmony, item, TruePostfix, "true"); } foreach (MethodInfo item2 in Resolve(forceFalse)) { Patch(harmony, item2, FalsePostfix, "false"); } } private static void Patch(Harmony harmony, MethodInfo method, HarmonyMethod postfix, string value) { try { harmony.Patch((MethodBase)method, (HarmonyMethod)null, postfix, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); UnshamedPlugin.UnshamedLogger.LogInfo((object)("Forcing " + method.DeclaringType?.Name + "." + method.Name + " to return " + value)); } catch (Exception ex) { UnshamedPlugin.UnshamedLogger.LogError((object)("Couldn't patch " + method.DeclaringType?.Name + "." + method.Name + ": " + ex.Message)); } } private static IEnumerable<MethodInfo> Resolve(string entries) { if (string.IsNullOrWhiteSpace(entries)) { yield break; } foreach (string item in from e in entries.Split(new char[1] { ',' }) select e.Trim() into e where e.Length > 0 select e) { string[] array = item.Split(new string[1] { "::" }, StringSplitOptions.RemoveEmptyEntries); if (array.Length != 2) { UnshamedPlugin.UnshamedLogger.LogError((object)("'" + item + "' isn't a Type::Method entry, skipping it")); continue; } Type type = AccessTools.TypeByName(array[0]); if (type == null) { UnshamedPlugin.UnshamedLogger.LogError((object)("No type named '" + array[0] + "', skipping '" + item + "'")); continue; } MethodInfo[] array2 = Candidates(type, array[1]).ToArray(); if (array2.Length == 0) { UnshamedPlugin.UnshamedLogger.LogError((object)(type.Name + " has no bool-returning '" + array[1] + "', skipping it")); continue; } MethodInfo[] array3 = array2; for (int num = 0; num < array3.Length; num++) { yield return array3[num]; } } } private static IEnumerable<MethodInfo> Candidates(Type type, string name) { foreach (MethodInfo item in from m in type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where m.Name == name && m.ReturnType == typeof(bool) && !m.IsAbstract select m) { yield return item; } PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property?.PropertyType == typeof(bool) && property.GetMethod != null) { yield return property.GetMethod; } } private static void ReturnTrue(ref bool __result) { __result = true; } private static void ReturnFalse(ref bool __result) { __result = false; } } } namespace Unshamed.Guide { internal static class AchievementsPanel { [HarmonyPatch(typeof(InventoryGui), "Awake")] private static class InventoryGui_Awake_Patch { private static void Postfix(InventoryGui __instance) { if (!Object.op_Implicit((Object)(object)__instance.m_achievementsPanel)) { return; } try { Build(__instance.m_achievementsPanel); } catch (Exception ex) { UnshamedPlugin.UnshamedLogger.LogError((object)("Couldn't build the achievement guide panel, the vanilla hierarchy probably moved: " + ex)); _guide = null; } } } [HarmonyPatch(typeof(AchievementsGui), "CreateStatRow")] private static class AchievementsGui_CreateStatRow_Patch { private static bool Prefix(AchievementsGui __instance, string statKey, float currentAmount, float totalAmount) { if (!Reveal) { return true; } Row(__instance, statKey, currentAmount, totalAmount); return false; } } [HarmonyPatch(typeof(AchievementsGui), "OnOpenAchievementDetails")] private static class AchievementsGui_OnOpenAchievementDetails_Patch { private static void Prefix(AchievementsGui __instance, Achievement achievement, bool clickable, out bool __state) { __state = false; _opening = clickable && (Object)(object)achievement != (Object)null && !__instance.m_achievementDetails.activeSelf; if (_opening) { _unmet = 0; if (Reveal) { __state = achievement.m_isSecret; achievement.m_isSecret = false; } } } private static void Postfix(AchievementsGui __instance, Achievement achievement) { if (!_opening) { return; } if (Reveal) { foreach (Achievement item in achievement.m_otherAchievementTriggers.Where((Achievement o) => (Object)(object)o != (Object)null)) { Row(__instance, item.m_name, item.m_unlocked ? 1 : 0, 1f); } } Show(achievement); } private static void Finalizer(Achievement achievement, bool __state) { if (__state) { achievement.m_isSecret = true; } } } [HarmonyPatch(typeof(InventoryGui), "UpdateAchievementsList")] private static class InventoryGui_UpdateAchievementsList_Patch { private static void Prefix(out List<(Achievement a, bool secret, bool clickable)>? __state) { __state = null; if (!Reveal) { return; } __state = (from a in StatSync.All() select (a: a, m_isSecret: a.m_isSecret, m_clickable: a.m_clickable)).ToList(); foreach (var item2 in __state) { Achievement item = item2.a; item.m_isSecret = false; item.m_clickable = true; } } private static void Postfix(InventoryGui __instance) { if (!Reveal || !Object.op_Implicit((Object)(object)__instance.m_achievementsPanel)) { return; } Dictionary<string, Achievement> dictionary = new Dictionary<string, Achievement>(); foreach (Achievement item in StatSync.All()) { dictionary[Localization.instance.Localize(item.m_name)] = item; } foreach (GameObject achievements in __instance.m_achievementsPanel.m_achievementsList) { Transform obj = achievements.transform.Find("name"); TMP_Text val = ((obj != null) ? ((Component)obj).GetComponent<TMP_Text>() : null); Transform obj2 = achievements.transform.Find("description"); TMP_Text val2 = ((obj2 != null) ? ((Component)obj2).GetComponent<TMP_Text>() : null); if (!((Object)(object)val == (Object)null) && !((Object)(object)val2 == (Object)null) && dictionary.TryGetValue(val.text, out var value) && !value.m_unlocked) { var (num, num2) = Requirements.Count(value); if (num2 > 0) { val2.text += $"\n<color=#C8B48C>{num} / {num2}</color>"; } } } } private static void Finalizer(List<(Achievement a, bool secret, bool clickable)>? __state) { if (__state == null) { return; } foreach (var item4 in __state) { Achievement item = item4.a; bool item2 = item4.secret; bool item3 = item4.clickable; item.m_isSecret = item2; item.m_clickable = item3; } } } private const float Width = 520f; private const float Gap = 12f; private static readonly Color Done = new Color(0.45f, 0.85f, 0.4f, 1f); private static readonly Color Pending = new Color(0.85f, 0.8f, 0.72f, 1f); private static RectTransform? _details; private static Vector2 _detailsHome; private static RectTransform? _cover; private static Vector2 _coverMin; private static GameObject? _guide; private static TMP_Text? _title; private static TMP_Text? _body; private static ScrollRect? _scroll; private static int _unmet; private static bool _opening; internal static bool Reveal => UnshamedPlugin.On(UnshamedPlugin.RevealRequirements); private static bool ShowGuide => UnshamedPlugin.On(UnshamedPlugin.GuidePanel); private static void Build(AchievementsGui gui) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //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_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_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: 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_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: 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_0102: 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_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Expected O, but got Unknown //IL_016f: 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_018b: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: 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_01e0: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Expected O, but got Unknown //IL_02e3: Unknown result type (might be due to invalid IL or missing references) //IL_02f9: Unknown result type (might be due to invalid IL or missing references) //IL_030f: Unknown result type (might be due to invalid IL or missing references) //IL_031b: Unknown result type (might be due to invalid IL or missing references) //IL_0327: Unknown result type (might be due to invalid IL or missing references) //IL_0346: Unknown result type (might be due to invalid IL or missing references) //IL_0350: Expected O, but got Unknown //IL_03ee: Unknown result type (might be due to invalid IL or missing references) _details = (RectTransform)gui.m_achievementDetails.transform; _detailsHome = _details.anchoredPosition; Transform obj = ((Transform)_details).Find("coverInteraction"); _cover = (RectTransform?)(object)((obj is RectTransform) ? obj : null); if (Object.op_Implicit((Object)(object)_cover)) { _coverMin = _cover.offsetMin; } GameObject val = Object.Instantiate<GameObject>(((Component)_details).gameObject, (Transform)(object)_details); ((Object)val).name = "UnshamedGuide"; Transform val2 = val.transform.Find("coverInteraction"); if (Object.op_Implicit((Object)(object)val2)) { Object.DestroyImmediate((Object)(object)((Component)val2).gameObject); } RectTransform val3 = (RectTransform)val.transform; Vector2 val4 = default(Vector2); ((Vector2)(ref val4))..ctor(0.5f, 0.5f); val3.pivot = val4; Vector2 anchorMin = (val3.anchorMax = val4); val3.anchorMin = anchorMin; ((Transform)val3).localScale = Vector3.one; val3.sizeDelta = new Vector2(520f, _details.sizeDelta.y); val3.anchoredPosition = new Vector2((0f - (_details.sizeDelta.x + 520f)) / 2f - 12f, 0f); Transform val6 = val.transform.Find("Closebutton"); if (Object.op_Implicit((Object)(object)val6)) { Object.DestroyImmediate((Object)(object)((Component)val6).gameObject); } RectTransform val7 = (RectTransform)val.transform.Find("DetailsContainer"); val7.sizeDelta = new Vector2(480f, val7.sizeDelta.y + 40f); val7.anchoredPosition += new Vector2(0f, -20f); RectTransform val8 = (RectTransform)((Transform)val7).Find("DetailsListScroll"); val8.anchoredPosition = new Vector2(val7.sizeDelta.x / 2f + 6f, 0f); val8.sizeDelta = new Vector2(val8.sizeDelta.x, val7.sizeDelta.y); Transform obj2 = ((Transform)val7).Find("DetailsList"); _scroll = ((Component)obj2).GetComponent<ScrollRect>(); Transform val9 = obj2.Find("UnlockConditionElement"); RectTransform val10 = (RectTransform)obj2.Find("ListRoot"); _body = ((Component)val9.Find("name")).GetComponent<TMP_Text>(); _body.transform.SetParent((Transform)(object)val10, false); Object.DestroyImmediate((Object)(object)((Component)val9).gameObject); foreach (Transform item in (from Transform t in (IEnumerable)val10 where (Object)(object)t != (Object)(object)_body.transform select t).ToList()) { Object.DestroyImmediate((Object)(object)((Component)item).gameObject); } Object.DestroyImmediate((Object)(object)((Component)val10).GetComponent<GridLayoutGroup>()); val10.anchorMin = new Vector2(0f, 1f); val10.anchorMax = new Vector2(1f, 1f); val10.pivot = new Vector2(0.5f, 1f); val10.anchoredPosition = Vector2.zero; val10.sizeDelta = Vector2.zero; VerticalLayoutGroup obj3 = ((Component)val10).gameObject.AddComponent<VerticalLayoutGroup>(); ((LayoutGroup)obj3).padding = new RectOffset(12, 18, 10, 10); ((HorizontalOrVerticalLayoutGroup)obj3).childControlWidth = true; ((HorizontalOrVerticalLayoutGroup)obj3).childControlHeight = true; ((HorizontalOrVerticalLayoutGroup)obj3).childForceExpandWidth = true; ((HorizontalOrVerticalLayoutGroup)obj3).childForceExpandHeight = false; ContentSizeFitter obj4 = ((Component)val10).GetComponent<ContentSizeFitter>() ?? ((Component)val10).gameObject.AddComponent<ContentSizeFitter>(); obj4.verticalFit = (FitMode)2; obj4.horizontalFit = (FitMode)0; ((Component)_body).gameObject.SetActive(true); _body.enableAutoSizing = false; _body.fontSize = 17f; _body.textWrappingMode = (TextWrappingModes)1; _body.overflowMode = (TextOverflowModes)0; _body.alignment = (TextAlignmentOptions)257; _body.richText = true; ((Graphic)_body).color = Pending; _title = ((Component)val.transform.Find("topic")).GetComponent<TMP_Text>(); _guide = val; val.SetActive(false); } private static void Show(Achievement a) { //IL_0075: 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) //IL_0089: 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) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Expected O, but got Unknown //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)_details) || !Object.op_Implicit((Object)(object)_guide) || (Object)(object)_title == (Object)null || (Object)(object)_body == (Object)null) { return; } if (!ShowGuide) { _guide.SetActive(false); _details.anchoredPosition = _detailsHome; if (Object.op_Implicit((Object)(object)_cover)) { _cover.offsetMin = _coverMin; } return; } _details.anchoredPosition = _detailsHome + new Vector2(266f, 0f); if (Object.op_Implicit((Object)(object)_cover)) { _cover.offsetMin = _coverMin - new Vector2(532f, 0f); } _guide.SetActive(true); _title.text = Localization.instance.Localize(a.m_name); _body.text = Compose(a); LayoutRebuilder.ForceRebuildLayoutImmediate((RectTransform)_body.transform.parent); if (Object.op_Implicit((Object)(object)_scroll)) { _scroll.verticalNormalizedPosition = 1f; } } internal static string Compose(Achievement a, bool rich = true) { //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Invalid comparison between Unknown and I4 StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(Hi(Localization.instance.Localize(a.m_description), "#FFA13C")); stringBuilder.AppendLine(); stringBuilder.AppendLine(Blurbs.For(a)); stringBuilder.AppendLine(); stringBuilder.AppendLine(Bold("Difficulty: ") + Requirements.DifficultyText(a) + " (this world: " + Requirements.CurrentDifficulty() + ")"); if (a.m_isSecret) { stringBuilder.AppendLine(Bold("Secret: ") + "vanilla hides this one until you unlock it."); } var (num, num2) = Requirements.Count(a); if (a.m_unlocked) { stringBuilder.AppendLine(Hi("Unlocked.", "#74D966")); } else if (a.m_lenientBuildAchievement) { var (value, value2) = Requirements.Lenient(a); stringBuilder.AppendLine(Bold("Progress: ") + "lenient score " + Requirements.Number(value) + ", needs more than " + Requirements.Number(value2) + ". Each row counts up to 115% of its target."); } else if (num2 > 0) { stringBuilder.AppendLine(Bold("Progress: ") + $"{num} of {num2} met" + ((num2 > 1) ? ", missing ones sort to the top of the list." : ".")); } if (!a.m_unlocked && (int)a.m_difficultyRequirement == 1 && Object.op_Implicit((Object)(object)Game.instance) && StatSync.Apply(Game.instance.GetPlayerProfile(), preview: true, new StatSync.Wanted((IEnumerable<Achievement>)(object)new Achievement[1] { a })).Any) { stringBuilder.AppendLine().AppendLine(Hi("Some of this you already did, back when the game wasn't counting. 'unshamed retro' in the console (F5) credits it.", "#FFA13C")); } if (!Achievements.CanGetAchievements(false)) { stringBuilder.AppendLine().AppendLine(Hi("This character can't earn achievements right now, so none of this will move. 'unshamed status' in the console says why.", "#FFA13C")); } string text = Extras.For(a, rich); if (text.Length > 0) { stringBuilder.AppendLine().AppendLine(text); } return stringBuilder.ToString().TrimEnd(Array.Empty<char>()); string Bold(string text2) { if (!rich) { return text2; } return "<b>" + text2 + "</b>"; } string Hi(string text2, string color) { if (!rich) { return text2; } return "<color=" + color + ">" + text2 + "</color>"; } } private static void Row(AchievementsGui gui, string key, float have, float need) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0042: 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) AchievementDetailUnlockCondition val = Object.Instantiate<AchievementDetailUnlockCondition>(gui.m_achievementDetailsElementPrefab, (Transform)(object)gui.m_achievementDetailsListRoot); ((Component)val).gameObject.SetActive(true); bool flag = have >= need; TextMeshProUGUI statName = val.StatName; Color color = (((Graphic)val.Progress).color = (flag ? Done : Pending)); ((Graphic)statName).color = color; ((TMP_Text)val.StatName).text = Requirements.Label(key); ((TMP_Text)val.Progress).text = Requirements.Number(have) + " / " + Requirements.Number(need); if (!flag) { ((Component)val).transform.SetSiblingIndex(_unmet++); } } } internal static class Blurbs { internal const string KillCredit = "Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list."; private const string SpiritCaller = "The Spirit Caller staff's wolf, boar, moose and bjorn summons are on the list too, as their own entries (vanilla gives them no name, they show as Wolf spiritcaller and so on). They're friendly, so you need the Butcher knife or PvP on to hurt them, and they have to actually die: unsummoning one or walking away from it doesn't count."; private static readonly Dictionary<string, string> Text = new Dictionary<string, string> { ["FirstDeath"] = "Die once. Any cause at all.", ["Arrived"] = "Spawn into a world once. \"The tenth world\" is Valheim itself in the lore, it is not asking you to visit ten worlds.", ["BigFish"] = "Catch a quality 4 fish on a fishing rod. That's the [4] shown after its name when you hover it. A fish grabbed by hand out of the water doesn't count, the stat only moves when a catch comes in on the rod.", ["GrindFish"] = "Catch one of each of the 12 fish on a rod: Perch, Pike, Tuna, Tetra, Trollfish, Giant Herring, Grouper, Coral Cod, Anglerfish, Northern Salmon, Magmafish and Pufferfish. Hand-grabbed fish don't count.", ["Boss1Eikthyr"] = "Kill Eikthyr. Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list.", ["Boss2Elder"] = "Kill The Elder. Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list.", ["Boss3Bonemass"] = "Kill Bonemass. Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list.", ["Boss4Moder"] = "Kill Moder. Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list.", ["Boss5Yagluth"] = "Kill Yagluth. Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list.", ["Boss6Queen"] = "Kill The Queen. Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list.", ["Boss7Fader"] = "Kill Fader. Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list.", ["Boss8FrozenKing"] = "Kill Kall Fimbulbringer, the Deep North boss. It's his final phase that registers as the kill. Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list.", ["SoloBoss"] = "Kill any boss where you were the only player who damaged it. Friends can stand and watch, they just can't land a single hit, and one who hit it and then logged off still counts against you.", ["MultiplayerBoss"] = "Kill any boss that at least two different players damaged. Everyone who hit it gets the achievement.", ["AllBosses"] = "Kill all eight bosses on any difficulty: Eikthyr, The Elder, Bonemass, Moder, Yagluth, The Queen, Fader and Kall Fimbulbringer. Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list.", ["AllBossesNormal"] = "Kill all eight bosses with the world's Combat modifier on Normal, Hard or Very hard at the moment of each kill. Kills on Easy, Very easy or Casual don't count, and neither do kills from before you changed the setting. Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list.", ["AllBossesHard"] = "Kill all eight bosses with the world's Combat modifier on Hard or Very hard at the moment of each kill. Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list.", ["AllMiniBosses"] = "Kill Hildir's three quest bosses and Lord Reto: Brenna (Black Forest), Geirrhafa (Mountains), both Plains brothers (the list has one entry for Zil & Thungr and a separate one for Zil), and Lord Reto in the Ashlands. Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list.", ["BuildDyrnwyn"] = "Craft Dyrnwyn from its recipe. It has to actually come out of crafting.", ["KillAllCreatures"] = "Kill one of every creature on the list. The list is built when you load in, from every creature prefab flagged for this achievement, so a modded creature cloned from a vanilla one can end up on it too. The details list on the right is your exact list, with the ones you still need at the top. The Spirit Caller staff's wolf, boar, moose and bjorn summons are on the list too, as their own entries (vanilla gives them no name, they show as Wolf spiritcaller and so on). They're friendly, so you need the Butcher knife or PvP on to hurt them, and they have to actually die: unsummoning one or walking away from it doesn't count. Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list.", ["KillAllCreaturesHard"] = "Same list as The Hunter, but each kill has to happen with the world's Combat modifier on Hard or Very hard. The Spirit Caller staff's wolf, boar, moose and bjorn summons are on the list too, as their own entries (vanilla gives them no name, they show as Wolf spiritcaller and so on). They're friendly, so you need the Butcher knife or PvP on to hurt them, and they have to actually die: unsummoning one or walking away from it doesn't count. Kill credit goes to every player who damaged it at any point and is still online when it dies, the last hit doesn't matter. Damage from your tames doesn't put you on the list.", ["FindAllTrophies"] = "Pick up one of every trophy. The list is every trophy item loaded (mod trophies included) minus a few Iron Gate excluded. Trophies you already carry get counted the next time your inventory changes, so move them around if old ones aren't showing.", ["AllFoodEaten"] = "Eat one of every item that fills a food slot. The list is built from every loaded item with a food value, so modded food makes it longer. Meads and potions aren't food and aren't on it.", ["AllFoodCooked"] = "Make one of every dish. That's everything with a food value that comes out of a crafting recipe (the cauldron, mostly) plus everything with a food value a cooking station turns out: the grill, the iron cooking station, the oven. Pulling cooked meat off the grill counts.", ["AllItemCraft"] = "Craft one of every recipe that needs a crafting station, minus the handful Iron Gate excluded. Taking finished food off a cooking station counts as crafting it. Modded recipes with a station are on the list too, which can make this a lot longer in a modded game.", ["AllWeaponCraft"] = "Craft one of every weapon that has a recipe, minus Iron Gate's exclusions.", ["AllBuildPieces"] = "Place one of every build piece on every tool that can deconstruct pieces (the hammer, plus any modded tool that allows removal). The repair \"piece\" isn't on it. The details list shows exactly which pieces are left.", ["GrindBuild"] = "Place 500 pieces with a tool that trains Crafting (the hammer). The catch: every piece you remove puts you one placement in debt, up to 20, and those placements pay the debt off without counting. Tear down and rebuild and you're treading water. The debt isn't saved, relogging clears it.", ["BuildHigh"] = "Place a piece at least 49 m above whatever terrain is straight below it. It also has to sit on your own foundation: a line straight down from it has to pass through at least 5 pieces, and more than 45% of those have to be ones you placed. No terrain within 200 m below means no reading.", ["BuildHighWorld"] = "Place a piece outdoors at world height 432 or more (sea level is 30). Height alone isn't enough, it has to sit on your own foundation: a line straight down from it (up to 200 m) has to pass through at least 5 build pieces, and more than 45% of those have to be ones you placed. Terrain and rock don't count toward that, so a single piece dropped on a tall peak gives no reading. Stack a tower of 5+ of your own pieces and place the last one on top, above 432. Build up from a mountain peak.", ["BuildHouse"] = "Have your own placed pieces loaded around you with these build menu tags: Floor 6, Wall 8, Roof 4, Furniture 1, Lighting 1, Storage 1. It's lenient: each tag counts up to 115% of its target and the capped total has to beat 21, so being over in one tag can cover being a little short in another. It isn't checked on every placement: the first check is your 11th piece after loading in, then every 21st piece after that, so keep placing.", ["BuildVillage"] = "Have your own placed pieces loaded around you with these build menu tags: Building 10, Floor 40, Wall 40, Roof 20, Architecture 10, Furniture 10, Lighting 5, Decor 5. Lenient like The Homesteader: each tag counts up to 115% of its target and the capped total has to beat 140. Checked on the same schedule too, every 21st piece you place.", ["ChildOfOdin"] = "Unlock The Pathfinder, The Toughest Viking, The Master Hunter and The Survivor. It checks whenever another achievement unlocks and when you load in.", ["KingsQueens"] = "Unlock The Viking, The Explorer, The Carpenter, The Hunter, The Master Chef and The Artisan. It checks whenever another achievement unlocks and when you load in.", ["DeathByAllTypes"] = "Die once to each of 16 causes. Only the hit that actually kills you counts: poisoned by a blob and finished off by a draugr is Enemy, not Poison.\n- Enemy: a creature's attack. Other players don't count.\n- Falling: fall damage.\n- Drowning: running out of stamina while swimming.\n- Burning: the burning damage over time, not the fire hit itself.\n- Freezing: the Freezing status, cold with no frost protection.\n- Poisoning: poison damage over time.\n- Smoke: breathing smoke indoors.\n- Edge of the world: going over the edge, past about 10,420 m out and dropping below the sea.\n- Tree: a falling tree or its log landing on you.\n- Ballista: shot by a ballista.\n- Stalactite: a falling icicle in the frost caves.\n- Catapult: a catapult shot.\n- Ashlands ocean: the boiling Ashlands water.\n- Obliterator: standing in the Obliterator.\n- Drawbridge: a drawbridge coming down on you.\n- Ashlands lava: lava.\nNot on the list: other players, carts, boats, structures, cinder fire, and killing yourself.", ["DeathByTree"] = "Get killed by a falling tree or its log. Chop, don't run.", ["DeathByObliterator"] = "Die inside the Obliterator.", ["SailEdge"] = "Die by going over the edge of the world. Sailing out there isn't enough, it's counted from the death: past about 10,420 m from the centre, dropping below the sea.", ["DeathByTreeAll"] = "Get killed by each of 10 kinds of tree. The log that kills you remembers which tree it came from, and its half logs do too.\n- Fir and Pine: Black Forest and Meadows.\n- Beech: Meadows.\n- Birch and Oak: Meadows and Plains, needs a bronze axe.\n- Swamp tree: Swamp, needs a bronze axe.\n- Snow fir and Snow pine: Deep North. In game they both just say Timber Tree when you hover them.\n- Yggdrasil shoot: Mistlands, needs a black metal axe.\n- Ashlands tree: Ashlands.\nHeads up: in the game data, some meadows and heath treasure chests, Deep North loot, glow worms, frost cores and mountain cave crystals carry a stale stat id that lands on Death by Birch. If Birch is already green and a birch never flattened you, that's why.", ["ExploreNSEW"] = "Go more than 10,350 m from the centre of the world to the north, south, east and west. It only ticks while you're moving (more than a metre every 2.5 seconds) and never while debug flying. The world ends at 10,500 m, so it's a thin strip and mostly ocean.", ["ExploreNSEWNoMap"] = "Same as The Explorer, but the world has to have the No Map modifier on while you're out there.", ["GrindComfort"] = "Reach comfort level 20. You start at 1, get +1 for being sheltered, then each comfort piece within 10 m adds its value (only the best one from each group). The record only updates when your base value changes, so if you're sat at 20 and nothing happens, walk out of the base and back in.", ["GrindCook"] = "Craft 100 consumables from a crafting menu, the cauldron mostly. It counts every item made, meads and potions included. Bait doesn't count, and the grill and oven don't count here at all.", ["GrindDays"] = "Survive 30 in-game days in a row. A day counts when the morning \"Day N\" message shows while you're in the world, and dying resets the streak to 0. Your best streak is what's kept.", ["GrindEat"] = "Eat 500 food items. Repeats count.", ["GrindForager"] = "Pick 250 berries and 250 mushrooms. Berries are raspberry, blueberry, cloudberry and lingonberry bushes plus vineberry vines. Mushrooms are the red, yellow and blue ones, Jotun puffs, magecaps and smoke puffs. Replanted and wild both count.", ["GrindHarvest"] = "Harvest 500 grown crops: barley, carrots, flax, kale, oats, onions, poteitr and turnips. Seed carrots, seed onions and seed turnips don't count, their stat id in the game data is stale.", ["GrindHoney"] = "Take 500 honey out of beehives. Emptying a full hive counts everything in it.", ["GrindLeviathan"] = "Be within 10 m of a Leviathan (measured flat, height ignored) when it dives. Every pickaxe hit on its back has a 25% chance to make it shake, and it goes under 5 seconds later. It doesn't have to be your hit, anyone close enough when it dives gets it, so don't row off after it shakes.", ["GrindSail"] = "Travel 131,946 m while aboard a ship, anywhere on deck.", ["GrindSailHelm"] = "Travel 65,973 m while steering a ship.", ["GrindTreasure"] = "Open 10 buried treasure chests, the ones you dig up. Dungeon and location chests don't count. Each chest counts once per character name.", ["GrindTrees"] = "Fell 500 trees yourself. Your hit has to be the one that brings it down. Logs and stumps don't count." }; internal static string For(Achievement a) { if (!Text.TryGetValue(a.m_id, out string value)) { return "No write-up for this one, it isn't a vanilla achievement I know about. The list on the right is what it actually checks."; } return value; } } internal static class Comfort { private const float Radius = 10f; internal static string Describe(bool rich) { //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) List<Piece> list = Pieces(); if (list.Count == 0) { return ""; } List<IGrouping<ComfortGroup, Piece>> list2 = (from p in list where (int)p.m_comfortGroup > 0 group p by p.m_comfortGroup into g orderby g.Key select g).ToList(); List<Piece> list3 = Distinct(list.Where((Piece p) => (int)p.m_comfortGroup == 0)); int num = 2 + list2.Sum((IGrouping<ComfortGroup, Piece> g) => g.Max((Piece p) => p.m_comfort)) + list3.Sum((Piece p) => p.m_comfort); StringBuilder stringBuilder = new StringBuilder(); Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null) { stringBuilder.AppendLine(Fmt.Heading("Right now", rich)); if (!localPlayer.InShelter()) { stringBuilder.AppendLine($"Comfort {localPlayer.GetComfortLevel()}. You're not sheltered, so nothing nearby counts."); } else { List<Piece> list4 = Counting(((Component)localPlayer).transform.position); stringBuilder.AppendLine($"Comfort {localPlayer.GetComfortLevel()}, counting these within {10f:0} m:"); stringBuilder.AppendLine((list4.Count == 0) ? Fmt.Dim(" nothing", rich) : Fmt.Columns(list4.Select((Piece p) => Entry(p, p.GetComfort())), rich)); } stringBuilder.AppendLine(Fmt.Gap(rich)); } stringBuilder.AppendLine(Fmt.Heading("Comfort pieces", rich)); stringBuilder.AppendLine($"Most you can stack with what's loaded: {num}. You start at 1, sheltered adds 1, and only the best piece from each group counts."); foreach (IGrouping<ComfortGroup, Piece> item in list2) { stringBuilder.AppendLine(Fmt.Gap(rich)); stringBuilder.AppendLine(Fmt.Sub(((object)item.Key/*cast due to .constrained prefix*/).ToString(), "best counts", rich)); stringBuilder.AppendLine(Fmt.Columns(from p in Distinct(item) select Entry(p, p.m_comfort), rich)); } if (list3.Count > 0) { stringBuilder.AppendLine(Fmt.Gap(rich)); stringBuilder.AppendLine(Fmt.Sub("No group", "each different one counts", rich)); stringBuilder.AppendLine(Fmt.Columns(list3.Select((Piece p) => Entry(p, p.m_comfort)), rich)); } return stringBuilder.ToString().TrimEnd(Array.Empty<char>()); string Entry(Piece p, int comfort) { return Name(p) + " " + Fmt.Dim("+" + comfort, rich); } static string Name(Piece p) { return Fmt.Loc(p.m_name, ((Object)p).name); } } private static List<Piece> Pieces() { if (!Object.op_Implicit((Object)(object)ObjectDB.instance)) { return new List<Piece>(); } return (from p in ObjectDB.instance.GetAllBuildPieces(true) where Object.op_Implicit((Object)(object)p) && p.m_comfort > 0 select p).ToList(); } private static List<Piece> Distinct(IEnumerable<Piece> pieces) { return (from p in pieces group p by p.m_name into g select g.OrderByDescending((Piece p) => p.m_comfort).First() into p orderby p.m_comfort descending, p.m_name select p).ToList(); } private static List<Piece> Counting(Vector3 position) { //IL_0006: 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_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) List<Piece> list = new List<Piece>(); Piece.GetAllComfortPiecesInRadius(position, 10f, list); list.Sort((Comparison<Piece>)SE_Rested.PieceComfortSort); List<Piece> list2 = new List<Piece>(); for (int i = 0; i < list.Count; i++) { if (i > 0) { Piece val = list[i - 1]; if (((int)list[i].m_comfortGroup != 0 && list[i].m_comfortGroup == val.m_comfortGroup) || list[i].m_name == val.m_name) { continue; } } if (list[i].GetComfort() > 0) { list2.Add(list[i]); } } return list2; } } internal static class Extras { private const float ExploreLine = 10350f; internal static string For(Achievement a, bool rich) { try { string result; switch (a.m_id) { case "GrindComfort": result = Comfort.Describe(rich); break; case "BuildVillage": case "BuildHouse": result = Tags(a, rich); break; case "GrindForager": result = Pickables(rich, (PlayerStatType)124, (PlayerStatType)125); break; case "GrindHarvest": result = Pickables(rich, (PlayerStatType)123); break; case "DeathByTreeAll": result = Trees(rich); break; case "GrindCook": result = Cookables(rich); break; case "ExploreNSEW": result = Explore(rich, noMap: false); break; case "ExploreNSEWNoMap": result = Explore(rich, noMap: true); break; case "GrindDays": result = Days(rich); break; case "GrindBuild": result =
plugins/HBK-NaturalForces/NaturalForces.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using NaturalForces.Atmosphere; using NaturalForces.Audio; using NaturalForces.BloodMoon; using NaturalForces.Compat; using NaturalForces.Core; using NaturalForces.DebugTools; using NaturalForces.Hazards; using NaturalForces.Net; using NaturalForces.Patches; using UnityEngine; using UnityEngine.Audio; using UnityEngine.Networking; using UnityEngine.Rendering; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("assembly_utils")] [assembly: IgnoresAccessChecksTo("assembly_valheim")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("NaturalForces")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")] [assembly: AssemblyProduct("NaturalForces")] [assembly: AssemblyTitle("NaturalForces")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.1.0.0")] [module: UnverifiableCode] namespace NaturalForces { [BepInPlugin("naturmod.NaturalForces", "Natural Forces", "0.2.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] [SynchronizationMode(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { public const string PluginGuid = "naturmod.NaturalForces"; public const string PluginName = "Natural Forces"; public const string PluginVersion = "0.2.0"; internal static ConfigEntry<float> EventLengthDays; internal static ConfigEntry<int> FallbackDaysPerSeason; internal static ConfigEntry<bool> ScheduleEnabled; internal static ConfigEntry<float> YearlyEventChance; internal static ConfigEntry<int> MinDaysBetweenEvents; internal static ConfigEntry<bool> RequireNiceWeather; internal static ConfigEntry<int> NiceWeatherPatienceDays; internal static ConfigEntry<float> StartDayFractionMin; internal static ConfigEntry<float> StartDayFractionMax; internal static ConfigEntry<bool> BlockRaidsDuringEvent; internal static ConfigEntry<string> StormFrom; internal static ConfigEntry<float> LightningAmount; internal static ConfigEntry<float> LightningRadius; internal static ConfigEntry<float> LightningCharacterDamage; internal static ConfigEntry<float> LightningStructureDamage; internal static ConfigEntry<float> LightningTreeFellChance; internal static ConfigEntry<float> MinStructureHealth; internal static ConfigEntry<int> NearMissesBeforeHit; internal static ConfigEntry<float> ExposureBeforeHit; internal static ConfigEntry<float> ElmoSecondsBeforeHit; internal static ConfigEntry<float> HailAmount; internal static ConfigEntry<float> HailDamagePerSecond; internal static ConfigEntry<bool> BlockBedsDuringBloodMoon; internal static ConfigEntry<float> BloodMoonSpawnsPerMinute; internal static ConfigEntry<int> BloodMoonMaxMobsPerPlayer; internal static ConfigEntry<int> BloodMoonExtraStars; internal static ConfigEntry<int> BloodMoonMaxLevel; internal static ConfigEntry<int> BloodMoonMinModifiers; internal static ConfigEntry<int> BloodMoonMaxModifiers; internal static ConfigEntry<float> BloodMoonHordeSize; internal static ConfigEntry<bool> BloodMoonChampion; internal static ConfigEntry<int> ChampionExtraStars; internal static ConfigEntry<float> ChampionSize; internal static ConfigEntry<int> ChampionModifiers; internal static ConfigEntry<string> BloodMoonModifiers; internal static ConfigEntry<bool> LogStateChanges; internal static ConfigEntry<float> AtmosphereStrength; internal static ConfigEntry<float> WeatherTransitionSeconds; internal static ConfigEntry<float> RainBoost; internal static ConfigEntry<float> BloodMoonBrightness; internal static ConfigEntry<float> SfxVolume; internal static ConfigEntry<float> EventMusicVolume; internal static ConfigEntry<float> CrossfadeSeconds; internal static ConfigEntry<float> VanillaDuckStrength; internal static ConfigEntry<bool> PlaceholderMusic; internal static ConfigEntry<float> OmensVanillaFadeOut; internal static ConfigEntry<float> OmensMusicStart; internal static ConfigEntry<float> RecoveryVanillaReturn; private Harmony _harmony; internal static Plugin Instance { get; private set; } internal static ManualLogSource Log { get; private set; } private void Awake() { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown Instance = this; Log = ((BaseUnityPlugin)this).Logger; BindConfig(); EventRegistry.RegisterDefaults(); SeasonProvider.Initialize(); CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new NfCommand()); _harmony = new Harmony("naturmod.NaturalForces"); _harmony.PatchAll(typeof(Plugin).Assembly); FarLandsCompat.Apply(_harmony); if (!FxUtil.Headless) { SoundBank.EnsureLoaded(); } Log.LogInfo((object)("Natural Forces 0.2.0 geladen. Seasons: " + (SeasonProvider.SeasonsInstalled ? "gefunden" : "nicht installiert (Fallback)"))); } private void Update() { NetSync.Tick(); EventDirector.Tick(); YearPlanner.Tick(); LayeredMusicManager.Tick(); AtmosphereController.Tick(); LightningDirector.Tick(); DistantThunder.Tick(); StrikeResolver.Tick(); HailController.Tick(); BloodMoonController.Tick(); } private void OnDestroy() { Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } private static ConfigDescription ServerSide(string text, AcceptableValueBase range = null) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown return new ConfigDescription(text + " [Server: wird an alle Spieler übertragen]", range, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } }); } private void BindConfig() { //IL_0740: Unknown result type (might be due to invalid IL or missing references) //IL_074a: Expected O, but got Unknown //IL_077d: Unknown result type (might be due to invalid IL or missing references) //IL_0787: Expected O, but got Unknown //IL_07ba: Unknown result type (might be due to invalid IL or missing references) //IL_07c4: Expected O, but got Unknown //IL_07f7: Unknown result type (might be due to invalid IL or missing references) //IL_0801: Expected O, but got Unknown //IL_0834: Unknown result type (might be due to invalid IL or missing references) //IL_083e: Expected O, but got Unknown //IL_0871: Unknown result type (might be due to invalid IL or missing references) //IL_087b: Expected O, but got Unknown //IL_08ae: Unknown result type (might be due to invalid IL or missing references) //IL_08b8: Expected O, but got Unknown //IL_08eb: Unknown result type (might be due to invalid IL or missing references) //IL_08f5: Expected O, but got Unknown //IL_0948: Unknown result type (might be due to invalid IL or missing references) //IL_0952: Expected O, but got Unknown //IL_0985: Unknown result type (might be due to invalid IL or missing references) //IL_098f: Expected O, but got Unknown //IL_09c2: Unknown result type (might be due to invalid IL or missing references) //IL_09cc: Expected O, but got Unknown EventLengthDays = ((BaseUnityPlugin)this).Config.Bind<float>("General", "EventLengthDays", 1f, ServerSide("Gesamtdauer eines Events (alle Phasen A–E) in Ingame-Tagen.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 5f))); FallbackDaysPerSeason = ((BaseUnityPlugin)this).Config.Bind<int>("General", "FallbackDaysPerSeason", 10, ServerSide("Nur ohne Seasons-Mod: Tage pro Jahreszeit (Jahr = 4 x Wert).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100))); ScheduleEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Schedule", "Enabled", true, ServerSide("Events automatisch starten (höchstens eines pro Seasons-Jahr).")); YearlyEventChance = ((BaseUnityPlugin)this).Config.Bind<float>("Schedule", "YearlyEventChance", 1f, ServerSide("Wahrscheinlichkeit, dass es in einem Jahr überhaupt ein Event gibt (1 = jedes Jahr).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f))); MinDaysBetweenEvents = ((BaseUnityPlugin)this).Config.Bind<int>("Schedule", "MinDaysBetweenEvents", 10, ServerSide("Mindestabstand in Ingame-Tagen zwischen zwei automatischen Events.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 500))); RequireNiceWeather = ((BaseUnityPlugin)this).Config.Bind<bool>("Schedule", "RequireNiceWeather", true, ServerSide("Nur an einem schönen Tag starten (kein Regen, Gewitter, Nebel, Schnee bei den Spielern).")); NiceWeatherPatienceDays = ((BaseUnityPlugin)this).Config.Bind<int>("Schedule", "NiceWeatherPatienceDays", 3, ServerSide("So viele Tage wird auf schönes Wetter gewartet, danach startet das Event trotzdem.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50))); StartDayFractionMin = ((BaseUnityPlugin)this).Config.Bind<float>("Schedule", "EarliestStartTime", 0.3f, ServerSide("Frühester Start am Tag (0 = Mitternacht, 0.25 = Sonnenaufgang, 0.30 = schon hell, 0.5 = Mittag). Zusätzlich muss Tageslicht sein.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 0.7f))); StartDayFractionMax = ((BaseUnityPlugin)this).Config.Bind<float>("Schedule", "LatestStartTime", 0.45f, ServerSide("Spätester Start am Tag (damit sich der Sturm über den Tag aufbaut).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 0.75f))); BlockRaidsDuringEvent = ((BaseUnityPlugin)this).Config.Bind<bool>("Schedule", "BlockRaidsDuringEvent", true, ServerSide("Kein Raid während einer Naturgewalt; ein automatisches Event wartet, bis ein laufender Raid vorbei ist.")); StormFrom = ((BaseUnityPlugin)this).Config.Bind<string>("Hazards", "StormFrom", "Random", ServerSide("Himmelsrichtung, aus der der Sturm aufzieht (Donner, Blitze, Wind).", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[9] { "Random", "N", "NE", "E", "SE", "S", "SW", "W", "NW" }))); LightningAmount = ((BaseUnityPlugin)this).Config.Bind<float>("Hazards", "LightningAmount", 1f, ServerSide("Multiplikator für die Anzahl der Blitze (1 = Hauptphase bis ~60 pro Minute und Spieler).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f))); LightningRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Hazards", "LightningRadius", 4f, ServerSide("Wirkungsradius eines Einschlags in Metern.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 15f))); LightningCharacterDamage = ((BaseUnityPlugin)this).Config.Bind<float>("Hazards", "LightningCharacterDamage", 40f, ServerSide("Blitzschaden an Spielern/Kreaturen im Zentrum (nimmt nach außen ab; Blitzresistenz zählt). Unter einem Dach: kein Schaden.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1000f))); LightningStructureDamage = ((BaseUnityPlugin)this).Config.Bind<float>("Hazards", "LightningStructureDamage", 120f, ServerSide("Schaden an getroffenen Bauteilen.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2000f))); LightningTreeFellChance = ((BaseUnityPlugin)this).Config.Bind<float>("Hazards", "LightningTreeFellChance", 0.7f, ServerSide("Wahrscheinlichkeit, dass ein getroffener Baum umstürzt.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f))); MinStructureHealth = ((BaseUnityPlugin)this).Config.Bind<float>("Hazards", "MinStructureHealth", 0.25f, ServerSide("Gebäude werden nie zerstört: so viel Haltbarkeit (Anteil) bleibt mindestens übrig.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 1f))); NearMissesBeforeHit = ((BaseUnityPlugin)this).Config.Bind<int>("Hazards", "NearMissesBeforeHit", 3, ServerSide("Gezielte Blitze schlagen erst so oft knapp neben dem Spieler ein (Warnung), bevor einer trifft.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 20))); ExposureBeforeHit = ((BaseUnityPlugin)this).Config.Bind<float>("Hazards", "ExposureBeforeHit", 15f, ServerSide("Erst wer so viele Sekunden ungeschützt im Sturm steht, kann direkt getroffen werden.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 300f))); ElmoSecondsBeforeHit = ((BaseUnityPlugin)this).Config.Bind<float>("Hazards", "ElmoSecondsBeforeHit", 5f, ServerSide("So lange knistert das Elmsfeuer am Spieler, bevor ein Blitz treffen kann (letzte Warnung).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f))); HailAmount = ((BaseUnityPlugin)this).Config.Bind<float>("Hazards", "HailAmount", 1f, ServerSide("Stärke des Hagels (0 = kein Hagel).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f))); HailDamagePerSecond = ((BaseUnityPlugin)this).Config.Bind<float>("Hazards", "HailDamagePerSecond", 3f, ServerSide("Hagelschaden pro Sekunde für Spieler im Freien (unter einem Dach: keiner).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 50f))); BlockBedsDuringBloodMoon = ((BaseUnityPlugin)this).Config.Bind<bool>("BloodMoon", "BlockBeds", true, ServerSide("Während des Blutmonds (Dämmerung bis Morgengrauen) kann niemand schlafen.")); BloodMoonSpawnsPerMinute = ((BaseUnityPlugin)this).Config.Bind<float>("BloodMoon", "HordesPerMinute", 2f, ServerSide("Zusätzliche Gegnergruppen (1–3 Gegner) pro Minute und Spieler in der Blutmond-Nacht.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 20f))); BloodMoonMaxMobsPerPlayer = ((BaseUnityPlugin)this).Config.Bind<int>("BloodMoon", "MaxHordeMobsPerPlayer", 8, ServerSide("Höchstens so viele Blutmond-Gegner gleichzeitig in der Nähe eines Spielers.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50))); BloodMoonExtraStars = ((BaseUnityPlugin)this).Config.Bind<int>("BloodMoon", "ExtraStars", 1, ServerSide("Zusätzliche Sterne für feindliche Gegner in der Blutmond-Nacht (danach wieder entfernt).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10))); BloodMoonMaxLevel = ((BaseUnityPlugin)this).Config.Bind<int>("BloodMoon", "MaxLevel", 10, ServerSide("Höchste Stufe durch den Blutmond (Stufe 1 = 0 Sterne). Mit StarLevelSystem nicht über dessen MaxLevel setzen.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 200))); BloodMoonMinModifiers = ((BaseUnityPlugin)this).Config.Bind<int>("BloodMoon", "MinSpecialStars", 1, ServerSide("Nur mit StarLevelSystem: so viele Spezialsterne (Modifikatoren) hat JEDER Horden-Gegner mindestens.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 6))); BloodMoonMaxModifiers = ((BaseUnityPlugin)this).Config.Bind<int>("BloodMoon", "MaxSpecialStars", 3, ServerSide("Nur mit StarLevelSystem: höchstens so viele Spezialsterne pro Horden-Gegner.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 6))); BloodMoonHordeSize = ((BaseUnityPlugin)this).Config.Bind<float>("BloodMoon", "HordeSize", 1.8f, ServerSide("Größe der Horden-Gegner (1 = normal). Mit StarLevelSystem für alle sichtbar; SLS begrenzt mit MaximumCreatureScale.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f))); BloodMoonChampion = ((BaseUnityPlugin)this).Config.Bind<bool>("BloodMoon", "Champion", true, ServerSide("Zu Beginn der Blutmond-Hauptphase: 3 Blitze kündigen EINEN riesigen Champion an, mit ihm setzt die Bossmusik ein.")); ChampionExtraStars = ((BaseUnityPlugin)this).Config.Bind<int>("BloodMoon", "ChampionExtraStars", 8, ServerSide("Sterne des Champions (Stufe = 1 + Wert, begrenzt durch MaxLevel).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100))); ChampionSize = ((BaseUnityPlugin)this).Config.Bind<float>("BloodMoon", "ChampionSize", 3f, ServerSide("Größe des Champions (1 = normal).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f))); ChampionModifiers = ((BaseUnityPlugin)this).Config.Bind<int>("BloodMoon", "ChampionSpecialStars", 3, ServerSide("Nur mit StarLevelSystem: Spezialsterne des Champions.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 6))); BloodMoonModifiers = ((BaseUnityPlugin)this).Config.Bind<string>("BloodMoon", "Modifiers", "Fire:Major,Frost:Major,Poison:Major,Lightning:Major,ElementalChaos:Major,Splitter:Major,SoulEater:Major,Alert:Minor,StaminaDrain:Minor", ServerSide("Nur mit StarLevelSystem: Modifikatoren für Blutmond-Gegner (Name:Major/Minor/Boss). Dürfen in der Modifiers.yaml abgeschaltet sein – so entstehen Kombinationen, die sonst nie spawnen.")); AtmosphereStrength = ((BaseUnityPlugin)this).Config.Bind<float>("Atmosphere", "Strength", 1f, new ConfigDescription("Wie stark Himmel, Licht, Nebel und Wind verändert werden (0 = gar nicht, 1 = normal).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1.5f), Array.Empty<object>())); WeatherTransitionSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Atmosphere", "WeatherTransitionSeconds", 30f, new ConfigDescription("Während eines Events: Dauer der Wetter-Überblendung (z. B. zu Regen/Gewitter) in Sekunden.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 300f), Array.Empty<object>())); RainBoost = ((BaseUnityPlugin)this).Config.Bind<float>("Atmosphere", "RainBoost", 4f, new ConfigDescription("Wie viel dichter Regen/Schnee während eines Sturms fällt (1 = Vanilla).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 8f), Array.Empty<object>())); BloodMoonBrightness = ((BaseUnityPlugin)this).Config.Bind<float>("Atmosphere", "BloodMoonBrightness", 1f, new ConfigDescription("Helligkeit in der Blutmond-Nacht (1 = Standard, 1.5 = heller, 0.6 = dunkler). Nur für dich.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.3f, 3f), Array.Empty<object>())); SfxVolume = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "SfxVolume", 1f, new ConfigDescription("Lautstärke von Donner, Blitzknall, Böen, Hagel und Elmsfeuer.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), Array.Empty<object>())); EventMusicVolume = ((BaseUnityPlugin)this).Config.Bind<float>("Music", "EventMusicVolume", 0.8f, new ConfigDescription("Lautstärke der Event-Musik (zusätzlich zum Musikregler im Spiel).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); CrossfadeSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Music", "CrossfadeSeconds", 20f, new ConfigDescription("Dauer der Überblendungen zwischen Phasen in Sekunden (wird bei Zeitraffer automatisch kürzer).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 120f), Array.Empty<object>())); VanillaDuckStrength = ((BaseUnityPlugin)this).Config.Bind<float>("Music", "VanillaDuckStrength", 1f, new ConfigDescription("Wie stark die Valheim-Musik während eines Events ausgeblendet wird (1 = ganz aus, 0 = bleibt an).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); PlaceholderMusic = ((BaseUnityPlugin)this).Config.Bind<bool>("Music", "PlaceholderMusic", true, "Platzhalter-Klänge abspielen, wenn für ein Event noch keine eigene Musik vorhanden ist."); OmensVanillaFadeOut = ((BaseUnityPlugin)this).Config.Bind<float>("Music", "OmensVanillaFadeOut", 0.15f, new ConfigDescription("Phase A: bis zu diesem Anteil der Phase blendet die Valheim-Musik aus.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.01f, 0.9f), Array.Empty<object>())); OmensMusicStart = ((BaseUnityPlugin)this).Config.Bind<float>("Music", "OmensMusicStart", 0.4f, new ConfigDescription("Phase A: ab diesem Anteil der Phase setzt die Event-Musik langsam ein (davor Stille).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 0.95f), Array.Empty<object>())); RecoveryVanillaReturn = ((BaseUnityPlugin)this).Config.Bind<float>("Music", "RecoveryVanillaReturn", 0.5f, new ConfigDescription("Phase E: ab diesem Anteil der Phase kehrt die Valheim-Musik langsam zurück (davor Stille).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 0.95f), Array.Empty<object>())); LogStateChanges = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "LogStateChanges", true, "Phasenwechsel und Event-Starts ins BepInEx-Log schreiben."); } } } namespace NaturalForces.Patches { [HarmonyPatch(typeof(Bed), "CheckEnemies")] internal static class Bed_CheckEnemies_Patch { private static bool Prefix(Player human, ref bool __result) { if (!BloodMoonController.BedsBlocked) { return true; } ((Character)human).Message((MessageType)2, "$msg_bedenemiesnearby", 0, (Sprite)null, false); __result = false; return false; } } [HarmonyPatch(typeof(EnvMan), "GetEnvironmentOverride")] internal static class EnvMan_GetEnvironmentOverride_Patch { private static void Postfix(EnvMan __instance, ref string __result) { string desiredEnv = AtmosphereController.DesiredEnv; if (string.IsNullOrEmpty(desiredEnv) || !string.IsNullOrEmpty(__instance.m_debugEnv)) { return; } Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer != (Object)null) || (!((Character)localPlayer).InIntro() && !((Character)localPlayer).InInterior())) { string text = (((Object)(object)RandEventSystem.instance != (Object)null) ? RandEventSystem.instance.GetEnvOverride() : null); if (string.IsNullOrEmpty(__result) || __result == text) { __result = desiredEnv; } } } } [HarmonyPatch(typeof(EnvMan), "SetEnv")] [HarmonyBefore(new string[] { "ru.ivest.farlands.fog" })] [HarmonyPriority(600)] internal static class EnvMan_SetEnv_Patch { private static void Postfix(EnvMan __instance) { //IL_0039: 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_0045: 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_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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: 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) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: 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_00d9: 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_00fb: 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_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0132: 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_0138: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: 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_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) //IL_0261: 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_026f: Unknown result type (might be due to invalid IL or missing references) //IL_0274: 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_0283: 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_0299: Unknown result type (might be due to invalid IL or missing references) //IL_029e: Unknown result type (might be due to invalid IL or missing references) //IL_02a8: 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_02ee: Unknown result type (might be due to invalid IL or missing references) //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) float weight = AtmosphereController.Weight; AtmosphereProfile profile = AtmosphereController.Profile; if (profile == null || (weight <= 0.0001f && AtmosphereController.Flash <= 0.001f) || (Object)(object)Utils.GetMainCamera() == (Object)null || !AtmosphereController.AppliesToLocalPlayer()) { return; } RenderSettings.fogColor = Color.Lerp(RenderSettings.fogColor, profile.FogColor, weight); float fogDensity = RenderSettings.fogDensity; RenderSettings.fogDensity = Mathf.Lerp(fogDensity, Mathf.Max(fogDensity, profile.FogDensity), weight); __instance.m_sunFogColor = Color.Lerp(__instance.m_sunFogColor, profile.FogColor, weight); Color ambientLight = RenderSettings.ambientLight; Color val = new Color(ambientLight.r * profile.AmbientTint.r, ambientLight.g * profile.AmbientTint.g, ambientLight.b * profile.AmbientTint.b, ambientLight.a) * profile.AmbientBrightness; RenderSettings.ambientLight = Color.Lerp(ambientLight, val, weight); if (profile.AmbientTarget.HasValue) { RenderSettings.ambientLight = Color.Lerp(RenderSettings.ambientLight, profile.AmbientTarget.Value, weight * profile.AmbientTargetStrength); } SkyboxTint.Apply(profile, weight); Light dirLight = __instance.m_dirLight; if ((Object)(object)dirLight != (Object)null) { Color color = dirLight.color; dirLight.color = Color.Lerp(color, new Color(color.r * profile.SunTint.r, color.g * profile.SunTint.g, color.b * profile.SunTint.b, color.a), weight); dirLight.intensity *= Mathf.Lerp(1f, profile.SunBrightness, weight); } if (profile.UseBloodMoonBrightness) { float num = Mathf.Lerp(1f, Plugin.BloodMoonBrightness.Value, weight); RenderSettings.ambientLight *= num; if ((Object)(object)dirLight != (Object)null) { dirLight.intensity *= num; } } if ((Object)(object)__instance.m_clouds != (Object)null) { Material material = ((Renderer)__instance.m_clouds).material; float num2 = material.GetFloat(EnvMan.s_opacity); material.SetFloat(EnvMan.s_opacity, Mathf.Lerp(num2, Mathf.Max(num2, profile.CloudCover), weight)); } float flash = AtmosphereController.Flash; if (flash > 0.001f) { Color val2 = default(Color); ((Color)(ref val2))..ctor(0.55f, 0.6f, 0.75f); RenderSettings.ambientLight += val2 * flash * 0.8f; RenderSettings.fogColor = Color.Lerp(RenderSettings.fogColor, val2, flash * 0.6f); __instance.m_sunFogColor = Color.Lerp(__instance.m_sunFogColor, val2, flash * 0.6f); } Shader.SetGlobalColor(EnvMan.s_sunFogColor, __instance.m_sunFogColor); if ((Object)(object)dirLight != (Object)null) { Shader.SetGlobalColor(EnvMan.s_sunColor, dirLight.color * dirLight.intensity); } Shader.SetGlobalColor(EnvMan.s_ambientColor, RenderSettings.ambientLight); } } [HarmonyPatch(typeof(EnvMan), "SetTargetWind")] internal static class EnvMan_SetTargetWind_Patch { private static void Prefix(EnvMan __instance, ref Vector3 dir, ref float intensity) { //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) float weight = AtmosphereController.Weight; AtmosphereProfile profile = AtmosphereController.Profile; if (profile == null || weight <= 0.0001f || __instance.m_debugWind) { return; } intensity = Mathf.Lerp(intensity, Mathf.Max(intensity, profile.Wind), weight); Ship localShip = Ship.GetLocalShip(); if (!((Object)(object)localShip != (Object)null) || !localShip.IsWindControllActive()) { float num = Mathf.InverseLerp(profile.WindDirectionTakeover * 0.5f, profile.WindDirectionTakeover, weight); if (num > 0f) { Vector3 val = Vector3.Slerp(dir, -AtmosphereController.StormFrom, num); dir = ((Vector3)(ref val)).normalized; } } } } [HarmonyPatch(typeof(MusicMan), "UpdateMusic")] internal static class MusicManPatch { private static float _lastWritten = -1f; private static float _vanillaVolume; private static void Postfix(MusicMan __instance) { AudioSource musicSource = __instance.m_musicSource; if (!((Object)(object)musicSource == (Object)null)) { if (!Mathf.Approximately(musicSource.volume, _lastWritten)) { _vanillaVolume = musicSource.volume; } float lastWritten = (musicSource.volume = _vanillaVolume * LayeredMusicManager.VanillaGain); _lastWritten = lastWritten; } } } [HarmonyPatch(typeof(RandEventSystem), "SetRandomEvent")] internal static class RandEventSystem_SetRandomEvent_Patch { private static bool Prefix(RandomEvent ev) { if (ev == null || !Plugin.BlockRaidsDuringEvent.Value) { return true; } if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return true; } if (!EventDirector.Current.IsActive) { return true; } Plugin.Log.LogInfo((object)("Raid '" + ev.m_name + "' unterdrückt – es läuft gerade '" + EventDirector.Current.EventId + "'.")); return false; } } internal static class RaidControl { public static bool RaidRunning { get { if ((Object)(object)RandEventSystem.instance != (Object)null) { return RandEventSystem.instance.GetCurrentRandomEvent() != null; } return false; } } public static string CurrentRaidName { get { RandEventSystem instance = RandEventSystem.instance; return ((instance == null) ? null : instance.GetCurrentRandomEvent()?.m_name) ?? ""; } } public static void EndRunningRaid() { if (RaidRunning && !((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer()) { Plugin.Log.LogInfo((object)("Laufender Raid '" + CurrentRaidName + "' wird für die Naturgewalt beendet.")); RandEventSystem.instance.ResetRandomEvent(); } } } [HarmonyPatch(typeof(WearNTear), "RPC_Damage")] internal static class WearNTear_RPC_Damage_Patch { private static bool Prefix(WearNTear __instance, HitData hit) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) if (hit == null || hit.m_statusEffectHash != StrikeResolver.DamageMarker) { return true; } hit.m_statusEffectHash = 0; ZNetView nview = __instance.m_nview; if ((Object)(object)nview == (Object)null || !nview.IsValid() || !nview.IsOwner()) { return true; } float num = nview.GetZDO().GetFloat(ZDOVars.s_health, __instance.m_health); float num2 = __instance.m_health * Plugin.MinStructureHealth.Value; float num3 = num - num2; if (num3 <= 0.5f) { return false; } HitData obj = hit.Clone(); DamageModifier val = default(DamageModifier); obj.ApplyResistance(__instance.m_damages, ref val); float totalDamage = obj.GetTotalDamage(); if (totalDamage > num3 && totalDamage > 0f) { ((DamageTypes)(ref hit.m_damage)).Modify(num3 / totalDamage); } return true; } } } namespace NaturalForces.Net { internal static class NetSync { private const string RpcState = "NF_State"; private const string RpcRequest = "NF_Request"; private const string RpcReply = "NF_Reply"; private const string SyncRequest = "sync"; private static ZRoutedRpc _registeredOn; private static bool _hasInitialState; private static float _lastRequestTime = -999f; public static void Tick() { //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Invalid comparison between Unknown and I4 //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Expected O, but got Unknown ZRoutedRpc instance = ZRoutedRpc.instance; if (instance != null) { if (instance != _registeredOn) { instance.Register<ZPackage>("NF_State", (Action<long, ZPackage>)OnState); instance.Register<ZPackage>("NF_Request", (Action<long, ZPackage>)OnRequest); instance.Register<ZPackage>("NF_Reply", (Action<long, ZPackage>)OnReply); instance.Register<ZPackage>("NF_HazardReq", (Action<long, ZPackage>)StrikeResolver.OnHazardRequest); instance.Register<ZPackage>("NF_StrikeFx", (Action<long, ZPackage>)StrikeResolver.OnStrikeFx); instance.Register<ZPackage>("NF_Elmo", (Action<long, ZPackage>)ElmoFx.OnElmo); instance.Register<ZPackage>("NF_BloodSpawnReq", (Action<long, ZPackage>)BloodMoonController.OnSpawnRequest); instance.Register<ZPackage>("NF_ChampionArrived", (Action<long, ZPackage>)BloodMoonController.OnChampionArrived); _registeredOn = instance; _hasInitialState = false; } if ((Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer() && (int)ZNet.GetConnectionStatus() == 2 && !_hasInitialState && Time.unscaledTime - _lastRequestTime > 3f) { _lastRequestTime = Time.unscaledTime; ZPackage val = new ZPackage(); val.Write("sync"); val.Write(0); instance.InvokeRoutedRPC("NF_Request", new object[1] { val }); } } } public static void Reset() { _registeredOn = null; _hasInitialState = false; _lastRequestTime = -999f; } public static void BroadcastState(EventState state) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown if (ZRoutedRpc.instance != null && !((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer()) { ZPackage val = new ZPackage(); state.Write(val); ZRoutedRpc.instance.InvokeRoutedRPC(0L, "NF_State", new object[1] { val }); } } private static void SendStateTo(long peer, EventState state) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ZPackage val = new ZPackage(); state.Write(val); ZRoutedRpc.instance.InvokeRoutedRPC(peer, "NF_State", new object[1] { val }); } public static void SendCommandToServer(string[] args) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown if (ZRoutedRpc.instance != null) { ZPackage val = new ZPackage(); val.Write("cmd"); val.Write(args.Length); foreach (string text in args) { val.Write(text); } ZRoutedRpc.instance.InvokeRoutedRPC("NF_Request", new object[1] { val }); } } private static void OnState(long sender, ZPackage pkg) { if (!((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsServer()) { EventState eventState = EventState.Read(pkg); if (eventState != null) { _hasInitialState = true; EventDirector.ApplyRemoteState(eventState); } } } private static void OnRequest(long sender, ZPackage pkg) { //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected O, but got Unknown if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer()) { string text = pkg.ReadString(); int num = pkg.ReadInt(); string[] array = new string[num]; for (int i = 0; i < num; i++) { array[i] = pkg.ReadString(); } if (text == "sync") { SendStateTo(sender, EventDirector.Current); } else if (text == "cmd") { string text2 = (IsAdmin(sender) ? EventDirector.ExecuteServerCommand(array, sender) : "Keine Berechtigung: nur Admins (adminlist.txt) dürfen Events steuern."); ZPackage val = new ZPackage(); val.Write(text2); ZRoutedRpc.instance.InvokeRoutedRPC(sender, "NF_Reply", new object[1] { val }); } } } private static void OnReply(long sender, ZPackage pkg) { string text = pkg.ReadString(); if ((Object)(object)Console.instance != (Object)null) { Console.instance.Print("[NF] " + text); } } private static bool IsAdmin(long sender) { if (sender == ZRoutedRpc.instance.m_id) { return true; } ZNetPeer peer = ZNet.instance.GetPeer(sender); if (peer?.m_socket == null) { return false; } return ZNet.instance.IsAdmin(peer.m_socket.GetHostName()); } } } namespace NaturalForces.Hazards { public static class DistantThunder { private static bool Headless { get { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 if ((int)SystemInfo.graphicsDeviceType != 4) { if ((Object)(object)ZNet.instance != (Object)null) { return ZNet.instance.IsDedicated(); } return false; } return true; } } public static void Tick() { //IL_0186: 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_01a0: 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_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: 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_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) //IL_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_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_0206: 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_0271: Unknown result type (might be due to invalid IL or missing references) if (Headless) { return; } EventState current = EventDirector.Current; if (!current.IsActive || current.Definition?.Lightning == null) { return; } Camera mainCamera = Utils.GetMainCamera(); if ((Object)(object)mainCamera == (Object)null) { return; } float num = current.PhaseProgress(EventDirector.Now, EventDirector.DayLengthSec); float num2 = 1f; bool flag = false; float num3; float num4; switch (current.Phase) { default: return; case EventPhase.Omens: { if (num < 0.35f) { return; } float num5 = Mathf.InverseLerp(0.35f, 1f, num); num3 = Mathf.Lerp(0.6f, 3f, num5); num4 = Mathf.Lerp(4500f, 3000f, num5); num2 = 0.35f; break; } case EventPhase.Intensify: num3 = Mathf.Lerp(3f, 7f, num); num4 = Mathf.Lerp(2800f, 1200f, num); num2 = Mathf.Lerp(0.6f, 1f, num); break; case EventPhase.Peak: num3 = 5f; num4 = Random.Range(600f, 1500f); break; case EventPhase.Fading: num3 = Mathf.Lerp(6f, 2f, num); num4 = Mathf.Lerp(900f, 2500f, num); flag = true; break; case EventPhase.Recovery: if (num > 0.4f) { return; } num3 = Mathf.Lerp(2f, 0.3f, num / 0.4f); num4 = 3500f; num2 = 0.5f; flag = true; break; } if (!(Random.value >= num3 / 60f * Time.deltaTime)) { Vector3 val = AtmosphereController.StormFrom * (flag ? (-1f) : 1f); float num6 = ((current.Phase == EventPhase.Peak) ? 180f : 35f); Vector3 val2 = Quaternion.Euler(0f, Random.Range(0f - num6, num6), 0f) * val; Vector3 pos = ((Component)mainCamera).transform.position + val2 * 250f + Vector3.up * 80f; float volume = Mathf.Clamp(500f / num4, 0.08f, 0.9f) * num2; float delay = Mathf.Min(num4 / 343f, 8f) * Random.Range(0.6f, 1f); AtmosphereController.AddFlash(Mathf.Clamp(250f / num4, 0.04f, 0.3f) * num2); SoundBank.PlayAt("thunder", pos, volume, delay, 50f, 2000f, 0.2f); } } } public static class ElmoFx { internal class FollowTransform : MonoBehaviour { public Transform Target; private void LateUpdate() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Target != (Object)null) { ((Component)this).transform.position = Target.position; } } } internal class ElmoFlicker : MonoBehaviour { public Light Light; private void Update() { if ((Object)(object)Light != (Object)null) { Light.intensity = 0.8f + Mathf.PerlinNoise(Time.time * 12f, 0.3f) * 1.4f; } } } public const string RpcElmo = "NF_Elmo"; private static bool _localOn; private static readonly Dictionary<ZDOID, GameObject> _active = new Dictionary<ZDOID, GameObject>(); public static void SetLocal(bool on) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_002d: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; if (on != _localOn && !((Object)(object)localPlayer == (Object)null) && ZRoutedRpc.instance != null) { _localOn = on; ZPackage val = new ZPackage(); val.Write(((Character)localPlayer).GetZDOID()); val.Write(on); ZRoutedRpc.instance.InvokeRoutedRPC(0L, "NF_Elmo", new object[1] { val }); } } public static void OnElmo(long sender, ZPackage pkg) { //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_001b: 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) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) ZDOID val = pkg.ReadZDOID(); bool flag = pkg.ReadBool(); if (FxUtil.Headless) { return; } if (_active.TryGetValue(val, out var value)) { if ((Object)(object)value != (Object)null) { Object.Destroy((Object)(object)value); } _active.Remove(val); } if (!flag) { return; } foreach (Player allPlayer in Player.GetAllPlayers()) { if (!((Object)(object)allPlayer == (Object)null) && !(((Character)allPlayer).GetZDOID() != val)) { _active[val] = Create(allPlayer); break; } } } private static GameObject Create(Player player) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("NF_ElmsFire"); val.transform.SetParent(((Component)player).transform, false); VisEquipment component = ((Component)player).GetComponent<VisEquipment>(); AddSparks(val, ((Object)(object)component != (Object)null && (Object)(object)component.m_rightHand != (Object)null) ? component.m_rightHand : ((Component)player).transform, 0.35f); AddSparks(val, ((Object)(object)component != (Object)null && (Object)(object)component.m_leftHand != (Object)null) ? component.m_leftHand : ((Component)player).transform, 0.25f); AddSparks(val, ((Object)(object)((Character)player).m_head != (Object)null) ? ((Character)player).m_head : ((Component)player).transform, 0.3f); Light val2 = new GameObject("glow").AddComponent<Light>(); ((Component)val2).transform.SetParent(val.transform, false); ((Component)val2).transform.localPosition = Vector3.up * 1.6f; val2.type = (LightType)2; val2.color = new Color(0.45f, 0.65f, 1f); val2.range = 4f; val2.intensity = 1.2f; val2.shadows = (LightShadows)0; val.AddComponent<ElmoFlicker>().Light = val2; AudioClip val3 = SoundBank.Random("elmo"); if ((Object)(object)val3 != (Object)null) { AudioSource val4 = val.AddComponent<AudioSource>(); val4.clip = val3; val4.loop = true; val4.spatialBlend = 1f; val4.minDistance = 2f; val4.maxDistance = 25f; val4.rolloffMode = (AudioRolloffMode)1; val4.volume = 0.9f * Plugin.SfxVolume.Value; if ((Object)(object)AudioMan.instance != (Object)null) { val4.outputAudioMixerGroup = AudioMan.instance.m_ambientMixer; } val4.Play(); } return val; } private static void AddSparks(GameObject root, Transform anchor, float rate) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_0049: 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_0063: 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_008f: 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_00c8: 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_00ef: 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) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0145: 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) Material val = FxUtil.SoftDot(); if (!((Object)(object)val == (Object)null)) { GameObject val2 = new GameObject("sparks"); val2.transform.SetParent(root.transform, false); val2.AddComponent<FollowTransform>().Target = anchor; ParticleSystem val3 = val2.AddComponent<ParticleSystem>(); val3.Stop(true, (ParticleSystemStopBehavior)0); MainModule main = val3.main; ((MainModule)(ref main)).loop = true; ((MainModule)(ref main)).startLifetime = new MinMaxCurve(0.08f, 0.25f); ((MainModule)(ref main)).startSpeed = new MinMaxCurve(0.2f, 1.2f); ((MainModule)(ref main)).startSize = new MinMaxCurve(0.03f, 0.09f); ((MainModule)(ref main)).startColor = new MinMaxGradient(new Color(0.6f, 0.8f, 1f, 1f), new Color(0.85f, 0.95f, 1f, 1f)); ((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1; ((MainModule)(ref main)).maxParticles = 80; ((MainModule)(ref main)).gravityModifier = MinMaxCurve.op_Implicit(-0.05f); EmissionModule emission = val3.emission; ((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(60f * rate); ((EmissionModule)(ref emission)).SetBursts((Burst[])(object)new Burst[1] { new Burst(0f, (short)3, (short)8, 0, Random.Range(0.3f, 0.7f)) }); ShapeModule shape = val3.shape; ((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)0; ((ShapeModule)(ref shape)).radius = 0.12f; ParticleSystemRenderer component = val2.GetComponent<ParticleSystemRenderer>(); ((Renderer)component).material = val; component.renderMode = (ParticleSystemRenderMode)0; val3.Play(); } } } internal static class FxUtil { private static Material _softDot; public static bool Headless { get { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 if ((int)SystemInfo.graphicsDeviceType != 4) { if ((Object)(object)ZNet.instance != (Object)null) { return ZNet.instance.IsDedicated(); } return false; } return true; } } public static Material SoftDot() { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Expected O, but got Unknown //IL_00b3: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_softDot != (Object)null) { return _softDot; } Shader val = Shader.Find("Sprites/Default"); if ((Object)(object)val == (Object)null) { return null; } Texture2D val2 = new Texture2D(32, 32, (TextureFormat)4, false) { wrapMode = (TextureWrapMode)1 }; for (int i = 0; i < 32; i++) { for (int j = 0; j < 32; j++) { float num = ((float)j + 0.5f) / 32f * 2f - 1f; float num2 = ((float)i + 0.5f) / 32f * 2f - 1f; float num3 = Mathf.Clamp01(1f - Mathf.Sqrt(num * num + num2 * num2)); val2.SetPixel(j, i, new Color(1f, 1f, 1f, num3 * num3)); } } val2.Apply(); Object.DontDestroyOnLoad((Object)(object)val2); _softDot = new Material(val) { mainTexture = (Texture)(object)val2 }; Object.DontDestroyOnLoad((Object)(object)_softDot); return _softDot; } } public class HailProfile { public EventPhase Phase = EventPhase.Peak; public float From = 0.35f; public float To = 0.65f; public float Ramp = 0.06f; public float IntensityFor(EventPhase phase, float progress) { if (phase != Phase || progress < From || progress > To) { return 0f; } float num = Mathf.InverseLerp(From, From + Ramp, progress); float num2 = Mathf.InverseLerp(To, To - Ramp, progress); return Mathf.SmoothStep(0f, 1f, Mathf.Min(num, num2)); } } public static class HailController { private static GameObject _root; private static ParticleSystem _ps; private static AudioSource _open; private static AudioSource _roof; private static float _intensity; private static float _shelterBlend; private static float _damageTimer; public static float Intensity => _intensity; public static void Tick() { if (!FxUtil.Headless) { EventState current = EventDirector.Current; float num = ((!current.IsActive) ? null : current.Definition?.Hail)?.IntensityFor(current.Phase, current.PhaseProgress(EventDirector.Now, EventDirector.DayLengthSec)) ?? 0f; Player localPlayer = Player.m_localPlayer; Camera mainCamera = Utils.GetMainCamera(); bool flag = (Object)(object)localPlayer != (Object)null && ((Character)localPlayer).InInterior(); if ((Object)(object)mainCamera == (Object)null || flag) { num = 0f; } _intensity = Mathf.MoveTowards(_intensity, num * Plugin.HailAmount.Value, Time.deltaTime / 3f); if (!(_intensity <= 0f) || !((Object)(object)_root == (Object)null)) { Ensure(); UpdateParticles(mainCamera); UpdateSound(localPlayer); UpdateDamage(localPlayer); } } } private static void Ensure() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown //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_006e: 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_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_0191: 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_01a5: 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_0212: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_0239: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_root != (Object)null)) { _root = new GameObject("NF_Hail"); Object.DontDestroyOnLoad((Object)(object)_root); Material val = FxUtil.SoftDot(); if ((Object)(object)val != (Object)null) { _ps = _root.AddComponent<ParticleSystem>(); _ps.Stop(true, (ParticleSystemStopBehavior)0); MainModule main = _ps.main; ((MainModule)(ref main)).loop = true; ((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(2.2f); ((MainModule)(ref main)).startSpeed = MinMaxCurve.op_Implicit(0f); ((MainModule)(ref main)).startSize = new MinMaxCurve(0.035f, 0.075f); ((MainModule)(ref main)).startColor = new MinMaxGradient(new Color(0.85f, 0.9f, 0.95f, 0.9f), new Color(1f, 1f, 1f, 1f)); ((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1; ((MainModule)(ref main)).maxParticles = 4000; ((MainModule)(ref main)).gravityModifier = MinMaxCurve.op_Implicit(1.2f); EmissionModule emission = _ps.emission; ((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(0f); ShapeModule shape = _ps.shape; ((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)5; ((ShapeModule)(ref shape)).scale = new Vector3(45f, 1f, 45f); VelocityOverLifetimeModule velocityOverLifetime = _ps.velocityOverLifetime; ((VelocityOverLifetimeModule)(ref velocityOverLifetime)).enabled = true; ((VelocityOverLifetimeModule)(ref velocityOverLifetime)).space = (ParticleSystemSimulationSpace)1; ((VelocityOverLifetimeModule)(ref velocityOverLifetime)).x = new MinMaxCurve(0f); ((VelocityOverLifetimeModule)(ref velocityOverLifetime)).y = new MinMaxCurve(-22f); ((VelocityOverLifetimeModule)(ref velocityOverLifetime)).z = new MinMaxCurve(0f); CollisionModule collision = _ps.collision; ((CollisionModule)(ref collision)).enabled = true; ((CollisionModule)(ref collision)).type = (ParticleSystemCollisionType)1; ((CollisionModule)(ref collision)).mode = (ParticleSystemCollisionMode)0; ((CollisionModule)(ref collision)).quality = (ParticleSystemCollisionQuality)1; ((CollisionModule)(ref collision)).collidesWith = LayerMask.op_Implicit(LayerMask.GetMask(new string[5] { "Default", "static_solid", "piece", "terrain", "vehicle" })); ((CollisionModule)(ref collision)).bounce = new MinMaxCurve(0.15f, 0.4f); ((CollisionModule)(ref collision)).dampen = new MinMaxCurve(0.3f, 0.6f); ((CollisionModule)(ref collision)).lifetimeLoss = MinMaxCurve.op_Implicit(0.45f); ParticleSystemRenderer component = _root.GetComponent<ParticleSystemRenderer>(); ((Renderer)component).material = val; component.renderMode = (ParticleSystemRenderMode)1; component.velocityScale = 0.012f; component.lengthScale = 1f; _ps.Play(); } _open = AddLoop("hail_open"); _roof = AddLoop("hail_roof"); } } private static AudioSource AddLoop(string bank) { AudioSource val = _root.AddComponent<AudioSource>(); val.clip = SoundBank.Random(bank); val.loop = true; val.spatialBlend = 0f; val.volume = 0f; if ((Object)(object)AudioMan.instance != (Object)null) { val.outputAudioMixerGroup = AudioMan.instance.m_ambientMixer; } return val; } private static void UpdateParticles(Camera cam) { //IL_004a: 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_005d: 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_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0093: 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_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_ps == (Object)null)) { if ((Object)(object)cam != (Object)null) { _root.transform.position = ((Component)cam).transform.position + Vector3.up * 22f; } EmissionModule emission = _ps.emission; ((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(2200f * _intensity); Vector3 val = (((Object)(object)EnvMan.instance != (Object)null) ? EnvMan.instance.GetWindForce() : Vector3.zero); VelocityOverLifetimeModule velocityOverLifetime = _ps.velocityOverLifetime; ((VelocityOverLifetimeModule)(ref velocityOverLifetime)).x = new MinMaxCurve(val.x * 9f); ((VelocityOverLifetimeModule)(ref velocityOverLifetime)).y = new MinMaxCurve(-22f); ((VelocityOverLifetimeModule)(ref velocityOverLifetime)).z = new MinMaxCurve(val.z * 9f); } } private static void UpdateSound(Player player) { bool flag = (Object)(object)player != (Object)null && player.InShelter(); _shelterBlend = Mathf.MoveTowards(_shelterBlend, flag ? 1f : 0f, Time.deltaTime * 2f); float num = _intensity * Plugin.SfxVolume.Value; SetLoop(_open, num * (1f - _shelterBlend) * 0.9f); SetLoop(_roof, num * _shelterBlend); } private static void SetLoop(AudioSource src, float volume) { if (!((Object)(object)src == (Object)null)) { if ((Object)(object)src.clip == (Object)null) { src.clip = SoundBank.Random(((Object)(object)src == (Object)(object)_open) ? "hail_open" : "hail_roof"); } src.volume = volume; if (volume > 0.001f && !src.isPlaying && (Object)(object)src.clip != (Object)null) { src.Play(); } else if (volume <= 0.001f && src.isPlaying) { src.Stop(); } } } private static void UpdateDamage(Player player) { //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null || ((Character)player).IsDead() || _intensity < 0.3f) { _damageTimer = 0f; return; } if (player.InShelter() || ((Character)player).InInterior()) { _damageTimer = 0f; return; } _damageTimer += Time.deltaTime; if (!(_damageTimer < 1f)) { _damageTimer = 0f; float num = Plugin.HailDamagePerSecond.Value * _intensity; if (!(num <= 0f)) { HitData val = new HitData(); val.m_damage.m_blunt = num; val.m_point = ((Character)player).GetHeadPoint(); val.m_dir = Vector3.down; ((Character)player).Damage(val); } } } } public static class LightningDirector { public const string RpcHazardRequest = "NF_HazardReq"; public const int KindStrike = 0; public const int KindGust = 1; private static readonly List<long> _targets = new List<long>(); public static void Tick() { if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || ZRoutedRpc.instance == null) { return; } EventState current = EventDirector.Current; LightningProfile lightningProfile = ((!current.IsActive) ? null : current.Definition?.Lightning); if (lightningProfile == null) { return; } double now = EventDirector.Now; double dayLengthSec = EventDirector.DayLengthSec; LightningProfile.Rates rates = lightningProfile.For(current.Phase, current.PhaseProgress(now, dayLengthSec), Plugin.LightningAmount.Value); if (rates.StrikesPerMinute <= 0f && rates.GustsPerMinute <= 0f) { return; } float deltaTime = Time.deltaTime; CollectTargets(); foreach (long target in _targets) { if (Random.value < rates.StrikesPerMinute / 60f * deltaTime) { bool targeted = Random.value < rates.TargetedShare; SendRequest(target, 0, targeted, rates.FrontDistance, rates.Spread); } if (Random.value < rates.GustsPerMinute / 60f * deltaTime) { SendRequest(target, 1, targeted: false, 20f, 80f); } } } private static void CollectTargets() { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) _targets.Clear(); if (!ZNet.instance.IsDedicated() && (Object)(object)Player.m_localPlayer != (Object)null) { _targets.Add(ZRoutedRpc.instance.m_id); } foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { if (peer != null && peer.m_characterID != ZDOID.None) { _targets.Add(peer.m_uid); } } } private static void SendRequest(long peer, int kind, bool targeted, float a, float b) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ZPackage val = new ZPackage(); val.Write(kind); val.Write(targeted); val.Write(a); val.Write(b); val.Write(Random.Range(int.MinValue, int.MaxValue)); ZRoutedRpc.instance.InvokeRoutedRPC(peer, "NF_HazardReq", new object[1] { val }); } public static string DebugStrike(long sender, string[] args) { if (ZRoutedRpc.instance == null) { return "Keine Verbindung."; } switch ((args.Length >= 2) ? args[1].ToLowerInvariant() : "me") { case "gust": SendRequest(sender, 1, targeted: false, 15f, 50f); return "Sturmböe ausgelöst."; case "near": SendRequest(sender, 0, targeted: false, 0f, 35f); return "Blitz in deiner Nähe ausgelöst."; case "hit": SendRequest(sender, 0, targeted: true, -1f, 0f); return "Direkter Treffer auf dich ausgelöst (ohne Warnungen)!"; case "far": SendRequest(sender, 0, targeted: false, 700f, 150f); return "Blitz am Horizont (aus der Sturmrichtung) ausgelöst."; default: SendRequest(sender, 0, targeted: true, 0f, 0f); return "Gezielter Blitz ausgelöst – erst Warnungen daneben, Treffer erst nach längerer Zeit im Freien während eines Sturms ('nf strike hit' trifft sofort)."; } } } public static class LightningFx { private const float SpeedOfSound = 343f; private static Material _boltMaterial; private static bool Headless { get { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 if ((int)SystemInfo.graphicsDeviceType != 4) { if ((Object)(object)ZNet.instance != (Object)null) { return ZNet.instance.IsDedicated(); } return false; } return true; } } public static void PlayStrike(Vector3 pos) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //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_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0082: 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_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) if (!Headless) { Camera mainCamera = Utils.GetMainCamera(); float num = (((Object)(object)mainCamera != (Object)null) ? Vector3.Distance(((Component)mainCamera).transform.position, pos) : 0f); float num2 = num / 343f; GameObject val = new GameObject("NF_Lightning"); val.transform.position = pos; float widthScale = Mathf.Max(1f, num / 150f); float skyFlash = Mathf.Lerp(1f, 0.2f, Mathf.Clamp01(num / 1200f)); val.AddComponent<LightningBolt>().Init(pos, GetMaterial(), widthScale, skyFlash); if (num < 350f) { SoundBank.PlayAt("lightning_crack", pos, 1f, num2, 15f, 450f); } SoundBank.PlayAt("thunder", pos, 0.9f, num2 + 0.15f, 60f, 1500f, 0.15f); if ((Object)(object)GameCamera.instance != (Object)null && num < 120f) { GameCamera.instance.AddShake(pos, 120f, Mathf.Lerp(3f, 0.5f, num / 120f), false); } } } public static void PlayGust(Vector3 pos) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (!Headless) { SoundBank.PlayAt("gust", pos, 1f, 0f, 10f, 160f, 0.15f); } } private static Material GetMaterial() { //IL_0061: 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_007b: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Expected O, but got Unknown if ((Object)(object)_boltMaterial != (Object)null) { return _boltMaterial; } Shader val = Shader.Find("Sprites/Default"); if ((Object)(object)val == (Object)null) { val = Shader.Find("Legacy Shaders/Particles/Additive"); } if ((Object)(object)val == (Object)null) { val = Shader.Find("Unlit/Color"); } if ((Object)(object)val == (Object)null) { Plugin.Log.LogWarning((object)"Kein Shader für den Blitzstrahl gefunden – es gibt nur Lichtblitz und Donner."); return null; } _boltMaterial = new Material(val) { color = new Color(0.85f, 0.9f, 1f, 1f) }; Object.DontDestroyOnLoad((Object)(object)_boltMaterial); return _boltMaterial; } } internal class LightningBolt : MonoBehaviour { private const float Lifetime = 0.7f; private readonly List<LineRenderer> _lines = new List<LineRenderer>(); private Light _light; private float _age; private float[] _flashes; private float _skyFlash; public void Init(Vector3 ground, Material mat, float widthScale, float skyFlash) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: 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) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00da: 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_0174: 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_017f: 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) _skyFlash = skyFlash; List<Vector3> list = BuildPath(ground + new Vector3(Random.Range(-40f, 40f), Random.Range(220f, 320f), Random.Range(-40f, 40f)), ground, 22, 9f); if ((Object)(object)mat != (Object)null) { AddLine(list, 1.6f * widthScale, 0.4f, mat); } int num = (((Object)(object)mat != (Object)null) ? Random.Range(2, 5) : 0); for (int i = 0; i < num; i++) { int index = Random.Range(3, list.Count - 6); Vector3 val = list[index]; Vector3 b = val + new Vector3(Random.Range(-45f, 45f), 0f - Random.Range(30f, 90f), Random.Range(-45f, 45f)); AddLine(BuildPath(val, b, 8, 5f), 0.7f * widthScale, 0.15f, mat); } _light = ((Component)this).gameObject.AddComponent<Light>(); _light.type = (LightType)2; _light.color = new Color(0.8f, 0.85f, 1f); _light.range = 180f; _light.intensity = 0f; _light.shadows = (LightShadows)0; ((Component)_light).transform.position = ground + Vector3.up * 25f; _flashes = new float[3] { 0f, Random.Range(0.08f, 0.14f), Random.Range(0.22f, 0.32f) }; } private static List<Vector3> BuildPath(Vector3 a, Vector3 b, int segments, float jitter) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //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_0066: 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_0049: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: 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) List<Vector3> list = new List<Vector3>(segments + 1); for (int i = 0; i <= segments; i++) { float num = (float)i / (float)segments; Vector3 val = Vector3.Lerp(a, b, num); if (i > 0 && i < segments) { val += new Vector3(Random.Range(0f - jitter, jitter), Random.Range((0f - jitter) * 0.3f, jitter * 0.3f), Random.Range(0f - jitter, jitter)) * Mathf.Sin(num * (float)Math.PI); } list.Add(val); } return list; } private void AddLine(List<Vector3> pts, float width, float endWidth, Material mat) { //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_0085: 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) GameObject val = new GameObject("bolt"); val.transform.SetParent(((Component)this).transform, false); LineRenderer val2 = val.AddComponent<LineRenderer>(); val2.useWorldSpace = true; val2.positionCount = pts.Count; val2.SetPositions(pts.ToArray()); val2.startWidth = width * 0.6f; val2.endWidth = width; val2.widthMultiplier = 1f; ((Renderer)val2).material = mat; Color val3 = default(Color); ((Color)(ref val3))..ctor(0.85f, 0.9f, 1f, 1f); val2.endColor = val3; val2.startColor = val3; ((Renderer)val2).shadowCastingMode = (ShadowCastingMode)0; ((Renderer)val2).receiveShadows = false; val2.numCapVertices = 2; _lines.Add(val2); } private void Update() { //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) _age += Time.deltaTime; if (_age >= 0.7f) { Object.Destroy((Object)(object)((Component)this).gameObject); return; } float num = 0f; float[] flashes = _flashes; foreach (float num2 in flashes) { float num3 = _age - num2; if (num3 >= 0f) { num = Mathf.Max(num, Mathf.Exp((0f - num3) * 18f)); } } num *= 1f - _age / 0.7f; Color val = default(Color); foreach (LineRenderer line in _lines) { ((Color)(ref val))..ctor(0.85f, 0.9f, 1f, Mathf.Clamp01(num * 1.4f)); Color startColor = (line.endColor = val); line.startColor = startColor; } if ((Object)(object)_light != (Object)null) { _light.intensity = num * 9f; } AtmosphereController.AddFlash(num * _skyFlash); } } public class LightningProfile { public struct Rates { public float StrikesPerMinute; public float FrontDistance; public float Spread; public float TargetedShare; public float GustsPerMinute; } public float HorizonPerMinute = 10f; public float PeakPerMinute = 60f; public float FadingPerMinute = 20f; public float TargetedShareMax = 0.5f; public float GustsPerMinute = 5f; public float ApproachStartDistance = 1100f; public float ArrivalDistance = 350f; public float LeaveDistance = 900f; public Rates For(EventPhase phase, float progress, float amount) { Rates result = default(Rates); switch (phase) { case EventPhase.Intensify: { float num2 = Mathf.InverseLerp(0.8f, 1f, progress); result.GustsPerMinute = GustsPerMinute * 0.2f * Mathf.InverseLerp(0.4f, 1f, progress); if (!(num2 <= 0f)) { result.StrikesPerMinute = Mathf.Lerp(3f, HorizonPerMinute, num2); result.FrontDistance = Mathf.Lerp(ApproachStartDistance * 0.6f, ArrivalDistance, num2); result.Spread = 260f; } break; } case EventPhase.Peak: { float num = Mathf.SmoothStep(0f, 1f, Mathf.Clamp01(progress / 0.3f)); result.FrontDistance = Mathf.Lerp(ArrivalDistance, 0f, num); result.Spread = Mathf.Lerp(200f, 110f, num); result.StrikesPerMinute = Mathf.Lerp(HorizonPerMinute * 1.5f, PeakPerMinute, num); result.TargetedShare = ((progress < 0.3f) ? 0f : Mathf.Lerp(0.08f, TargetedShareMax, Mathf.InverseLerp(0.3f, 1f, progress))); result.GustsPerMinute = GustsPerMinute * Mathf.Lerp(0.3f, 1f, num); break; } case EventPhase.Fading: result.FrontDistance = Mathf.Lerp(0f, 0f - LeaveDistance, progress); result.Spread = Mathf.Lerp(120f, 300f, progress); result.StrikesPerMinute = Mathf.Lerp(FadingPerMinute, 2f, progress); result.GustsPerMinute = GustsPerMinute * 0.3f * (1f - progress); break; } result.StrikesPerMinute *= amount; return result; } } public static class StrikeResolver { public const string RpcStrikeFx = "NF_StrikeFx"; public static readonly int DamageMarker = StringExtensionMethods.GetStableHashCode("NF_LightningDamage"); private static int _surfaceMask; private static readonly Collider[] _overlap = (Collider[])(object)new Collider[128]; private static float _exposedSeconds; private static float _shelteredSeconds; private static int _nearMisses; private static float _elmoSeconds; private static int SurfaceMask { get { if (_surfaceMask == 0) { return _surfaceMask = LayerMask.GetMask(new string[7] { "Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "vehicle" }); } return _surfaceMask; } } private static bool WarningsComplete { get { if (_nearMisses >= Plugin.NearMissesBeforeHit.Value) { return _exposedSeconds >= Plugin.ExposureBeforeHit.Value; } return false; } } public static void OnHazardRequest(long sender, ZPackage pkg) { int num = pkg.ReadInt(); bool targeted = pkg.ReadBool(); float num2 = pkg.ReadSingle(); float num3 = pkg.ReadSingle(); int seed = pkg.ReadInt(); Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null) && !((Character)localPlayer).IsDead() && !((Character)localPlayer).InInterior() && !((Character)localPlayer).InIntro()) { Random rng = new Random(seed); if (num == 1) { ResolveGust(localPlayer, rng, num2, num3); } else { ResolveStrike(localPlayer, rng, targeted, num2, num3); } } } public static void Tick() { Player localPlayer = Player.m_localPlayer; EventState current = EventDirector.Current; if (!((Object)(object)localPlayer != (Object)null) || !current.IsActive || current.Definition?.Lightning == null || (current.Phase != EventPhase.Peak && current.Phase != EventPhase.Fading)) { _exposedSeconds = 0f; _nearMisses = 0; _elmoSeconds = 0f; ElmoFx.SetLocal(on: false); return; } float deltaTime = Time.deltaTime; int num; if (!localPlayer.InShelter()) { num = (((Character)localPlayer).InInterior() ? 1 : 0); if (num == 0) { _shelteredSeconds = 0f; _exposedSeconds += deltaTime; goto IL_00d8; } } else { num = 1; } _shelteredSeconds += deltaTime; _exposedSeconds = Mathf.Max(0f, _exposedSeconds - deltaTime * 2f); if (_shelteredSeconds > 5f) { _nearMisses = 0; } goto IL_00d8; IL_00f3: float elmoSeconds; _elmoSeconds = elmoSeconds; int num2; ElmoFx.SetLocal((byte)num2 != 0); return; IL_00d8: if (num == 0) { num2 = (WarningsComplete ? 1 : 0); if (num2 != 0) { elmoSeconds = _elmoSeconds + deltaTime; goto IL_00f3; } } else { num2 = 0; } elmoSeconds = 0f; goto IL_00f3; } private static Vector3 TargetedOffset(Player player, Random rng) { //IL_0009: 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_0062: Unknown result type (might be due to invalid IL or missing references) //IL_007b: 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_00b9: Unknown result type (might be due to invalid IL or missing references) if (player.InShelter()) { return RandomHorizontal(rng) * (float)(rng.NextDouble() * 1.5); } if (!WarningsComplete || _elmoSeconds < Plugin.ElmoSecondsBeforeHit.Value) { if (!WarningsComplete) { _nearMisses++; } float num = Plugin.LightningRadius.Value + 1.5f; return RandomHorizontal(rng) * Mathf.Lerp(num, num + 4f, (float)rng.NextDouble()); } _nearMisses = Mathf.Max(0, Plugin.NearMissesBeforeHit.Value - 2); _elmoSeconds = 0f; return RandomHorizontal(rng) * (float)(rng.NextDouble() * 1.5); } public static string FormatStatus() { return $"Blitzgefahr: {_exposedSeconds:0} s ungeschützt, {_nearMisses}/{Plugin.NearMissesBeforeHit.Value} Warnungen" + ((_elmoSeconds > 0f) ? $", ELMSFEUER seit {_elmoSeconds:0.0} s (Treffer ab {Plugin.ElmoSecondsBeforeHit.Value:0} s)" : ""); } private static void ResolveStrike(Player player, Random rng, bool targeted, float front, float spread) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_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_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: 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_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0028: 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_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: 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_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0131: 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_013e: Unknown result type (might be due to invalid IL or missing references) //IL_00df: 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_00f0: 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) Vector3 position = ((Component)player).transform.position; Vector3 val; float spread2; if (targeted) { val = ((front < 0f) ? (position + RandomHorizontal(rng) * (float)(rng.NextDouble() * 1.0)) : (position + TargetedOffset(player, rng))); spread2 = 0f; } else { Vector3 stormFrom = AtmosphereController.StormFrom; Vector3 val2 = default(Vector3); ((Vector3)(ref val2))..ctor(stormFrom.z, 0f, 0f - stormFrom.x); float num = front + ((float)rng.NextDouble() - 0.5f) * spread * 1.2f; float num2 = ((float)rng.NextDouble() * 2f - 1f) * spread; val = position + stormFrom * num + val2 * num2; spread2 = 8f; } if (!FindHighestSurface(val, spread2, rng, out var best)) { if (WorldGenerator.instance == null) { return; } ((Vector3)(ref best))..ctor(val.x, Mathf.Max(WorldGenerator.instance.GetHeight(val.x, val.z), ((Object)(object)ZoneSystem.instance != (Object)null) ? ZoneSystem.instance.m_waterLevel : 30f), val.z); } Broadcast(0, best); if (Vector3.Distance(best, position) < 200f) { ApplyStrikeDamage(best); } } private static bool FindHighestSurface(Vector3 center, float spread, Random rng, out Vector3 best) { //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_0021: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0047: 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_0059: 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_0064: 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_009c: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) best = Vector3.zero; bool flag = false; int num = ((!(spread > 0f)) ? 1 : 4); RaycastHit val2 = default(RaycastHit); for (int i = 0; i < num; i++) { Vector3 val = center + ((i == 0) ? Vector3.zero : (RandomHorizontal(rng) * (float)(rng.NextDouble() * (double)spread))); if (Physics.Raycast(new Vector3(val.x, val.y + 300f, val.z), Vector3.down, ref val2, 600f, SurfaceMask, (QueryTriggerInteraction)1)) { if (!flag || ((RaycastHit)(ref val2)).point.y > best.y) { best = ((RaycastHit)(ref val2)).point; } flag = true; } } if (flag && (Object)(object)ZoneSystem.instance != (Object)null) { best.y = Mathf.Max(best.y, ZoneSystem.instance.m_waterLevel); } return flag; } private static void ApplyStrikeDamage(Vector3 pos) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Expected O, but got Unknown //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_0160: 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_0169: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: 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_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e3: Expected O, but got Unknown //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) float value = Plugin.LightningRadius.Value; int num = Physics.OverlapSphereNonAlloc(pos, value, _overlap, -1, (QueryTriggerInteraction)1); HashSet<Character> hashSet = new HashSet<Character>(); HashSet<WearNTear> hashSet2 = new HashSet<WearNTear>(); HashSet<TreeBase> hashSet3 = new HashSet<TreeBase>(); for (int i = 0; i < num; i++) { Collider val = _overlap[i]; if ((Object)(object)val == (Object)null) { continue; } Character componentInParent = ((Component)val).GetComponentInParent<Character>(); if ((Object)(object)componentInParent != (Object)null) { hashSet.Add(componentInParent); continue; } WearNTear componentInParent2 = ((Component)val).GetComponentInParent<WearNTear>(); if ((Object)(object)componentInParent2 != (Object)null) { hashSet2.Add(componentInParent2); continue; } TreeBase componentInParent3 = ((Component)val).GetComponentInParent<TreeBase>(); if ((Object)(object)componentInParent3 != (Object)null) { hashSet3.Add(componentInParent3); } } foreach (Character item in hashSet) { if (item.IsDead()) { continue; } Player val2 = (Player)(object)((item is Player) ? item : null); if (val2 == null || (!val2.InShelter() && !((Character)val2).InInterior())) { float num2 = Falloff(((Component)item).transform.position, pos, value); if (!(num2 <= 0f)) { HitData val3 = new HitData(); val3.m_damage.m_lightning = Plugin.LightningCharacterDamage.Value * num2; val3.m_point = ((Component)item).transform.position + Vector3.up; Vector3 val4 = ((Component)item).transform.position - pos; val3.m_dir = ((Vector3)(ref val4)).normalized; val3.m_pushForce = 60f * num2; item.Damage(val3); } } } foreach (WearNTear item2 in hashSet2) { float num3 = Falloff(((Component)item2).transform.position, pos, value + 1f); if (!(num3 <= 0f)) { HitData val5 = new HitData(); val5.m_damage.m_blunt = Plugin.LightningStructureDamage.Value * Mathf.Max(0.3f, num3); val5.m_toolTier = 100; val5.m_point = pos; val5.m_dir = Vector3.down; val5.m_statusEffectHash = DamageMarker; item2.Damage(val5); } } foreach (TreeBase item3 in hashSet3) { if (!(Random.value > Plugin.LightningTreeFellChance.Value)) { FellTree(item3, RandomHorizontal(new Random(((Object)item3).GetInstanceID()))); } } } private static float Falloff(Vector3 target, Vector3 center, float radius) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) float num = Vector3.Distance(target, center); return Mathf.Clamp01(1f - num / radius) * 0.7f + ((num < radius) ? 0.3f : 0f); } private static void ResolveGust(Player player, Random rng, float minR, float maxR) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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) //IL_003e: 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: 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_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: 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_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) Vector3 position = ((Component)player).transform.position; Vector3 val = (((Object)(object)EnvMan.instance != (Object)null) ? EnvMan.instance.GetWindDir() : Vector3.forward); if (((Vector3)(ref val)).sqrMagnitude < 0.01f) { val = Vector3.forward; } for (int i = 0; i < 4; i++) { float num = Mathf.Lerp(minR, maxR, (float)rng.NextDouble()); int num2 = Physics.OverlapSphereNonAlloc(position + RandomHorizontal(rng) * num, 12f, _overlap, -1, (QueryTriggerInteraction)1); TreeBase val2 = null; for (int j = 0; j < num2; j++) { if (!((Object)(object)val2 == (Object)null)) { break; } val2 = (((Object)(object)_overlap[j] != (Object)null) ? ((Component)_overlap[j]).GetComponentInParent<TreeBase>() : null); } if (!((Object)(object)val2 == (Object)null)) { Broadcast(1, ((Component)val2).transform.position + Vector3.up * 4f); TreeBase tree = val2; Vector3 val3 = new Vector3(val.x, 0f, val.z); FellTree(tree, ((Vector3)(ref val3)).normalized); break; } } } private static void FellTree(TreeBase tree, Vector3 dir) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //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_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)tree == (Object)null) && !((Object)(object)tree.m_nview == (Object)null) && tree.m_nview.IsValid()) { HitData val = new HitData(); val.m_damage.m_chop = tree.m_health * 5f + 1000f; val.m_toolTier = 100; val.m_point = ((Component)tree).transform.position + Vector3.up * 1.5f; val.m_dir = dir; tree.Damage(val); } } private static Vector3 RandomHorizontal(Random rng) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) float num = (float)(rng.NextDouble() * 3.1415927410125732 * 2.0); return new Vector3(Mathf.Sin(num), 0f, Mathf.Cos(num)); } public static void BroadcastStrikeFx(Vector3 pos) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) Broadcast(0, pos); } private static void Broadcast(int kind, Vector3 pos) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_000e: Unknown result type (might be due to invalid IL or missing references) ZPackage val = new ZPackage(); val.Write(kind); val.Write(pos); ZRoutedRpc.instance.InvokeRoutedRPC(0L, "NF_StrikeFx", new object[1] { val }); } public static void OnStrikeFx(long sender, ZPackage pkg) { //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_0017: 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) int num = pkg.ReadInt(); Vector3 pos = pkg.ReadVector3(); if (num == 1) { LightningFx.PlayGust(pos); } else { LightningFx.PlayStrike(pos); } } } } namespace NaturalForces.DebugTools { public class NfCommand : ConsoleCommand { private static readonly string[] SubCommands = new string[16] { "help", "list", "status", "season", "start", "phase", "speed", "stop", "music", "reload", "atmo", "env", "hold", "strike", "plan", "bm" }; public override string Name => "nf"; public override string Help => "Natural Forces: nf help | list | status | season | start <event> [A-E] | phase <A-E|next> | speed <x> | stop [now] | hold | strike [near|gust] | music [event] [A-E] | reload | atmo | env"; public override List<string> CommandOptionList() { return SubCommands.ToList(); } public override void Run(string[] args) { if (args.Length == 0 || args[0].Equals("help", StringComparison.OrdinalIgnoreCase)) { PrintHelp(); return; } switch (args[0].ToLowerInvariant()
plugins/LivingMap/LivingMap.dll
Decompiled 5 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using TMPro; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.0.0.0")] namespace LivingMap; [BepInPlugin("j1ga.livingmap", "Living Map", "0.19.2")] public class LivingMapPlugin : BaseUnityPlugin { private class DTile { public int Level; public int TX; public int TZ; public long Key; public Texture2D Tex; public RawImage Img; public bool Ready; public bool Queued; public bool Failed; public long LightSig; public byte[] Pending; public byte[] Pending2; public long PendingLight; public Texture2D Tex2; public RawImage Img2; public long Sig; public float RenderedAt; public float LastUsed; public int ShownFrame = -1; public int FogShownFrame = -1; } private class HeightZone { public float Cx; public float Cz; public float Scale; public int Pitch; public int Half; public float[] D; } private struct DTree { public float X; public float Z; public float R; public bool Rock; } private struct DBox { public float X; public float Z; public float HX; public float HZ; public float Cos; public float Sin; public float Top; public byte Mat; public bool Roof; public bool Ridge; public float NX; public float NY; public float NZ; } private class DJob { public DTile Tile; public float X0; public float Z0; public float Mpp; public float Priority; public float WaterLevel; public float Relief; public float ForestShade; public float ZoneSize; public Color32 WaterShallow; public Color32 WaterDeep; public Color32 Tree; public Color32 Rock; public Color32[] Biome; public float[] Fog; public int FogX0; public int FogZ0; public int FogW; public int FogH; public float PixelSize; public int TexSize; public sbyte[] ForestFix; public List<PieceRec> Pieces; public List<DBox> Boxes; public List<DTree> Trees; public HashSet<long> LiveZones; public Dictionary<long, HeightZone> Heights; public Color32[] MatColors; public Color32 MatUnknown; public Color32 Outline; public bool DrawOutline; public List<long> TerrKeys; public List<byte> TerrKinds; public float Grid; public float PathWidth; public Color32 Paved; public Color32 Dirt; public Color32 Cultivated; public Color32 Cleared; public long Sig; public PortJob Port; public long LightSig; public bool Relight; public byte[] Pixels; public byte[] Pixels2; public double Ms; } private class SectorSig { public long Sig; public float At; } private sealed class HostTile { public long Hash; public byte[] Data; } private sealed class TileData { public readonly List<PieceRec> Pieces = new List<PieceRec>(); public readonly List<KeyValuePair<long, byte>> Terrain = new List<KeyValuePair<long, byte>>(); public readonly List<int> Cleared = new List<int>(); public readonly List<int> Planted = new List<int>(); } private sealed class MirrorTile { public long Hash; public TileData Data; public bool Hidden; public bool Pending; } private class PortTex { public int Levels; public int[] W; public int[] H; public float[][] R; public float[][] G; public float[][] B; public float[][] A; public void Sample(float u, float v, float lod, out float r, out float g, out float b, out float a) { int num = Mathf.Clamp((int)(lod + 0.5f), 0, Levels - 1); int num2 = W[num]; int num3 = H[num]; float num4 = u * (float)num2 - 0.5f; float num5 = v * (float)num3 - 0.5f; int num6 = Mathf.FloorToInt(num4); int num7 = Mathf.FloorToInt(num5); float num8 = num4 - (float)num6; float num9 = num5 - (float)num7; num6 %= num2; if (num6 < 0) { num6 += num2; } num7 %= num3; if (num7 < 0) { num7 += num3; } int num10 = ((num6 + 1 != num2) ? (num6 + 1) : 0); int num11 = ((num7 + 1 != num3) ? (num7 + 1) : 0); int num12 = num7 * num2 + num6; int num13 = num7 * num2 + num10; int num14 = num11 * num2 + num6; int num15 = num11 * num2 + num10; float num16 = (1f - num8) * (1f - num9); float num17 = num8 * (1f - num9); float num18 = (1f - num8) * num9; float num19 = num8 * num9; float[] array = R[num]; float[] array2 = G[num]; float[] array3 = B[num]; float[] array4 = A[num]; r = array[num12] * num16 + array[num13] * num17 + array[num14] * num18 + array[num15] * num19; g = array2[num12] * num16 + array2[num13] * num17 + array2[num14] * num18 + array2[num15] * num19; b = array3[num12] * num16 + array3[num13] * num17 + array3[num14] * num18 + array3[num15] * num19; a = array4[num12] * num16 + array4[num13] * num17 + array4[num14] * num18 + array4[num15] * num19; } public float Lod(float repeat, float mpp, float world) { float num = repeat * (float)W[0] * mpp / world; if (!(num <= 1f)) { return Mathf.Log(num, 2f); } return 0f; } } private class PortAssets { public PortTex Background; public PortTex FogLayer; public PortTex Water; public PortTex Lava; public PortTex Mountain; public PortTex Cloud; public PortTex Forest; public Texture2D CloudTex; } private class PortJob { public PortAssets A; public float World; public int TexSize; public Color Forest; public Color Water; public Color WaterDeep; public Color WaterAsh; public Color WaterAshDeep; public Color SunFog; public Color Light; public Color Ambient; public Color Sun; public Color AmbientG; public Color Lava1; public Color Lava2; public Vector3 LightDir; public float NormalWidth; public float NormalIntensity; public float Zoom; public float SharedFade; public float CloudX; public float CloudZ; public float TimeX; public float TimeY; public float Cells; public bool CellPerPixel; public bool Clouds; public Color32[] Mat; public Color32 MatUnknown; public Color32 Outline; public Color32 Paved; public Color32 Dirt; public Color32 Cultivated; public Color32 Cleared; public bool DrawOutline; public bool Styled; public int X0; public int Z0; public int W; public int H; public float[] Height; public float[] MainR; public float[] MainG; public float[] MainB; public float[] MaskX; public float[] MaskY; public float[] MaskZ; public float[] FogX; public float[] FogY; public int MainScale = 1; public int MainX0; public int MainZ0; public int MainW; public int MainH; public bool Classic; } private class PortDetail { public byte[] Main; public float[] MaskX; public byte[] Ground; public float[] H; public int Gs; public float Half; public byte[] Kind; public short[] Box; } private struct PrefabInfo { public bool IsPiece; public bool IsTree; public bool IsRock; public bool IsTerrain; public byte Mat; public Vector3 Min; public Vector3 Max; public bool Roof; public bool Ridge; public Vector3 RoofN; } private struct PieceRec { public float X0; public float Z0; public float X1; public float Z1; public float Y; public byte Mat; public float CX => (X0 + X1) * 0.5f; public float CZ => (Z0 + Z1) * 0.5f; } private const byte LayerBuildings = 1; private const byte LayerPaths = 2; private const byte LayerForest = 4; private const float DefaultResetRadius = 100f; private const string SecGeneral = "01 General"; private const string SecLayers = "02 Layers"; private const string SecScanning = "03 Scanning"; private const string SecRendering = "04 Rendering"; private const string SecColors = "05 Colors"; private const string SecAdvanced = "06 Advanced"; private const string SecDebug = "07 Debug"; private const int GameMatCount = 9; private const byte MatRoofThatch = 9; private const byte MatRoofDarkwood = 10; private const byte MatRoofTurf = 11; private const byte MatRoofSlate = 12; private const string UiLayers = "1. Map layers"; private const string UiDetail = "2. Close-up detail"; private const string UiColours = "3. Colours"; private const string UiShare = "4. Multiplayer"; private const string UiAdvanced = "5. Advanced"; private const string UiDebug = "6. Debug"; private const string SecDetail = "08 Detail"; private const float LegacyRelief = 1f; private const float LegacyForestShade = 0.35f; private const float LegacyToneDesaturate = 0.5f; private const float LegacySharedOpacity = 0.5f; private const int DTileSize = 256; private const int DVisibleLimit = 64; private const int DUploadsPerFrame = 2; private const int DEnqueuesPerFrame = 2; private const float DRedrawMinAge = 5f; private const double DSnapBudgetMs = 4.0; private const float DRecheckInterval = 0.1f; private const float DSectorSigAge = 2f; private const int DRelightSwapsPerFrame = 8; private const float DObjectsMaxMpp = 2.9f; private const float DPrefetchPriority = 1E+09f; private const float DPrefetchAge = 30f; private const int DStep = 2; private const int ForestZonesPerFrame = 150; private const int BiomeLookupsPerFrame = 600; private const int MaxIncrementalPieces = 1500; private const float MapRebuildInterval = 0.5f; private const float HeightEditMin = 0.5f; private const int HeightSamples = 3; private const string HighOff = "Off"; private const string HighMinimap = "Minimap"; private const string HighBoth = "Both"; private const float HighGroundFrom = 70f; private const float WaterHidesBelow = 29.5f; private const string NoticeVersion = "0.16.0"; private const float NoticeFontIncrease = 2f; private const BindingFlags MmFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; private const float ScanMoveDelta = 8f; private const float ScanInterval = 1f; private const float IdleRescanInterval = 10f; private const int MaxColliders = 8192; private const string SecShare = "09 Multiplayer"; private const int ShareProto = 1; private const float ShareTile = 128f; private const float ShareRefresh = 60f; private const float ShareReapply = 20f; private const int ShareReplyBytes = 204800; private const int ShareAskTiles = 128; private const int ShareTilesPerFrame = 64; private const string RpcHello = "LivingMap_Hello"; private const string RpcIndex = "LivingMap_Index"; private const string RpcGet = "LivingMap_Get"; private const string RpcTiles = "LivingMap_Tiles"; private const int MaxShareErrors = 4; private const float SaveInterval = 60f; private const int TerrainZonesPerFrame = 4; private const int MaxTcErrors = 10; private const string CloudsSmooth = "Smooth"; private const string CloudsExact = "Exact"; private const string CloudsOff = "Off"; private const int MaxZdoErrors = 10; public const string Guid = "j1ga.livingmap"; public const string Name = "Living Map"; public const string Version = "0.19.2"; private const byte MatNone = byte.MaxValue; private const byte TerrainNone = 0; private const byte TerrainCultivated = 1; private const byte TerrainPaved = 2; private const byte TerrainDirt = 3; private const byte TerrainCleared = 4; private const float RefogInterval = 15f; private const float MaxFootprint = 32f; private const int MaxErrors = 25; private const int MaxTerrainErrors = 10; internal const float FlatPieceDamp = 0.85f; private const string OldGuid = "j1ga.mapoverlay"; private const string OldFolder = "MapOverlay"; private ConfigEntry<bool> _cfgEnabled; private ConfigEntry<bool> _cfgPersist; private ConfigEntry<bool> _cfgShowBuildings; private ConfigEntry<bool> _cfgOnlyPlayerBuilt; private ConfigEntry<bool> _cfgShowPaths; private ConfigEntry<bool> _cfgShowCleared; private ConfigEntry<float> _cfgPathWidth; private ConfigEntry<bool> _cfgPathsClearForest; private ConfigEntry<bool> _cfgShowForest; private ConfigEntry<float> _cfgForestRadius; private ConfigEntry<int> _cfgForestMaxTrees; private ConfigEntry<bool> _cfgShowPlanted; private ConfigEntry<int> _cfgPlantedMinTrees; private ConfigEntry<bool> _cfgPlantedAnyBiome; private ConfigEntry<bool> _cfgRespectFog; private ConfigEntry<string> _cfgScanSource; private ConfigEntry<string> _cfgPathSource; private ConfigEntry<float> _cfgZdoInterval; private ConfigEntry<int> _cfgMapScale; private ConfigEntry<float> _cfgPieceSize; private ConfigEntry<bool> _cfgOutline; private ConfigEntry<float> _cfgOutlineWidth; private ConfigEntry<float> _cfgTerrainGrid; private ConfigEntry<Color>[] _cfgMatColor; private ConfigEntry<float> _cfgPaletteStrength; private ConfigEntry<Color> _cfgMatUnknownColor; private ConfigEntry<Color> _cfgCultivatedColor; private ConfigEntry<Color> _cfgPavedColor; private ConfigEntry<Color> _cfgDirtColor; private ConfigEntry<Color> _cfgClearedColor; private ConfigEntry<Color> _cfgOutlineColor; private ConfigEntry<int> _cfgZdoPerFrame; private ConfigEntry<float> _cfgScanRadius; private ConfigEntry<int> _cfgMaxPieces; private ConfigEntry<int> _cfgMaxTerrain; private ConfigEntry<bool> _cfgDebug; private ConfigEntry<bool> _cfgDebugMarker; private ConfigEntry<bool> _cfgIncremental; private ConfigEntry<bool> _cfgLinearFix; private ConfigEntry<bool> _cfgMapFlipY; private static readonly string[] MatNames = new string[13] { "Wood", "Stone", "Iron", "HardWood", "Marble", "Ashstone", "Ancient", "Ice", "Timberwood", "Roof_Thatch", "Roof_Darkwood", "Roof_Turf", "Roof_Slate" }; private static readonly string[] DroppedSettings = new string[16] { "MapRebuildInterval", "MoveDelta", "ScanInterval", "IdleRescanInterval", "SaveInterval", "MaxColliders", "PaintMapTexture", "DetailedOverlay", "MinimapOverlay", "FlushInterval", "PixelsPerFlush", "OverlayOpacity", "SmoothOverlay", "MinimapOverlayResolution", "DetailedOverlayResolution", "DetailedOverlayInterval" }; private ConfigEntry<bool> _cfgDetail; private ConfigEntry<float> _cfgDetailStartSpan; private ConfigEntry<float> _cfgDetailFinest; private ConfigEntry<bool> _cfgDetailObjects; private ConfigEntry<int> _cfgDetailWorkers; private ConfigEntry<int> _cfgDetailCache; private ConfigEntry<bool> _cfgDetailPrefetch; private ConfigEntry<float> _cfgDetailRelight; private static readonly Color LegacyWaterShallow = new Color(0.27f, 0.28f, 0.33f, 1f); private static readonly Color LegacyWaterDeep = new Color(0.22f, 0.24f, 0.3f, 1f); private static readonly Color LegacyTree = new Color(0.55f, 0.62f, 0.45f, 1f); private static readonly Color LegacyRock = new Color(0.5f, 0.5f, 0.48f, 1f); private static readonly Color LegacyToneTint = new Color(0.38f, 0.48f, 0.44f, 1f); private static float[] DLevels = new float[3] { 4f, 2f, 1f }; private readonly Dictionary<long, DTile> _dTiles = new Dictionary<long, DTile>(); private readonly HashSet<long> _dEverDrawn = new HashSet<long>(); private int _dRedraws; private readonly List<DJob> _dPending = new List<DJob>(); private readonly List<DJob> _dDone = new List<DJob>(); private readonly object _dLock = new object(); private Thread[] _dWorkers; private volatile bool _dStop; private bool _dBroken; private RectTransform _dRoot; private RectTransform _dBack; private RectTransform _dFront; private RectTransform _dFogBack; private RectTransform _dFogFront; private CanvasGroup _dGroup; private int _dRecheckCursor; private int _dEnqueuedThisFrame; private int _dFrame; private double _dSnapMsFrame; private int _dOpenLevel = -1; private float _dRecheckNext; private readonly Dictionary<uint, SectorSig> _dSectorSig = new Dictionary<uint, SectorSig>(); private readonly List<DTile> _dScratch = new List<DTile>(); private FieldInfo _fiMistColor; private FieldInfo _fiObjectsBySector; private int _dRendered; private double _dMsTotal; private double _dMsMax; private int _dSnaps; private double _dSnapMsTotal; private double _dSnapMsMax; private readonly Dictionary<long, HeightZone> _dHeights = new Dictionary<long, HeightZone>(); private readonly Dictionary<long, int> _dZoneRev = new Dictionary<long, int>(); private long _dHeightsWorld; private readonly Dictionary<int, byte> _dKind = new Dictionary<int, byte>(); private RawImage _dClouds; private int _dShownLevel = -1; private bool _dViewCovered; private float _dShownNeed; private float _dShownAt = -100f; private long _dLight; private float _dLightNext; private FieldInfo _fiGeneratedZones; private BitArray _forestMask; private BitArray _pixelTrusted; private byte[] _treeCount; private readonly HashSet<int> _clearedForest = new HashSet<int>(); private readonly HashSet<int> _trustedZones = new HashSet<int>(); private readonly List<int> _trustedZoneScratch = new List<int>(); private readonly List<int> _forestSample = new List<int>(); private bool _forestDisabled; private int _forestCursor = -1; private bool _forestChanged; private int _forestAdded; private int _forestRemoved; private readonly HashSet<int> _plantedForest = new HashSet<int>(); private readonly Dictionary<int, int> _outsideCounts = new Dictionary<int, int>(); private readonly Dictionary<int, bool> _forestBiome = new Dictionary<int, bool>(); private int _biomeLookupsThisFrame; private RenderTexture _rtMask; private Material _glMatMask; private Material _glMatMaskAdd; private Texture2D _vanillaMask; private Texture _origSmallMask; private Texture _origLargeMask; private RenderTexture _rt; private Material _glMat; private bool _gpuUnavailable; private bool _rtDirty; private bool _maskDirty; private readonly List<PieceRec> _addPieces = new List<PieceRec>(); private readonly List<long> _addTerrain = new List<long>(); private readonly List<PieceRec> _fogPieces = new List<PieceRec>(); private readonly List<long> _fogTerrain = new List<long>(); private readonly List<int> _fogForest = new List<int>(); private readonly List<PieceRec> _groupScratch = new List<PieceRec>(); private readonly List<PieceRec> _fillScratch = new List<PieceRec>(); private int _rtIncrements; private bool _collectedCleared; private float _nextRtRebuild; private int _rtScale = 1; private int _rtRebuilds; private static readonly Comparison<PieceRec> ByTop = (PieceRec a, PieceRec b) => a.Y.CompareTo(b.Y); private static float MapPixelSize; private static bool LinearColors; private ConfigEntry<bool> _cfgHeightFromTerrain; private Texture2D _heightTex; private Texture _origSmallHeight; private Texture _origLargeHeight; private bool _heightDirty; private bool _heightUnavailable; private readonly Dictionary<int, float> _heightApplied = new Dictionary<int, float>(); private ConfigEntry<string> _cfgHighOverlay; private ConfigEntry<float> _cfgHighStrength; private ConfigEntry<bool> _cfgHighWater; private RenderTexture _rtHigh; private Material _glMatHigh; private bool _highDirty; private bool _highUnavailable; private BitArray _highPixels; private BitArray _highMist; private BitArray _highWater; private RawImage _highSmall; private RawImage _highLarge; private Sprite _highCircle; private Color _highLight = Color.white; private int _highPieceCount; private int _highCellCount; private long _highSig = -1L; private readonly List<PieceRec> _highScratch = new List<PieceRec>(); private readonly List<long> _highCells = new List<long>(); private ConfigEntry<string> _cfgNoticeSeen; private bool _noticeDone; private TMP_Text _noticeBody; private float _noticeFont; private float _noticeFontMax; private static readonly FieldInfo s_fiPopupInstance = typeof(UnifiedPopup).GetField("instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); private static readonly FieldInfo s_fiPopupBody = typeof(UnifiedPopup).GetField("bodyText", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly string[] PortTestGlobals = new string[3] { "_SunColor", "_AmbientColor", "_SunFogColor" }; private static readonly string[] ProbeTexNames = new string[4] { "_MainTex", "_HeightTex", "_MaskTex", "_FogTex" }; private RawImage _probeImg; private Material _probeMat; private RenderTexture[] _probeRt; private Texture[] _probeSrc; private Rect _probeUv; private bool _probeCrop; private int _probeSize; private Collider[] _colliderBuf; private int _pieceLayerMask; private ConfigEntry<bool> _cfgShare; private ConfigEntry<bool> _cfgUseHostMap; private ZRoutedRpc _rpcRegistered; private int _storeRev; private int _sharedRev = -1; private int _shareErrors; private bool _shareOff; private readonly HashSet<long> _hostPeers = new HashSet<long>(); private Dictionary<int, HostTile> _hostTiles = new Dictionary<int, HostTile>(); private bool _hostBuilding; private float _nextShareCheck; private int _shareSentTiles; private long _shareSentBytes; private readonly Dictionary<int, MirrorTile> _mirror = new Dictionary<int, MirrorTile>(); private readonly Dictionary<int, List<long>> _ownTerrainByTile = new Dictionary<int, List<long>>(); private readonly Queue<int> _wantQueue = new Queue<int>(); private readonly Dictionary<int, long> _indexHashes = new Dictionary<int, long>(); private readonly List<int> _asked = new List<int>(); private bool _helloSent; private bool _waiting; private float _waitingSince; private float _nextReapply; private bool _hostPieces; private bool _hostTerrain; private bool _hostForest; private int _shareGotTiles; private long _shareGotBytes; private long _worldUid; private bool _storeChanged; private readonly List<ZDO> _tcZdos = new List<ZDO>(); private readonly Dictionary<ZDOID, uint> _tcRevision = new Dictionary<ZDOID, uint>(); private int _tcCursor = -1; private int _tcParsed; private int _tcSkipped; private int _tcAdded; private int _tcRemoved; private int _tcChanged; private int _tcErrorCount; private int _tcPasses; private double _tcMs; private bool _tcDisabled; private bool[] _tcHeightScratch; private byte[] _tcKindScratch; private ConfigEntry<string> _cfgDetailStyle; private ConfigEntry<float> _cfgDetailPixel; private ConfigEntry<string> _cfgDetailCloudStyle; private ConfigEntry<bool> _cfgDetailStyled; private ConfigEntry<bool> _cfgPortClassicFirst; internal static int s_portCoastFrom = 0; private Texture _origCloudTex; private Texture _clearCloudTex; private Material _cloudMatLarge; private Material _cloudMatSmall; private PortAssets _port; private Material _portMat; private bool _portFailed; private static float[] s_srgbToLinear; private static readonly FieldInfo s_fiHeightTex = typeof(Minimap).GetField("m_heightTexture", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly FieldInfo s_fiForestTex = typeof(Minimap).GetField("m_forestMaskTexture", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private static readonly FieldInfo s_fiFogTex = typeof(Minimap).GetField("m_fogTexture", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); internal static bool s_portLinMaterial = false; internal static bool s_portLinGlobals = false; internal static bool s_portLinTextures = true; internal static bool s_portSrgbOut = true; internal static int s_portLightMode = 1; internal static bool s_portMaskFromMaterial = false; private int _zdoPieceLayer = -1; private readonly Dictionary<int, PrefabInfo> _prefabCache = new Dictionary<int, PrefabInfo>(); private List<ZDO>[] _zdoSectors; private FieldInfo _fiPortalObjects; private readonly HashSet<int> _portalHashes = new HashSet<int>(); private readonly HashSet<ZDO> _portalsSeen = new HashSet<ZDO>(); private int _zdoSectorCursor; private readonly List<ZDO> _zdoSnapshot = new List<ZDO>(); private int _zdoSnapshotCursor; private readonly Dictionary<int, List<PieceRec>> _zdoBuckets = new Dictionary<int, List<PieceRec>>(); private readonly Stack<List<PieceRec>> _listPool = new Stack<List<PieceRec>>(); private readonly List<int> _removeScratch = new List<int>(); private int _zdoCursor = -1; private float _nextZdoPass; private Vector3 _zdoPassOrigin; private Vector3 _zdoPrevOrigin; private bool _zdoHavePrevOrigin; private bool _zdoAuthoritative; private int _zdoPasses; private int _zdoPassFrames; private int _zdoErrorCount; private readonly Stopwatch _sw = new Stopwatch(); private double _zdoPassMs; private double _forestMs; private bool _zdoDisabled; private bool _zdoPassPieces; private bool _piecesOnlyPlayerBuilt; private readonly Dictionary<int, List<PieceRec>> _pieces = new Dictionary<int, List<PieceRec>>(); private int _pieceCount; private readonly Dictionary<long, byte> _terrain = new Dictionary<long, byte>(); private readonly List<int> _circleScratch = new List<int>(); private readonly Dictionary<int, List<PieceRec>> _scanBuckets = new Dictionary<int, List<PieceRec>>(); private readonly List<long> _terrainScratch = new List<long>(); private Minimap _mm; private Texture2D _vanillaTex; private Texture _origSmallTex; private Texture _origLargeTex; private int _texSize; private float _pixelSize; private bool _ready; private Vector3 _lastScanPos; private float _nextScanTime; private float _lastScanTime; private float _nextSaveTime; private float _nextRefogTime; private FieldInfo _fiExplored; private FieldInfo _fiExploredOthers; private int _errorCount; private int _terrainErrorCount; private bool _disabledByErrors; private bool _terrainDisabled; private readonly HashSet<string> _loggedErrors = new HashSet<string>(); private readonly HashSet<int> _pathForest = new HashSet<int>(); private long _drawSig = -1L; private long _maskCfgSig = -1L; private bool _highWaterOn; private bool _heightOn; private float _nextSigCheck; private float _paletteApplied = 1f; private bool _oldPluginChecked; private static bool WeakCpu => SystemInfo.processorCount <= 4; private int DetailThreads { get { int num = ((_cfgDetailWorkers != null) ? _cfgDetailWorkers.Value : 0); if (num > 0) { return Mathf.Clamp(num, 1, 8); } return Mathf.Clamp(SystemInfo.processorCount - 2, 1, 4); } } private int DetailCacheLimit { get { if (_cfgDetailCache == null) { return 96; } return Mathf.Clamp(_cfgDetailCache.Value, 32, 512); } } private bool ForestWanted { get { if ((_cfgShowForest.Value || _cfgShowPlanted.Value) && !_forestDisabled) { return UseZdoScan; } return false; } } private int MapScale { get { int num = ((_cfgMapScale != null) ? _cfgMapScale.Value : 0); if (num > 0) { return Mathf.Clamp(num, 1, 8); } int graphicsMemorySize = SystemInfo.graphicsMemorySize; if (graphicsMemorySize <= 0) { return 2; } if (graphicsMemorySize >= 3072) { if (graphicsMemorySize >= 7168) { return 4; } return 2; } return 1; } } private bool HeightsWanted { get { if (_cfgHeightFromTerrain != null) { return _cfgHeightFromTerrain.Value; } return true; } } private string HighMode { get { if (_cfgHighOverlay == null) { return "Off"; } return _cfgHighOverlay.Value; } } private bool HighWaterWanted { get { if (_cfgHighWater != null) { return _cfgHighWater.Value; } return false; } } private float HighStrength { get { if (_cfgHighStrength == null) { return 0.7f; } return Mathf.Clamp(_cfgHighStrength.Value, 0.2f, 1f); } } private bool HighWanted { get { if (!_highUnavailable && HighMode != "Off" && _cfgEnabled != null) { return _cfgEnabled.Value; } return false; } } private bool ShareHost { get { if (!_shareOff && _cfgShare.Value && (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer() && !ZNet.instance.IsDedicated() && _zdoAuthoritative) { return _zdoPasses > 0; } return false; } } private bool ShareClient { get { if (!_shareOff && _cfgUseHostMap.Value && (Object)(object)ZNet.instance != (Object)null) { return !ZNet.instance.IsServer(); } return false; } } private bool UseZdoPaths { get { if (UseZdoScan && !_tcDisabled) { return string.Equals(_cfgPathSource.Value, "ZDO", StringComparison.OrdinalIgnoreCase); } return false; } } private bool PortWanted { get { if (_cfgDetailStyle != null) { return _cfgDetailStyle.Value == "Vanilla"; } return false; } } private bool PortClassicFirst { get { if (_cfgPortClassicFirst != null) { return _cfgPortClassicFirst.Value; } return false; } } private string CloudStyle { get { if (_cfgDetailCloudStyle == null) { return "Smooth"; } return _cfgDetailCloudStyle.Value; } } private bool UseZdoScan { get { if (!_zdoDisabled && _fiObjectsBySector != null) { return string.Equals(_cfgScanSource.Value, "ZDO", StringComparison.OrdinalIgnoreCase); } return false; } } private float PaletteStrength { get { if (_cfgPaletteStrength == null) { return 1f; } return Mathf.Clamp(_cfgPaletteStrength.Value, 0.5f, 1f); } } private void RegisterCommands() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown //IL_0020: Unknown result type (might be due to invalid IL or missing references) new ConsoleCommand("livingmap", "Living Map. 'livingmap status' shows what the map remembers; 'livingmap reset [buildings|paths|forest] [metres|all]' forgets it around you (100 m by default) and collects it again", (ConsoleEvent)delegate(ConsoleEventArgs args) { RunCommand(args); }, false, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); } private static void Say(ConsoleEventArgs args, string text) { if (args != null && (Object)(object)args.Context != (Object)null) { args.Context.AddString(text); } } private void RunCommand(ConsoleEventArgs args) { //IL_01f8: Unknown result type (might be due to invalid IL or missing references) try { string text = ((args.Args.Length > 1) ? args.Args[1].ToLowerInvariant() : ""); switch (text) { case "status": Say(args, StatusText()); return; case "probe": Say(args, ProbeCommand(args.Args)); return; case "port": Say(args, PortTest()); return; } if (text != "reset") { Say(args, "livingmap status | livingmap reset [buildings|paths|forest] [metres|all]"); return; } byte b = 0; float radius = 100f; bool world = false; for (int i = 2; i < args.Args.Length; i++) { string text2 = args.Args[i].ToLowerInvariant(); switch (text2) { case "buildings": case "pieces": b |= 1; continue; case "paths": case "terrain": b |= 2; continue; case "forest": case "trees": b |= 4; continue; case "all": case "world": world = true; continue; } if (float.TryParse(text2, NumberStyles.Float, CultureInfo.InvariantCulture, out var result) && result > 0f) { radius = result; continue; } Say(args, "livingmap: unknown word '" + args.Args[i] + "'"); return; } if (b == 0) { b = 7; } if (!_ready || (Object)(object)_mm == (Object)null) { Say(args, "livingmap: not attached to a map right now"); } else if ((Object)(object)Player.m_localPlayer == (Object)null) { Say(args, "livingmap: no player"); } else { Say(args, ResetData(b, ((Component)Player.m_localPlayer).transform.position, radius, world)); } } catch (Exception e) { HandleError("console command", e); Say(args, "livingmap: failed, see the BepInEx log"); } } private string StatusText() { if (!_ready || (Object)(object)_mm == (Object)null) { return "Living Map 0.19.2: not attached to a map"; } return string.Format("Living Map {0}: {1} pieces in {2} map pixels, {3} path cells, forest cleared {4} / planted {5}; buildings via {6}, paths via {7}; map {8}px ({9:0.##} m/px); last pass {10} frames, {11:0.0} ms", "0.19.2", _pieceCount, _pieces.Count, _terrain.Count, _clearedForest.Count, _plantedForest.Count, (!UseZdoScan) ? "physics" : (_zdoAuthoritative ? "ZDO (host, whole world)" : "ZDO (client)"), UseZdoPaths ? "terrain records" : "loaded heightmaps", (((Object)(object)_rt != (Object)null) ? ((Texture)_rt).width : 0) + ((_cfgMapScale.Value > 0) ? "" : " auto"), ((Object)(object)_rt != (Object)null) ? (_pixelSize / (float)_rtScale) : 0f, _zdoPassFrames, _zdoPassMs) + "; " + DetailStatus() + "; " + ShareStatus() + "; " + HighStatus() + "; " + HeightStatus() + "\n" + MaterialText(); } private string MaterialText() { int[] array = new int[MatNames.Length]; int num = 0; foreach (KeyValuePair<int, List<PieceRec>> piece in _pieces) { List<PieceRec> value = piece.Value; for (int i = 0; i < value.Count; i++) { byte mat = value[i].Mat; if (mat < array.Length) { array[mat]++; } else { num++; } } } StringBuilder stringBuilder = new StringBuilder("pieces by material: "); int num2 = 0; for (int j = 0; j < array.Length; j++) { if (array[j] != 0) { if (num2++ > 0) { stringBuilder.Append(", "); } stringBuilder.Append(MatNames[j]).Append(' ').Append(array[j]); } } if (num > 0) { stringBuilder.Append((num2++ > 0) ? ", " : "").Append("unknown ").Append(num); } if (num2 == 0) { stringBuilder.Append("none stored yet"); } return stringBuilder.ToString(); } private string ResetData(byte layers, Vector3 center, float radius, bool world) { //IL_0255: 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_0050: 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) float half = (float)_texSize * 0.5f; float num = radius * radius; int num2 = 0; int num3 = 0; int num4 = 0; if ((layers & 1) != 0) { _removeScratch.Clear(); foreach (KeyValuePair<int, List<PieceRec>> piece in _pieces) { if (world || PixelWithin(piece.Key, center, num, half)) { _removeScratch.Add(piece.Key); } } for (int i = 0; i < _removeScratch.Count; i++) { List<PieceRec> list = _pieces[_removeScratch[i]]; num2 += list.Count; _pieceCount -= list.Count; ReturnList(list); _pieces.Remove(_removeScratch[i]); } _removeScratch.Clear(); _addPieces.Clear(); _fogPieces.Clear(); } if ((layers & 2) != 0) { float num5 = Mathf.Max(0.5f, _cfgTerrainGrid.Value); List<long> list2 = new List<long>(); foreach (KeyValuePair<long, byte> item in _terrain) { if (!world) { float num6 = ((float)(int)(item.Key >> 32) + 0.5f) * num5 - center.x; float num7 = ((float)(int)(item.Key & 0xFFFFFFFFu) + 0.5f) * num5 - center.z; if (num6 * num6 + num7 * num7 > num) { continue; } } list2.Add(item.Key); } for (int j = 0; j < list2.Count; j++) { _terrain.Remove(list2[j]); } num3 = list2.Count; _addTerrain.Clear(); _fogTerrain.Clear(); _tcRevision.Clear(); _lastScanPos = new Vector3(float.MinValue, 0f, float.MinValue); _nextScanTime = 0f; } if ((layers & 4) != 0) { num4 += RemovePixels(_clearedForest, center, num, half, world); num4 += RemovePixels(_plantedForest, center, num, half, world); _trustedZones.Clear(); _fogForest.Clear(); _maskDirty = true; } ResetZdoPass(); _nextZdoPass = 0f; _rtDirty = true; MarkStoreChanged(); string text = (world ? "the whole world" : $"{radius:0} m around you"); string text2 = $"Living Map: forgot {num2} pieces, {num3} path cells, {num4} forest pixels in {text}; collecting again"; ((BaseUnityPlugin)this).Logger.LogInfo((object)text2); return text2; } private bool PixelWithin(int idx, Vector3 center, float r2, float half) { float num = ((float)(idx % _texSize) + 0.5f - half) * _pixelSize - center.x; float num2 = ((float)(idx / _texSize) + 0.5f - half) * _pixelSize - center.z; return num * num + num2 * num2 <= r2; } private int RemovePixels(HashSet<int> pixels, Vector3 center, float r2, float half, bool world) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (world) { int count = pixels.Count; pixels.Clear(); return count; } _removeScratch.Clear(); foreach (int pixel in pixels) { if (PixelWithin(pixel, center, r2, half)) { _removeScratch.Add(pixel); } } for (int i = 0; i < _removeScratch.Count; i++) { pixels.Remove(_removeScratch[i]); } int count2 = _removeScratch.Count; _removeScratch.Clear(); return count2; } private void BindConfig() { //IL_05b7: 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_05dd: Unknown result type (might be due to invalid IL or missing references) //IL_05e2: Unknown result type (might be due to invalid IL or missing references) //IL_0603: Unknown result type (might be due to invalid IL or missing references) //IL_0608: Unknown result type (might be due to invalid IL or missing references) //IL_0629: Unknown result type (might be due to invalid IL or missing references) //IL_062e: Unknown result type (might be due to invalid IL or missing references) //IL_064f: Unknown result type (might be due to invalid IL or missing references) //IL_0654: Unknown result type (might be due to invalid IL or missing references) //IL_0675: Unknown result type (might be due to invalid IL or missing references) //IL_067a: Unknown result type (might be due to invalid IL or missing references) //IL_069b: Unknown result type (might be due to invalid IL or missing references) //IL_06a0: Unknown result type (might be due to invalid IL or missing references) //IL_06c1: Unknown result type (might be due to invalid IL or missing references) //IL_06c6: Unknown result type (might be due to invalid IL or missing references) //IL_06e7: Unknown result type (might be due to invalid IL or missing references) //IL_06ec: Unknown result type (might be due to invalid IL or missing references) //IL_070e: Unknown result type (might be due to invalid IL or missing references) //IL_0713: Unknown result type (might be due to invalid IL or missing references) //IL_0735: Unknown result type (might be due to invalid IL or missing references) //IL_073a: Unknown result type (might be due to invalid IL or missing references) //IL_075c: Unknown result type (might be due to invalid IL or missing references) //IL_0761: Unknown result type (might be due to invalid IL or missing references) //IL_0783: Unknown result type (might be due to invalid IL or missing references) //IL_0788: Unknown result type (might be due to invalid IL or missing references) //IL_0843: Unknown result type (might be due to invalid IL or missing references) //IL_08f3: Unknown result type (might be due to invalid IL or missing references) //IL_093e: Unknown result type (might be due to invalid IL or missing references) //IL_0989: Unknown result type (might be due to invalid IL or missing references) //IL_09d4: Unknown result type (might be due to invalid IL or missing references) //IL_0a1f: Unknown result type (might be due to invalid IL or missing references) //IL_0a6a: Unknown result type (might be due to invalid IL or missing references) _cfgEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("01 General", "Enabled", true, Ui("Living Map on or off. Off: the vanilla map, as if the mod were not there.", "1. Map layers", "Living Map on", 100, advanced: false)); _cfgPersist = ((BaseUnityPlugin)this).Config.Bind<bool>("01 General", "SaveOverlay", true, Ui("Remember what was collected between sessions, in a file per world. Matters on a dedicated server, where you only get what the server has sent you; the host collects everything again within seconds anyway.", "5. Advanced", "Remember between sessions", 100, advanced: true)); _cfgShowBuildings = ((BaseUnityPlugin)this).Config.Bind<bool>("02 Layers", "ShowBuildings", true, Ui("Show buildings on the map.", "1. Map layers", "Buildings", 90, advanced: false)); _cfgShowPaths = ((BaseUnityPlugin)this).Config.Bind<bool>("02 Layers", "ShowPaths", true, Ui("Show dirt paths, fields and paving made with the hoe and the cultivator.", "1. Map layers", "Paths and fields", 88, advanced: false)); _cfgShowForest = ((BaseUnityPlugin)this).Config.Bind<bool>("02 Layers", "ShowClearedForest", true, Ui("Remove the forest from the map where you have cut it down (the vanilla map always shows the forest the world started with).", "1. Map layers", "Cleared forest", 80, advanced: false)); _cfgShowPlanted = ((BaseUnityPlugin)this).Config.Bind<bool>("02 Layers", "ShowPlantedForest", true, Ui("Draw forest where you have planted a grove.", "1. Map layers", "Planted forest", 75, advanced: false)); _cfgOnlyPlayerBuilt = ((BaseUnityPlugin)this).Config.Bind<bool>("02 Layers", "OnlyPlayerBuilt", false, Ui("Only buildings placed by players: ruins, villages and other buildings that come with the world are left out.", "1. Map layers", "Only player buildings", 70, advanced: false)); _cfgRespectFog = ((BaseUnityPlugin)this).Config.Bind<bool>("02 Layers", "RespectFog", true, Ui("Only draw on ground you have explored. Off shows everything the mod knows about - on the host, the whole world.", "1. Map layers", "Only explored ground", 65, advanced: false)); _cfgPathWidth = ((BaseUnityPlugin)this).Config.Bind<float>("02 Layers", "PathWidthMeters", 0f, Ui("How wide a road is drawn, in metres. 0 = its real width. A road is often one cell across, which on the zoomed-out map and the minimap is a single pixel and easy to lose against a dark biome; 4 to 6 makes it a line you can follow. It only widens what is drawn, not what is remembered.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 12f), "1. Map layers", "Road width (m)", 87, advanced: false)); _cfgPathsClearForest = ((BaseUnityPlugin)this).Config.Bind<bool>("02 Layers", "PathsClearForest", true, Ui("Where a road runs through forest, stop drawing the forest pattern over it. The map draws its trees on top of everything, so a road under them is hidden whatever colour it is - and where a road was laid the trees are gone anyway.", "1. Map layers", "Roads show through the forest", 86, advanced: false)); _cfgShowCleared = ((BaseUnityPlugin)this).Config.Bind<bool>("02 Layers", "ShowClearedGround", true, Ui("Also mark ground that was only levelled or raised, never painted with the hoe: a terrace, a filled hollow, a causeway. It covers everything you have ever terraformed, so around a big base it paints wide areas - turn it off for a map that shows only what you painted and built.", "1. Map layers", "Levelled ground", 60, advanced: false)); _cfgForestRadius = ((BaseUnityPlugin)this).Config.Bind<float>("02 Layers", "ClearedForestRadius", 12f, Ui("Metres around a map pixel checked for trees when deciding whether it is cleared forest. Larger ignores natural gaps between trees, smaller follows the edge of a clearing more closely.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(6f, 96f), "5. Advanced", "Cleared forest: search radius (m)", 60, advanced: true)); _cfgForestMaxTrees = ((BaseUnityPlugin)this).Config.Bind<int>("02 Layers", "ClearedForestMaxTrees", 2, Ui("Trees that may still stand in that area for it to count as cleared. A natural wood has 6 to 40 there.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), "5. Advanced", "Cleared forest: trees left", 59, advanced: true)); _cfgPlantedMinTrees = ((BaseUnityPlugin)this).Config.Bind<int>("02 Layers", "PlantedForestMinTrees", 6, Ui("Trees a map pixel (12 x 12 m) must hold to be drawn as planted forest. A planted grove has 15 or more.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 30), "5. Advanced", "Planted forest: trees needed", 58, advanced: true)); _cfgPlantedAnyBiome = ((BaseUnityPlugin)this).Config.Bind<bool>("02 Layers", "PlantedForestAnyBiome", false, Ui("Also draw planted forest where the vanilla map never draws forest (swamps, mountains, Mistlands, Ashlands). Their natural woods then get the forest pattern too.", "5. Advanced", "Planted forest in every biome", 57, advanced: true)); _cfgScanSource = ((BaseUnityPlugin)this).Config.Bind<string>("03 Scanning", "BuildingScanSource", "ZDO", Ui("Where buildings are read from. ZDO: the game's object database - the whole world on the host, what the server has sent on a dedicated server. Physics: only what is loaded around you (the old way). ZDO falls back to Physics by itself if needed.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[2] { "ZDO", "Physics" }), "5. Advanced", "Read buildings from", 50, advanced: true)); _cfgPathSource = ((BaseUnityPlugin)this).Config.Bind<string>("03 Scanning", "PathScanSource", "ZDO", Ui("Where painted ground is read from. ZDO: the terrain records in the object database. Heightmap: the loaded terrain around you (the old way). ZDO needs buildings read from ZDO too.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[2] { "ZDO", "Heightmap" }), "5. Advanced", "Read paths from", 49, advanced: true)); _cfgZdoInterval = ((BaseUnityPlugin)this).Config.Bind<float>("03 Scanning", "ZdoScanInterval", 5f, Ui("Seconds between passes over the object database: how long a new or removed building takes to reach the map.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 120f), "5. Advanced", "Update every (s)", 48, advanced: true)); _cfgMapScale = ((BaseUnityPlugin)this).Config.Bind<int>("04 Rendering", "MapTextureScale", 0, Ui("How sharp the map and the minimap are. 0 = chosen for your graphics card: 1 under 3 GB, 2 under 7 GB, 4 above. Or set it: 1 = 12 m a pixel (16 MB of video memory), 2 = 6 m (64 MB), 4 = 3 m (256 MB), 8 = 1.5 m (1 GB). This is what to raise if buildings look smeared, and the only setting that needs the world loaded again. Close up, the detailed map draws its own picture and is not affected. livingmap status says what is in use.", (AcceptableValueBase)(object)new AcceptableValueList<int>(new int[5] { 0, 1, 2, 4, 8 }), "1. Map layers", "Map sharpness", 95, advanced: false)); _cfgPieceSize = ((BaseUnityPlugin)this).Config.Bind<float>("04 Rendering", "MinPieceSizeMeters", 2f, Ui("Smallest size a building piece is drawn at on the zoomed-out map, so thin walls stay visible.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 8f), "5. Advanced", "Smallest piece (m)", 44, advanced: true)); _cfgOutline = ((BaseUnityPlugin)this).Config.Bind<bool>("04 Rendering", "BuildingOutline", true, Ui("A dark edge around buildings on the map and the minimap, so a wooden house does not blend into the dirt it stands on. Its colour is in the colours below.", "1. Map layers", "Building outline", 58, advanced: false)); _cfgOutlineWidth = ((BaseUnityPlugin)this).Config.Bind<float>("04 Rendering", "OutlineWidthMeters", 1f, Ui("How wide that edge is.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 4f), "5. Advanced", "Outline width (m)", 42, advanced: true)); _cfgTerrainGrid = ((BaseUnityPlugin)this).Config.Bind<float>("04 Rendering", "TerrainGridSize", 2f, Ui("Metres per cell of the paths layer. Smaller is finer but takes four times the memory for half the size. Changing it collects the paths again.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 8f), "5. Advanced", "Paths cell size (m)", 41, advanced: true)); _cfgMatColor = new ConfigEntry<Color>[MatNames.Length]; Color[] array = (Color[])(object)new Color[13] { new Color(0.72f, 0.42f, 0.14f, 1f), new Color(0.72f, 0.74f, 0.8f, 1f), new Color(0.4f, 0.44f, 0.52f, 1f), new Color(0.55f, 0.34f, 0.16f, 1f), new Color(0.9f, 0.87f, 0.8f, 1f), new Color(0.45f, 0.2f, 0.2f, 1f), new Color(0.36f, 0.52f, 0.36f, 1f), new Color(0.65f, 0.85f, 0.95f, 1f), new Color(0.7f, 0.45f, 0.3f, 1f), new Color(0.8f, 0.66f, 0.34f, 1f), new Color(0.33f, 0.27f, 0.24f, 1f), new Color(0.42f, 0.55f, 0.26f, 1f), new Color(0.47f, 0.48f, 0.52f, 1f) }; string[] array2 = new string[13] { "Wood", "Stone", "Iron", "Core wood", "Marble", "Ashstone", "Ancient", "Ice", "Timber", "Roof: thatch", "Roof: darkwood", "Roof: turf", "Roof: slate" }; for (int i = 0; i < MatNames.Length; i++) { _cfgMatColor[i] = ((BaseUnityPlugin)this).Config.Bind<Color>("05 Colors", "Material_" + MatNames[i], array[i], Ui("Colour of " + array2[i].ToLowerInvariant() + " on the map.", "3. Colours", array2[i], 100 - i, advanced: false)); } _cfgPaletteStrength = ((BaseUnityPlugin)this).Config.Bind<float>("05 Colors", "PaletteStrength", 0.85f, Ui("How bright the building colours are, all of them at once. The map's shader brightens what it is given by about half again, which on snow is fine and over a swamp or the Mistlands is a white spot. Lower this rather than editing every colour below. 1 = the colours exactly as they are below; 0.85 by default, which is about where a building stops being the loudest thing on the map.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 1f), "3. Colours", "Building colours: brightness", 200, advanced: false)); _cfgMatUnknownColor = ((BaseUnityPlugin)this).Config.Bind<Color>("05 Colors", "Material_Unknown", new Color(0.85f, 0.3f, 0.75f, 1f), Ui("Colour of pieces whose material is not known.", "3. Colours", "Other pieces", 80, advanced: false)); _cfgCultivatedColor = ((BaseUnityPlugin)this).Config.Bind<Color>("05 Colors", "Terrain_Cultivated", new Color(0.36f, 0.26f, 0.12f, 0.85f), Ui("Colour of cultivated soil.", "3. Colours", "Fields", 79, advanced: false)); _cfgPavedColor = ((BaseUnityPlugin)this).Config.Bind<Color>("05 Colors", "Terrain_Paved", new Color(0.62f, 0.62f, 0.66f, 0.9f), Ui("Colour of paving.", "3. Colours", "Paving", 78, advanced: false)); _cfgDirtColor = ((BaseUnityPlugin)this).Config.Bind<Color>("05 Colors", "Terrain_DirtPath", new Color(0.42f, 0.36f, 0.3f, 0.8f), Ui("Colour of dirt paths.", "3. Colours", "Dirt paths", 77, advanced: false)); _cfgClearedColor = ((BaseUnityPlugin)this).Config.Bind<Color>("05 Colors", "Terrain_Cleared", new Color(0.5f, 0.47f, 0.36f, 0.5f), Ui("Colour of levelled ground (when it is shown).", "3. Colours", "Levelled ground", 76, advanced: false)); _cfgOutlineColor = ((BaseUnityPlugin)this).Config.Bind<Color>("05 Colors", "Building_Outline", new Color(0.1f, 0.07f, 0.04f, 0.85f), Ui("Colour of the building outline on the zoomed-out map.", "3. Colours", "Building outline", 75, advanced: false)); _cfgZdoPerFrame = ((BaseUnityPlugin)this).Config.Bind<int>("06 Advanced", "ZdoObjectsPerFrame", 4000, Ui("Objects looked at per frame while reading the object database. Higher updates the map sooner, lower is smoother.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(500, 50000), "5. Advanced", "Objects per frame", 30, advanced: true)); _cfgScanRadius = ((BaseUnityPlugin)this).Config.Bind<float>("06 Advanced", "ScanRadius", 64f, Ui("Radius scanned around you by the old Physics / Heightmap readers. Unused with the default ZDO.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(16f, 256f), "5. Advanced", "Old scan radius (m)", 29, advanced: true)); _cfgMaxPieces = ((BaseUnityPlugin)this).Config.Bind<int>("06 Advanced", "MaxPieces", 300000, Ui("Most building pieces remembered (300 000 take about 7 MB).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1000, 3000000), "5. Advanced", "Max pieces", 28, advanced: true)); _cfgMaxTerrain = ((BaseUnityPlugin)this).Config.Bind<int>("06 Advanced", "MaxTerrainCells", 500000, Ui("Most path cells remembered.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1000, 5000000), "5. Advanced", "Max path cells", 27, advanced: true)); _cfgDebug = ((BaseUnityPlugin)this).Config.Bind<bool>("07 Debug", "Debug", false, Ui("Verbose log with timings, for bug reports.", "6. Debug", "Debug log", 20, advanced: true)); _cfgDebugMarker = ((BaseUnityPlugin)this).Config.Bind<bool>("07 Debug", "DebugMarker", false, Ui("A magenta cross at your position, to check the layer lines up with the map.", "6. Debug", "Position marker", 19, advanced: true)); _cfgIncremental = ((BaseUnityPlugin)this).Config.Bind<bool>("07 Debug", "IncrementalRedraw", true, Ui("Draw only what changed. Off redraws everything on each change - only for tracking down a drawing glitch.", "6. Debug", "Draw changes only", 18, advanced: true)); _cfgLinearFix = ((BaseUnityPlugin)this).Config.Bind<bool>("07 Debug", "LinearColorFix", true, Ui("Colour conversion for the game's linear colour space. Off only to check whether colours are the problem.", "6. Debug", "Colour conversion", 17, advanced: true)); _cfgMapFlipY = ((BaseUnityPlugin)this).Config.Bind<bool>("07 Debug", "MapLayerFlipY", false, Ui("Flip the layer vertically, for a graphics API that draws it upside down.", "6. Debug", "Flip layer", 16, advanced: true)); BindHighGroundConfig(); BindHeightConfig(); BindDetailConfig(); MigrateDefaults(); BindNoticeConfig(); BindShareConfig(); } private void MigrateDefaults() { //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) ConfigEntry<int> val = ((BaseUnityPlugin)this).Config.Bind<int>("01 General", "ConfigVersion", 1, Hidden("Internal: which defaults these sections have been updated to. Do not edit.")); if (val.Value < 2 && _cfgMapScale.Value == 2) { _cfgMapScale.Value = 0; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Map sharpness now follows the graphics card (MapTextureScale = 0). Set it to 2 to keep what it was."); } if (val.Value < 3 && !_cfgShowCleared.Value) { _cfgShowCleared.Value = true; ((BaseUnityPlugin)this).Logger.LogInfo((object)"Levelled ground is now drawn by default (ShowClearedGround = true). Set it back to false for a map of only what you painted and built."); } if (val.Value < 4) { Color val2 = default(Color); ((Color)(ref val2))..ctor(0.95f, 0.55f, 0.15f, 1f); if (_cfgMatColor.Length > 0 && _cfgMatColor[0].Value == val2) { _cfgMatColor[0].Value = new Color(0.72f, 0.42f, 0.14f, 1f); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Wooden buildings are drawn a darker wood colour now (Material_Wood). Set it back to F28C26FF for what it was."); } } val.Value = 4; } private void MigrateConfigLayout(HashSet<ConfigDefinition> inFile) { Dictionary<ConfigDefinition, string> dictionary = OrphanedConfigEntries(); if (dictionary == null || dictionary.Count == 0) { return; } Dictionary<string, ConfigEntryBase> dictionary2 = new Dictionary<string, ConfigEntryBase>(); foreach (ConfigDefinition key in ((BaseUnityPlugin)this).Config.Keys) { dictionary2[key.Key] = ((BaseUnityPlugin)this).Config[key]; } List<ConfigDefinition> list = new List<ConfigDefinition>(); int num = 0; bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; try { foreach (KeyValuePair<ConfigDefinition, string> item in dictionary) { string text = item.Key.Key; if (item.Key.Section == "06 Colors" && text == "BuildingOutline") { text = "Building_Outline"; } if (!dictionary2.TryGetValue(text, out var value)) { if (Array.IndexOf(DroppedSettings, text) >= 0) { list.Add(item.Key); } continue; } list.Add(item.Key); if (inFile == null || !inFile.Contains(value.Definition)) { try { value.SetSerializedValue(item.Value); num++; } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not carry the setting " + item.Key.Section + "/" + item.Key.Key + " over: " + ex.Message)); } } } for (int i = 0; i < list.Count; i++) { dictionary.Remove(list[i]); } } finally { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; } if (list.Count != 0) { ((BaseUnityPlugin)this).Config.Save(); ((BaseUnityPlugin)this).Logger.LogInfo((object)("Settings file updated to the 0.15.0 layout: " + num + " values moved to their new sections, " + (list.Count - num) + " obsolete lines removed.")); } } private HashSet<ConfigDefinition> SettingsInFile() { Dictionary<ConfigDefinition, string> dictionary = OrphanedConfigEntries(); if (dictionary == null) { return null; } return new HashSet<ConfigDefinition>(dictionary.Keys); } private Dictionary<ConfigDefinition, string> OrphanedConfigEntries() { try { PropertyInfo property = typeof(ConfigFile).GetProperty("OrphanedEntries", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property != null) { return property.GetValue(((BaseUnityPlugin)this).Config, null) as Dictionary<ConfigDefinition, string>; } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not read the unbound settings: " + ex.Message)); } return null; } private static ConfigDescription Ui(string description, string category, string name, int order, bool advanced) { return Ui(description, null, category, name, order, advanced); } private static ConfigDescription Ui(string description, AcceptableValueBase values, string category, string name, int order, bool advanced) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes(); configurationManagerAttributes.Category = category; configurationManagerAttributes.DispName = name; configurationManagerAttributes.Order = order; configurationManagerAttributes.IsAdvanced = advanced; return new ConfigDescription(description, values, new object[1] { configurationManagerAttributes }); } private static ConfigDescription Hidden(string description) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes(); configurationManagerAttributes.Browsable = false; return new ConfigDescription(description, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes }); } private void BindDetailConfig() { _cfgDetail = ((BaseUnityPlugin)this).Config.Bind<bool>("08 Detail", "DetailEnabled", true, Ui("When you zoom the big map in, draw it in detail: buildings with their roofs, paths, fields and the forest as they are, in the vanilla map's style. The minimap is not changed.", "2. Close-up detail", "Close-up detail", 100, advanced: false)); _cfgDetailStartSpan = ((BaseUnityPlugin)this).Config.Bind<float>("08 Detail", "DetailStartSpanMeters", WeakCpu ? 3000f : 6000f, Ui("How far out the detail begins, as the width of the map on screen in metres. Larger: the detail starts earlier and grows more gradually as you zoom in; smaller: it starts later, closer in, and costs less. Default 6000 (3000 on a processor with 4 threads or fewer). Much above the default the view wants more tiles than the cache holds and the picture stops filling in, so there is little to gain.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1000f, 12000f), "2. Close-up detail", "Detail starts at map width (m)", 95, advanced: false)); _cfgDetailFinest = ((BaseUnityPlugin)this).Config.Bind<float>("08 Detail", "DetailFinestMetersPerPixel", 1f, Ui("The finest detail level allowed, in metres per pixel. Coarser means fewer tiles to draw.", (AcceptableValueBase)(object)new AcceptableValueList<float>(new float[3] { 1f, 2f, 4f }), "5. Advanced", "Detail: finest level (m)", 20, advanced: true)); _cfgDetailObjects = ((BaseUnityPlugin)this).Config.Bind<bool>("08 Detail", "DetailObjects", true, Ui("Close up, read buildings (turned, with roofs and heights) straight from the objects near you. Off: the stored outlines only.", "5. Advanced", "Detail: read objects", 19, advanced: true)); _cfgDetailPrefetch = ((BaseUnityPlugin)this).Config.Bind<bool>("08 Detail", "DetailPrefetch", true, Ui("Draw a little more than is on screen: a ring of tiles around the view, so panning does not start from nothing at the edge, and the next closer level, so a step of the zoom has something to show at once. Off by default: it fills the cache with tiles that are not on screen, and unless DetailTileCache is raised well past its default that costs more in tiles drawn again than it saves.", "2. Close-up detail", "Draw ahead", 80, advanced: false)); _cfgDetailCache = ((BaseUnityPlugin)this).Config.Bind<int>("08 Detail", "DetailTileCache", 256, Ui("How many drawn tiles are kept. Panning the map throws the oldest away, and coming back draws them again from nothing - a bigger cache keeps them instead. Each tile is about half a megabyte of memory, and as much again on the card.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(32, 512), "5. Advanced", "Detail: tiles kept", 14, advanced: true)); _cfgDetailWorkers = ((BaseUnityPlugin)this).Config.Bind<int>("08 Detail", "DetailWorkerThreads", 0, Ui("Background threads that draw the detail. 0 = automatic: the processor's threads less two, at most four. They run only while the big map is open, below the game's own priority, and whatever is left to draw is dropped when the map closes. Takes effect on the next world load.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 8), "5. Advanced", "Detail: threads", 15, advanced: true)); _cfgDetailRelight = ((BaseUnityPlugin)this).Config.Bind<float>("08 Detail", "DetailRelightSeconds", 30f, Ui("HBK: how often the close-up detail checks whether the daylight has changed enough to draw its tiles again. Every change of the light draws every tile on screen once more, and the light changes all the time with weather and time of day - the original checked every 2 seconds. 0 = never: the tiles keep the light they were drawn in.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 600f), "5. Advanced", "Detail: relight every (s)", 13, advanced: true)); BindPortConfig(); MigrateDetailConfig(); } private void MigrateDetailConfig() { ConfigEntry<int> val = ((BaseUnityPlugin)this).Config.Bind<int>("08 Detail", "DetailConfigVersion", 1, Hidden("Internal: which defaults this section has been updated to. Do not edit.")); if (val.Value >= 5) { return; } if (val.Value < 4) { if (val.Value < 3 && !WeakCpu && Mathf.Approximately(_cfgDetailStartSpan.Value, 3000f)) { _cfgDetailStartSpan.Value = 6000f; } if (_cfgDetailWorkers.Value == 2) { _cfgDetailWorkers.Value = 0; } if (WeakCpu && Mathf.Approximately(_cfgDetailStartSpan.Value, 6000f)) { _cfgDetailStartSpan.Value = 3000f; } val.Value = 4; } _cfgDetailPrefetch.Value = true; if (_cfgDetailCache.Value < 256) { _cfgDetailCache.Value = 256; } val.Value = 5; } private Color32 Tone(Color c) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) float num = 0.5f; Color legacyToneTint = LegacyToneTint; float num2 = 0.299f * c.r + 0.587f * c.g + 0.114f * c.b; return Color32.op_Implicit(new Color((c.r + (num2 - c.r) * num) * legacyToneTint.r, (c.g + (num2 - c.g) * num) * legacyToneTint.g, (c.b + (num2 - c.b) * num) * legacyToneTint.b, c.a)); } private static long DZoneKey(int zx, int zz) { return ((long)zx << 32) | (uint)zz; } private void LateUpdate() { if (_disabledByErrors) { return; } try { if (_ready) { UpdateVanillaClouds(); } } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("[clouds] " + ex)); } try { NoticeTick(); } catch (Exception ex2) { _noticeDone = true; ((BaseUnityPlugin)this).Logger.LogError((object)("[notice] " + ex2)); } if ((Object)(object)_probeImg != (Object)null) { try { ProbeTick(); return; } catch (Exception ex3) { ((BaseUnityPlugin)this).Logger.LogError((object)("[probe] " + ex3)); ProbeHide(); return; } } try { if (_ready) { HighTick(); } } catch (Exception ex4) { _highUnavailable = true; ((BaseUnityPlugin)this).Logger.LogError((object)("[high ground] " + ex4)); } if (_dBroken) { return; } try { DetailTick(); } catch (Exception e) { DetailFail("tick", e); } } private void DetailFail(string where, Exception e) { _dBroken = true; ((BaseUnityPlugin)this).Logger.LogError((object)string.Concat("[detail ", where, "] ", e, "\nThe detailed map layer is off for this session; the rest of Living Map keeps working.")); try { DetailTeardown(); } catch { } } private void DetailWorldCheck() { if (_dHeightsWorld != _worldUid) { _dHeightsWorld = _worldUid; _dHeights.Clear(); _dZoneRev.Clear(); } } private void StoreHeightZone(Vector3 zonePos, int pitch, float scale, float[] delta) { //IL_0006: 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_000c: Unknown result type (might be due to invalid IL or missing references) DetailWorldCheck(); Vector2s zone = ZoneSystem.GetZone(zonePos); long key = DZoneKey(zone.x, zone.y); if (delta == null) { _dHeights.Remove(key); } else { HeightZone heightZone = new HeightZone(); heightZone.Cx = zonePos.x; heightZone.Cz = zonePos.z; heightZone.Scale = scale; heightZone.Pitch = pitch; heightZone.Half = pitch / 2; heightZone.D = delta; _dHeights[key] = heightZone; } _heightDirty = true; _dZoneRev.TryGetValue(key, out var value); _dZoneRev[key] = value + 1; } private void DetailTick() { //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Invalid comparison between Unknown and I4 //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_024f: Unknown result type (might be due to invalid IL or missing references) //IL_0254: Unknown result type (might be due to invalid IL or missing references) //IL_04d9: Unknown result type (might be due to invalid IL or missing references) //IL_04be: Unknown result type (might be due to invalid IL or missing references) //IL_050c: Unknown result type (might be due to invalid IL or missing references) //IL_0557: Unknown result type (might be due to invalid IL or missing references) Minimap mm = _mm; if (!_ready || !((Object)(object)mm != (Object)null) || !_cfgDetail.Value || (int)mm.m_mode != 2 || !((Object)(object)mm.m_mapImageLarge != (Object)null) || !((Object)(object)mm.m_largeRoot != (Object)null) || !mm.m_largeRoot.activeInHierarchy) { if ((Object)(object)_dRoot != (Object)null && ((Component)_dRoot).gameObject.activeSelf) { ((Component)_dRoot).gameObject.SetActive(false); } _dViewCovered = false; _dOpenLevel = -1; DropPendingTiles(); if (!_ready && (_dTiles.Count > 0 || _dWorkers != null)) { DetailTeardown(); } return; } DetailWorldCheck(); RawImage mapImageLarge = mm.m_mapImageLarge; Rect uvRect = mapImageLarge.uvRect; float num = (float)_texSize * _pixelSize; UpdateLevels(num); float num2 = ((Rect)(ref uvRect)).width * num; float value = _cfgDetailStartSpan.Value; float num3 = Mathf.Clamp01((value - num2) / (value * 0.2f)); if (num3 <= 0f) { if ((Object)(object)_dRoot != (Object)null && ((Component)_dRoot).gameObject.activeSelf) { ((Component)_dRoot).gameObject.SetActive(false); } _dViewCovered = false; _dOpenLevel = -1; DropPendingTiles(); return; } if (PortWanted) { num3 = 1f; } EnsureDetailLayer(mapImageLarge); if (!((Component)_dRoot).gameObject.activeSelf) { ((Component)_dRoot).gameObject.SetActive(true); } _dGroup.alpha = num3; EnsureWorkers(); _dEnqueuedThisFrame = 0; _dSnapMsFrame = 0.0; _dFrame = Time.frameCount; Canvas canvas = ((Graphic)mapImageLarge).canvas; Rect rect = ((Graphic)mapImageLarge).rectTransform.rect; float num4 = ((Rect)(ref rect)).width * (((Object)(object)canvas != (Object)null) ? canvas.scaleFactor : 1f); float num5 = num2 / Mathf.Max(1f, num4); float num6 = Mathf.Max(1f, _cfgDetailFinest.Value); int num7 = -1; if (PortWanted) { Rect rect2 = ((Graphic)mapImageLarge).rectTransform.rect; float num8 = ((((Rect)(ref rect2)).height > 0f) ? (((Rect)(ref rect2)).width / ((Rect)(ref rect2)).height) : 1f); float num9 = Mathf.Max(1f, mm.m_minZoom * num8 * num); float num10 = ((value > num9) ? Mathf.Clamp01(Mathf.Log(value / Mathf.Max(num2, num9)) / Mathf.Log(value / num9)) : 1f); num7 = Mathf.Min(DLevels.Length - 1, Mathf.FloorToInt(num10 * (float)DLevels.Length)); while (num7 > 0 && DLevels[num7] < num6 * 0.85f) { num7--; } } else { for (int i = 0; i < DLevels.Length && !(DLevels[i] < num6 - 0.01f); i++) { num7 = i; if (DLevels[i] <= num5) { break; } } } if (num7 < 0) { num7 = 0; } float num11 = (((Rect)(ref uvRect)).xMin - 0.5f) * num; float num12 = (((Rect)(ref uvRect)).xMax - 0.5f) * num; float num13 = (((Rect)(ref uvRect)).yMin - 0.5f) * num; float num14 = (((Rect)(ref uvRect)).yMax - 0.5f) * num; while (num7 > 0 && TileCount(num7, num11, num12, num13, num14) > 64) { num7--; } _dShownLevel = num7; _dShownNeed = num5; _dShownAt = Time.realtimeSinceStartup; float cx = (num11 + num12) * 0.5f; float cz = (num13 + num14) * 0.5f; float realtimeSinceStartup = Time.realtimeSinceStartup; bool flag = num7 == _dOpenLevel; int num15 = -1; if (!flag && _dOpenLevel >= 0 && _dOpenLevel < DLevels.Length) { ReadyTiles(_dOpenLevel, num11, num12, num13, num14, out var need, out var have); if (need > 0 && have > 0) { num15 = _dOpenLevel; } } if (num15 < 0) { float num16 = 0f; for (int num17 = num7 - 1; num17 >= 0; num17--) { ReadyTiles(num17, num11, num12, num13, num14, out var need2, out var have2); if (need2 > 0 && have2 > 0) { float num18 = (float)have2 / (float)need2; if (flag || !(num18 < 0.999f)) { if (num18 > num16 + 0.001f) { num16 = num18; num15 = num17; } if (num16 >= 0.999f) { break; } } } } } if (num15 >= 0) { ShowLevel(num15, num11, num12, num13, num14, uvRect, num, realtimeSinceStartup, request: false, cx, cz, place: true); } ShowLevel(num7, num11, num12, num13, num14, uvRect, num, realtimeSinceStartup, request: true, cx, cz, flag); if (!flag && _dViewCovered) { _dOpenLevel = num7; flag = true; ShowLevel(num7, num11, num12, num13, num14, uvRect, num, realtimeSinceStartup, request: true, cx, cz, place: true); } if (!flag) { _dViewCovered = false; } Prefetch(num7, num11, num12, num13, num14, realtimeSinceStartup, cx, cz); if (num15 >= 0 && flag) { HideCoveredFog(num7, num15); } ApplyShown(); UpdateClouds(uvRect); UploadDone(); RecheckTiles(realtimeSinceStartup); RelightTiles(realtimeSinceStartup); Evict(realtimeSinceStartup); } private void ReadyTiles(int level, float vx0, float vx1, float vz0, float vz1, out int need, out int have) { need = 0; have = 0; float num = 256f * DLevels[level]; int num2 = Mathf.FloorToInt(vx0 / num); int num3 = Mathf.FloorToInt(vx1 / num); int num4 = Mathf.FloorToInt(vz0 / num); int num5 = Mathf.FloorToInt(vz1 / num); for (int i = num4; i <= num5; i++) { for (int j = num2; j <= num3; j++) { need++; if (_dTiles.TryGetValue(TileKey(level, j, i), out var value) && value.Ready && (Object)(object)value.Img != (Object)null) { have++; } } } } private static int TileCount(int level, float x0, float x1, float z0, float z1) { float num = 256f * DLevels[level]; int num2 = Mathf.FloorToInt(x1 / num) - Mathf.FloorToInt(x0 / num) + 1; int num3 = Mathf.FloorToInt(z1 / num) - Mathf.FloorToInt(z0 / num) + 1; return num2 * num3; } private static long TileKey(int level, int tx, int tz) { return ((long)level << 58) ^ ((long)(tx & 0x1FFFFFFF) << 29) ^ (tz & 0x1FFFFFFF); } private void ShowLevel(int level, float vx0, float vx1, float vz0, float vz1, Rect uv, float world, float now, bool request, float cx, float cz, bool place) { //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_020a: 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) bool dViewCovered = true; float num = DLevels[level]; float num2 = 256f * num; int num3 = Mathf.FloorToInt(vx0 / num2); int num4 = Mathf.FloorToInt(vx1 / num2); int num5 = Mathf.FloorToInt(vz0 / num2); int num6 = Mathf.FloorToInt(vz1 / num2); Vector2 a = default(Vector2); Vector2 a2 = default(Vector2); for (int i = num5; i <= num6; i++) { for (int j = num3; j <= num4; j++) { long key = TileKey(level, j, i); if (!_dTiles.TryGetValue(key, out var value)) { if (!request) { continue; } DTile dTile = new DTile(); dTile.Level = level; dTile.TX = j; dTile.TZ = i; dTile.Key = key; value = dTile; _dTiles[key] = value; } value.LastUsed = now; float num7 = (float)j * num2; float num8 = (float)i * num2; if (request && !value.Ready && !value.Queued && !value.Failed && CanEnqueue()) { float num9 = num7 + num2 * 0.5f - cx; float num10 = num8 + num2 * 0.5f - cz; Enqueue(value, num9 * num9 + num10 * num10); } if (!value.Ready || (Object)(object)value.Img == (Object)null) { dViewCovered = false; } else if (place) { float num11 = num7; float num12 = num8; if ((Object)(object)value.Img2 != (Object)null) { num11 -= num * 0.5f; num12 -= num * 0.5f; } ((Vector2)(ref a))..ctor((num11 / world + 0.5f - ((Rect)(ref uv)).xMin) / ((Rect)(ref uv)).width, (num12 / world + 0.5f - ((Rect)(ref uv)).yMin) / ((Rect)(ref uv)).height); ((Vector2)(ref a2))..ctor(((num11 + num2) / world + 0.5f - ((Rect)(ref uv)).xMin) / ((Rect)(ref uv)).width, ((num12 + num2) / world + 0.5f - ((Rect)(ref uv)).yMin) / ((Rect)(ref uv)).height); Place(value.Img, request ? _dFront : _dBack, a, a2); value.ShownFrame = _dFrame; if ((Object)(object)value.Img2 != (Object)null) { Place(value.Img2, request ? _dFogFront : _dFogBack, a, a2); value.FogShownFrame = _dFrame; } } } } if (request) { _dViewCovered = dViewCovered; } } private void Prefetch(int level, float vx0, float vx1, float vz0, float vz1, float now, float cx, float cz) { if (_cfgDetailPrefetch == null || !_cfgDetailPrefetch.Value || _dEnqueuedThisFrame > 0 || !CanEnqueue() || level == 0) { return; } float num = 256f * DLevels[level]; int num2 = Mathf.FloorToInt(vx0 / num); int num3 = Mathf.FloorToInt(vx1 / num); int num4 = Mathf.FloorToInt(vz0 / num); int num5 = Mathf.FloorToInt(vz1 / num); for (int i = num4 - 1; i <= num5 + 1; i++) { for (int j = num2 - 1; j <= num3 + 1; j++) { if ((j < num2 || j > num3 || i < num4 || i > num5) && !Want(level, j, i, now, cx, cz, num, 1E+09f)) { return; } } } if (level + 1 >= DLevels.Length) { return; } float num6 = 256f * DLevels[level + 1]; int num7 = Mathf.FloorToInt(vx0 / num6); int num8 = Mathf.FloorToInt(vx1 / num6); int num9 = Mathf.FloorToInt(vz0 / num6); int num10 = Mathf.FloorToInt(vz1 / num6); for (int k = num9; k <= num10; k++) { for (int l = num7; l <= num8; l++) { if (!Want(level + 1, l, k, now, cx, cz, num6, 2E+09f)) { return; } } } } private bool Want(int level, int tx, int tz, float now, float cx, float cz, float t, float prio) { long key = TileKey(level, tx, tz); if (!_dTiles.TryGetValue(key, out var value)) { value = new DTile(); value.Level = level; value.TX = tx; value.TZ = tz; value.Key = key; _dTiles[key] = value; } value.LastUsed = now - 30f; if (value.Ready || value.Queued || value.Failed) { return true; } float num = (float)tx * t + t * 0.5f - cx; float num2 = (float)tz * t + t * 0.5f - cz; Enqueue(value, prio + num * num + num2 * num2); return false; } private static void Place(RawImage img, RectTransform parent, Vector2 a0, Vector2 a1) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_002c: 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_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) RectTransform rectTransform = ((Graphic)img).rectTransform; if ((Object)(object)((Transform)rectTransform).parent != (Object)(object)parent) { ((Transform)rectTransform).SetParent((Transform)(object)parent, false); } if (rectTransform.anchorMin != a0) { rectTransform.anchorMin = a0; } if (rectTransform.anchorMax != a1) { rectTransform.anchorMax = a1; } if (rectTransform.offsetMin != Vector2.zero) { rectTransform.offsetMin = Vector2.zero; } if (rectTransform.offsetMax != Vector2.zero) { rectTransform.offsetMax = Vector2.zero; } } private void ApplyShown() { foreach (DTile value in _dTiles.Values) { if ((Object)(object)value.Img != (Object)null) { bool flag = value.ShownFrame == _dFrame; if (((Behaviour)value.Img).enabled != flag) { ((Behaviour)value.Img).enabled = flag; } } if ((Object)(object)value.Img2 != (Object)null) { bool flag2 = value.FogShownFrame == _dFrame; if (((Behaviour)value.Img2).enabled != flag2) { ((Behaviour)value.Img2).enabled = flag2; } } } } private void HideCoveredFog(int level, int back) { float num = 256f * DLevels[level]; float num2 = 256f * DLevels[back]; foreach (DTile value2 in _dTiles.Values) { if (value2.Level != back || (Object)(object)value2.Img2 == (Object)null || value2.FogShownFrame != _dFrame) { continue; } float num3 = (float)value2.TX * num2; float num4 = (float)value2.TZ * num2; int num5 = Mathf.FloorToInt(num3 / num); int num6 = Mathf.FloorToInt((num3 + num2 - 0.01f) / num); int num7 = Mathf.FloorToInt(num4 / num); int num8 = Mathf.FloorToInt((num4 + num2 - 0.01f) / num); bool flag = true; for (int i = num7; i <= num8; i++) { if (!flag) { break; } for (int j = num5; j <= num6; j++) { if (!flag) { break; } if (!_dTiles.TryGetValue(TileKey(level, j, i), out var value) || (Object)(object)value.Img == (Object)null || value.ShownFrame != _dFrame) { flag = false; } } } if (flag) { value2.FogShownFrame = -1; } } } private void UpdateClouds(Rect uv) { //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_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0109: 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_011a: Unknown result type (might be due to invalid IL or missing references) //IL_011f: 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_0174: Invalid comparison between Unknown and I4 //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_dClouds == (Object)null) { return; } bool flag = PortWanted && CloudStyle == "Smooth" && _port != null && (Object)(object)_port.CloudTex != (Object)null && (Object)(object)_portMat != (Object)null; if (((Behaviour)_dClouds).enabled != flag) { ((Behaviour)_dClouds).enabled = flag; } if (flag) { if ((Object)(object)_dClouds.texture != (Object)(object)_port.CloudTex) { _dClouds.texture = (Texture)(object)_port.CloudTex; } Vector4 globalVector = Shader.GetGlobalVector("_CloudOffset"); _dClouds.uvRect = new Rect(((Rect)(ref uv)).x * 7f - globalVector.x, ((Rect)(ref uv)).y * 7f - globalVector.z, ((Rect)(ref uv)).width * 7f, ((Rect)(ref uv)).height * 7f); Color globalColor = Shader.GetGlobalColor("_SunColor"); Color color = _portMat.GetColor("_lightColor"); Color val = default(Color); ((Color)(ref val))..ctor(Mathf.Clamp01(globalColor.r * color.r), Mathf.Clamp01(globalColor.g * color.g), Mathf.Clamp01(globalColor.b * color.b), 1f); ((Graphic)_dClouds).color = (((int)QualitySettings.activeColorSpace == 1) ? ((Color)(ref val)).gamma : val); } } private string DetailStatus() { if (!_cfgDetail.Value) { return "detail layer off"; } if (_dShownLevel < 0) { return "detail layer not shown yet (zoom the big map in past DetailStartSpanMeters)"; } float num = ((_dShownLevel < DLevels.Length) ? DLevels[_dShownLevel] : 0f); int num2 = ((_dWorkers != null) ? _dWorkers.Length : 0); return string.Format("detail layer {0}, last shown {6:0} s ago: level {1} of {2} ({3:0.##} m per map pixel), {4:0.##} m per screen pixel, so a map pixel is {5:0.#} screen pixels. Cost so far: {7} tiles drawn on {8} background threads ({16} of them a second time, after the cache let them go), {9:0} ms a tile on average (worst {10:0}); {11} snapshots on the main thread, {12:0.0} ms on average (worst {13:0.0}); {14} of {17} tiles cached (~{15:0} MB)", PortWanted ? "vanilla style" : "legacy", _dShownLevel + 1, DLevels.Length, num, _dShownNeed, (_dShownNeed > 0f) ? (num / _dShownNeed) : 0f, Time.realtimeSinceStartup - _dShownAt, _dRendered, num2, (_dRendered > 0) ? (_dMsTotal / (double)_dRendered) : 0.0, _dMsMax, _dSnaps, (_dSnaps > 0) ? (_dSnapMsTotal / (double)_dSnaps) : 0.0, _dSnapMsMax, _dTiles.Count, (double)(_dTiles.Count * 524288) / 1048576.0, _dRedraws, DetailCacheLimit); } private void UpdateLevels(float world) { float[] array; if (PortWanted) { float num = world / 7000f; array = new float[3] { num, 2.6f, 2f }; } else { array = new float[3] { 4f, 2f, 1f }; } bool flag = array.Length == DLevels.Length; int num2 = 0; while (flag && num2 < array.Length) { flag = Mathf.Abs(array[num2] - DLevels[num2]) < 0.0001f; num2++; } if (flag) { return; } DLevels = array; foreach (DTile value in _dTiles.Values) { DestroyTile(value); } _dTiles.Clear(); } private static void DestroyTile(DTile t) { if ((Object)(object)t.Img != (Object)null) { Object.Destroy((Object)(object)((Component)t.Img).gameObject); } if ((Object)(object)t.Img2 != (Object)null) { Object.Destroy((Object)(object)((Component)t.Img2).gameObject); } if ((Object)(object)t.Tex != (Object)null) { Object.Destroy((Object)(object)t.Tex); } if ((Object)(object)t.Tex2 != (Object)null) { Object.Destroy((Object)(object)t.Tex2); } t.Img = null; t.Img2 = null; t.Tex = null; t.Tex2 = null; t.Ready = false; } private void EnsureDetailLayer(RawImage img) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown if ((Object)(object)_dRoot != (Object)null && (Object)(object)((Transform)_dRoot).parent == (Object)(object)((Component)img).transform) { return; } DestroyDetailLayer(); GameObject val = new GameObject("LivingMap detail", new Type[1] { typeof(RectTransform) }); _dRoot = (RectTransform)val.transform; ((Transform)_dRoot).SetParent(((Component)img).transform, false); ((Transform)_dRoot).SetAsFirstSibling(); Stretch(_dRoot); val.AddComponent<RectMask2D>(); _dGroup = val.AddComponent<CanvasGroup>(); _dGroup.blocksRaycasts = false; _dGroup.interactable = false; _dBack = NewLayer("back", _dRoot); _dFront = NewLayer("front", _dRoot); RectTransform val2 = NewLayer("clouds", _dRoot); _dClouds = ((Component)val2).gameObject.AddComponent<RawImage>(); ((Graphic)_dClouds).raycastTarget = false; ((Behaviour)_dClouds).enabled = false; _dFogBack = NewLayer("fog back", _dRoot); _dFogFront = NewLayer("fog front", _dRoot); if (_fiMistColor == null) { _fiMistColor = typeof(Minimap).GetField("m_mistlandsColor", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } if (_fiObjectsBySector == null) { FieldInfo field = typeof(ZDOMan).GetField("m_objectsBySector", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != null && typeof(List<ZDO>[]).IsAssignableFrom(field.FieldType)) { _fiObjectsBySector = field; } else { LogOnce("detail-sectors", "ZDOMan.m_objectsBySector was not found; the detailed map draws the forest pattern and stored footprints only."); } } } private static RectTransform NewLayer(string name, RectTransform parent) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) }); RectTransform val2 = (RectTransform)val.transform; ((Transform)val2).SetParent((Transform)(object)parent, false); Stretch(val2); return val2; } private static void Stretch(RectTransform rt) { //IL_0001: 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_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) rt.anchorMin = Vector2.zero; rt.anchorMax = Vector2.one; rt.offsetMin = Vector2.zero; rt.offsetMax = Vector2.zero; ((Transform)rt).localScale = Vector3.one; } private void DestroyDetailLayer() { foreach (DTile value in _dTiles.Values) { DestroyTile(value); } if ((Object)(object)_dRoot != (Object)null) { Object.Destroy((Object)(object)((Component)_dRoot).gameObject); } _dRoot = null; _dBack = null; _dFront = null; _dFogBack = null; _dFogFront = null; _dGroup = null; _dClouds = null; } private void DetailTeardown() { StopWorkers(); DestroyDetailLayer(); _dTiles.Clear(); _dEverDrawn.Clear(); _dRedraws = 0; _dSectorSig.Clear(); _dOpenLevel = -1; lock (_dLock) { _dPending.Clear(); _dDone.Clear(); } } private void TileArea(DTile t, out float x0, out float z0, out float size, out int fx0, out int fz0, out int w) { float num = DLevels[t.Level]; size = 256f * num; x0 = (float)t.TX * size; z0 = (float)t.TZ * size; float num2 = (float)_texSize * 0.5f; fx0 = Mathf.FloorToInt(x0 / _pixelSize + num2) - 1; fz0 = Mathf.FloorToInt(z0 / _pixelSize + num2) - 1; w = Mathf.CeilToInt(size / _pixelSize) + 3; } private long RegionSig(DTile t) { TileArea(t, out var x, out var z, out var size, out var fx, out var fz, out var w); BitArray bitArray = ((_fiExplored != null) ? (_fiExplored.GetValue(_mm) as BitArray) : null); BitArray exploredOthers = ((_fiExploredOthers != null) ? (_fiExploredOthers.GetValue(_mm) as BitArray) : null); bool value = _cfgRespectFog.Value; bool value2 = _cfgShowBuildings.Value; long num = 17L; for (int i = 0; i < w; i++) { for (int j = 0; j < w; j++) { int num2 = fx + j; int num3 = fz + i; if (num2 >= 0 && num3 >= 0 && num2 < _texSize && num3 < _texSize) { int num4 = num3 * _texSize + num2; if (!value || IsExplored(bitArray, exploredOthers, num4)) { num += ((bitArray == null || num4 >= bitArray.Length || !bitArray[num4]) ? 1 : 2); } if (_plantedForest.Contains(num4)) { num += 7919; } else if (_clearedForest.Contains(num4)) { num += 104729; } else if (_pathForest.Contains(num4)) { num += 15485863; } if (value2 && _pieces.TryGetValue(num4, out var value3)) { num += (long)value3.Count * 131L; } } } } float zs = (((Object)(object)ZoneSystem.instance != (Object)null) ? ZoneSystem.instance.m_zoneSize : 64f); TileZones(x, z, size, zs, out var zx, out var zz, out var zx2, out var zz2); List<ZDO>[] array = ((DLevels[t.Level] <= 2.9f && _cfgDetailObjects.Value) ? Sectors() : null); for (int k = zz; k <= zz2; k++) { for (int l = zx; l <= zx2; l++) { if (_dZoneRev.TryGetValue(DZoneKey(l, k), out var value4)) { num += (long)value4 * 1000003L; } if (array != null) { num += SectorObjectSig(array, l, k) * 65537; } } } num += (_cfgShowBuildings.Value ? 1 : 0) * 3 + (_cfgShowPaths.Value ? 1 : 0) * 5 + (_cfgShowCleared.Value ? 1 : 0) * 11; num += (PortClassicFirst ? 13 : 0); return num + (long)(PaletteStrength * 1000f) * 37; } private static void TileZones(float x0, float z0, float size, float zs, out int zx0, out int zz0, out int zx1, out int zz1) { zx0 = Mathf.FloorToInt(x0 / zs + 0.5f) - 1; zx1 = Mathf.FloorToInt((x0 + size) / zs + 0.5f) + 1; zz0 = Mathf.FloorToInt(z0 / zs + 0.5f) - 1; zz1 = Mathf.FloorToInt((z0 + size) / zs + 0.5f) + 1; } private long SectorObjectSig(List<ZDO>[] sectors, int zx, int zz) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) uint sector = ZoneSystem.SectorToIndex(zx, zz).Sector; if (sector >= sectors.Length) { return 0L; } float realtimeSinceStartup = Time.realtimeSinceStartup; if (_dSectorSig.TryGetValue(sector, out var value) && realtimeSinceStartup - value.At < 2f) { return value.Sig; } long num = 0L; List<ZDO> list = sectors[sector]; if (list != null) { for (int i = 0; i < list.Count; i++) { ZDO val = list[i]; if (val != null) { int prefab = val.GetPrefab(); if (prefab != 0 && DKind(prefab) != 0) { num += 1 + (prefab & 0xFFFF); } } } } if (value == null) { value = new SectorSig(); _dSectorSig[sector] = value; } value.Sig = num; value.At = realtimeSinceStartup; return num; } private List<ZDO>[] Sectors() { if (_fiObjectsBySector == null || ZDOMan.instance == null) { return null; } return _fiObjectsBySector.GetValue(ZDOMan.instance) as List<ZDO>[]; } private static List<ZDO> SectorList(List<ZDO>[] sectors, int zx, int zz) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) if (sectors == null) { return null; } uint sector = ZoneSystem.SectorToIndex(zx, zz).Sector; if (sector >= sectors.Length) { return null; } return sectors[sector]; } private bool CanEnqueue() { if (_dEnqueuedThisFrame >= 2) { return false; } if (_dEnqueuedThisFrame > 0 && _dSnapMsFrame > 4.0) { return false; } int count; lock (_dLock) { count = _dPending.Count; } return count < Mathf.Max(2, DetailThreads * 2); } private void Enqueue(DTile tile, float priority) { Enqueue(tile, priority, relight: false); } private void Enqueue(DTile tile, float priority, bool relight) { _dEnqueuedThisFrame++; if (!_dEverDrawn.Add(tile.Key) && !relight) { _dRedraws++; } long timestamp = Stopwatch.GetTimestamp(); DJob dJob = BuildJob(tile, priority, relight); double num = (double)(Stopwatch.GetTimestamp() - timestamp) * 1000.0 / (double)Stopwatch.Frequency; _dSnaps++; _dSnapMsTotal += num; if (num > _dSnapMsMax) { _dSnapMsMax = num; } _dSnapMsFrame += num; if (num > 20.0 && _cfgDebug.Value) { ((BaseUnityPlugin)this).Logger.LogInfo((object)$"Slow snapshot: {num:0.0} ms at level {tile.Level + 1} ({DLevels[tile.Level]:0.##} m/px), tile ({tile.TX}, {tile.TZ}): {((dJob.Pieces != null) ? dJob.Pieces.Count : 0)} pieces, {((dJob.Boxes != null) ? dJob.Boxes.Count : 0)} boxes, {((dJob.Trees != null) ? dJob.Trees.Count : 0)} trees/rocks, {((dJob.TerrKeys != null) ? dJob.TerrKeys.Count : 0)} path cells, {((dJob.Heights != null) ? dJob.Heights.Count : 0)} zones"); } tile.Queued = true; lock (_dLock) { _dPending.Add(dJob); Monitor.Pulse(_dLock); } } private DJob BuildJob(DTile tile, float priority, bool relight) { //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: 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_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: 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_0211: Unknown result type (might be due to invalid IL or missing references) //IL_0216: Unknown result type (might be due to invalid IL or missing references) //IL_021b: 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_0233: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_024b: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_0268: 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_0272: 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_0289: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Unknown result type (might be due to invalid IL or missing references) //IL_02a5: 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_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_02c4: Unknown result type (might be due to invalid IL or missing references) //IL_02eb: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_02f5: Unknown result type (might be due to invalid IL or missing references) //IL_02fa: 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_031c: 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_0326: 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_0335: 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_033f: 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_0138: Unknown result type (might be due to invalid IL or missing references) //IL_013f: 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_0149: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015a: 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_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_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_084d: Unknown result type (might be due to invalid IL or missing references) //IL_0852: Unknown result type (might be due to invalid IL or missing references) //IL_0857: Unknown result type (might be due to invalid IL or missing references) //IL_085c: Unknown result type (might be due to invalid IL or missing references) //IL_087c: Unknown result type (might be due to invalid IL or missing references) //IL_0881: Unknown result type (might be due to invalid IL or missing references) //IL_0886: Unknown result type (might be due to invalid IL or missing references) //IL_0894: Unknown result type (might be due to invalid IL or missing references) //IL_0899: Unknown result type (might be due to invalid IL or missing references) //IL_089e: Unknown result type (might be due to invalid IL or missing references) //IL_0a9e: Unknown result type (might be due to invalid IL or missing references) //IL_0aa3: Unknown result type (might be due to invalid IL or missing references) //IL_0aa8: Unknown result type (might be due to invalid IL or missing references) //IL_0ab6: Unknown result type (might be due to invalid IL or missing references) //IL_0abb: Unknown result type (might be due to invalid IL or missing references) //IL_0ac0: Unknown result type (might be due to invalid IL or missing references) //IL_0ace: Unknown result type (might be due to invalid IL or missing references) //IL_0ad3: Unknown result type (might be due to invalid IL or missing references) //IL_0ad8: Unknown result type (might be due to invalid IL or missing references) //IL_0ae6: Unknown result type (might be due to invalid IL or missing references) //IL_0aeb: Unknown result type (might be due to i
plugins/Tides/Tides.dll
Decompiled 5 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Permissions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using HarmonyLib; using Jotunn; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using Tides.Commands; using Tides.Compatibility; using Tides.Core; using Tides.Systems; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Tides")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Tides")] [assembly: AssemblyCopyright("Copyright © 2026")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("e3243d22-4307-4008-ba36-9f326008cde5")] [assembly: AssemblyFileVersion("1.3.1")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.3.1.0")] namespace Tides { [BepInPlugin("com.naexn.Tides", "Tides", "1.3.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] internal class Tides : BaseUnityPlugin { public const string PluginGUID = "com.naexn.Tides"; public const string PluginName = "Tides"; public const string PluginVersion = "1.3.1"; public static CustomLocalization Localization = LocalizationManager.Instance.GetLocalization(); private void Awake() { //IL_006f: 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_007f: Expected O, but got Unknown Logger.LogInfo((object)"Tides has landed"); CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new TidesInfoCommand()); CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new TidesDiagCommand()); CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new TidesDebugLilyCommand()); CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new TidesDebugCattailCommand()); SeasonsCompat.CheckForCompatibility(); SeasonalityCompat.CheckForCompatibility(); TidesConfig.SetupLocalizations(); TidesConfig.CreateConfigValues(((BaseUnityPlugin)this).Config); TideSystem.ApplyConfigModifications(); TidesConfig.RegisterChangeCallbacks(); Harmony val = new Harmony("com.naexn.Tides"); val.PatchAll(); SeasonalityCompat.Initialize(val); } } } namespace Tides.Systems { internal class SwampMovementSystem { private static float BaseWaterLevel => TideSystem.OceanBaseY - 0.1f; internal static float ComputeSwampVariant(Character c, float baseSpeed) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: 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_001a: Invalid comparison between Unknown and I4 //IL_0023: 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) Vector3 position = ((Component)c).transform.position; Biome biome = WorldGenerator.instance.GetBiome(position); if ((int)biome != 2) { return baseSpeed; } float groundHeight = ZoneSystem.instance.GetGroundHeight(position); float num = BaseWaterLevel - groundHeight; if (num <= 0f) { return baseSpeed; } float num2 = c.m_collider.height / 3f; float num3 = Mathf.Clamp01(num / num2); float num4 = baseSpeed; num4 -= num4 * num4 * num3 * 0.05f; if (Diagnostics.DebugSwampMovementEnabled) { Logger.LogInfo((object)$"SWAMP: Biome={biome}, GroundY={groundHeight}, Depth={num}, DepthFactor={num3}, BaseSpeed={baseSpeed}, ResultSpeed={num4}"); } return num4; } } internal class TideSystem { internal static float TidePeriodDays = 0.5175f; internal static float TideAmplitude = 1.4f; internal static float OceanBaseY = 30f; internal static float _lastTideOffset = 0f; private static bool _debugTidesEnabled = false; private static Transform _waterPlane; internal static void UpdateTides() { //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_0245: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || TideAmplitude == 0f) { return; } if ((Object)(object)_waterPlane == (Object)null) { if (Diagnostics.DebugTidesEnabled && _debugTidesEnabled) { Logger.LogWarning((object)"Waterplane is null, trying to get and cache."); } CacheWaterPlane(); } float num = (float)EnvMan.instance.GetDay() + EnvMan.instance.GetDayFraction(); float tideOffset = Mathf.Sin(num / TidePeriodDays * (float)Math.PI * 2f) * TideAmplitude; float baseWaterY = OceanBaseY; ApplyCompatibilityModifiers(ref tideOffset, ref baseWaterY); _lastTideOffset = tideOffset; float num2 = baseWaterY + tideOffset; if ((Object)(object)_waterPlane != (Object)null) { if (Diagnostics.DebugTidesEnabled && _debugTidesEnabled) { Logger.LogWarning((object)"Waterplane is not null, applying transform."); } Vector3 position = _waterPlane.position; position.y = num2; _waterPlane.position = position; } else if (Diagnostics.DebugTidesEnabled && _debugTidesEnabled) { Logger.LogWarning((object)"Waterplane is null, skipping transform."); } foreach (WaterVolume instance in WaterVolume.Instances) { if ((Object)(object)instance == (Object)null) { continue; } Material material = ((Renderer)instance.m_waterSurface).material; if (!((Object)(object)material == (Object)null) && !(((Object)material).name.ToLowerInvariant() != "water (instance)")) { Vector3 position2 = ((Component)instance).transform.position; position2.y = num2; ((Component)instance).transform.position = position2; Vector3 position3 = ((Component)instance.m_waterSurface).transform.position; position3.y = num2; ((Component)instance.m_waterSurface).transform.position = position3; if (Diagnostics.DebugTidesEnabled && _debugTidesEnabled) { Logger.LogInfo((object)$"offset={tideOffset}m, worldDay={num}, Day={EnvMan.instance.GetDay()} + Frac={EnvMan.instance.GetDayFraction()} = WorldDays={(float)EnvMan.instance.GetDay() + EnvMan.instance.GetDayFraction()}, finalY={num2}m , physPos={((Component)instance).transform.position.y}m, visualPos={((Component)instance.m_waterSurface).transform.position.y}m"); _debugTidesEnabled = false; } } } } internal static void ApplyConfigModifications() { float value = TidesConfig.TideAmplitude.Value; float value2 = TidesConfig.BaseWaterLevel.Value; float value3 = TidesConfig.TideSpeedMultiplier.Value; float num = Mathf.Clamp(value, 0f, 3f); float num2 = Mathf.Clamp(value2, 26f, 34f); float num3 = Mathf.Clamp(value3, 0.1f, 5f); if (num != TideAmplitude) { if (Diagnostics.DebugTidesEnabled && _debugTidesEnabled) { Logger.LogInfo((object)$"Tide amplitude modified from {TideAmplitude}m to {num}m"); } TideAmplitude = num; } if (num2 != OceanBaseY) { if (Diagnostics.DebugTidesEnabled && _debugTidesEnabled) { Logger.LogInfo((object)$"Base water level modified from {OceanBaseY}m to {num2}m"); } OceanBaseY = num2; } if (num3 != 1f) { if (Diagnostics.DebugTidesEnabled && _debugTidesEnabled) { Logger.LogInfo((object)$"Tide speed multiplier modified to {num3}x"); } TidePeriodDays = 0.5175f / num3; } } internal static void CacheWaterPlane() { GameObject obj = GameObject.Find("WaterPlane"); _waterPlane = ((obj != null) ? obj.transform : null); if (Diagnostics.DebugTidesEnabled && _debugTidesEnabled) { if ((Object)(object)_waterPlane == (Object)null) { Logger.LogWarning((object)"Failed to find WaterPlane."); } Logger.LogWarning((object)"WaterPlane found."); } } internal static void ApplyCompatibilityModifiers(ref float tideOffset, ref float baseWaterY) { float num = 0f; if (true) { num = Mathf.Max(num, SeasonsCompat.GetWaterFreezeStatus()); } if (SeasonalityCompat.IsEnabled && SeasonalityCompat.IsWaterFrozen) { num = 1f; } if (!(num <= 0f)) { tideOffset *= 1f - num; baseWaterY = Mathf.Lerp(baseWaterY, 30f, num); } } } internal static class VegetationSystem { private class WaterLilyInstance { public Matrix4x4 OriginalMatrix; public float MinOffset; public float MaxOffset; } private class WaterLiliesBatch { public InstanceRenderer Renderer; public WaterLilyInstance[] WaterLilies; } private class CattailsBatch { public InstanceRenderer Renderer; public Matrix4x4[] OriginalMatrices; } private const float MinLilyMaxOffset = 0.4f; private const float MaxLilyMaxOffset = 2f; private const float LilyMinGroundHeight = 0.2f; private const float CattailStartDepth = 0.45f; private const float CattailMaxDepth = 1.4f; private const float CattailMaxOffset = -1.1f; private static readonly List<WaterLiliesBatch> _waterLilies = new List<WaterLiliesBatch>(); private static readonly List<CattailsBatch> _cattails = new List<CattailsBatch>(); private static readonly HashSet<InstanceRenderer> _pendingLilies = new HashSet<InstanceRenderer>(); private static readonly HashSet<InstanceRenderer> _pendingCattails = new HashSet<InstanceRenderer>(); private static FieldInfo _instancesField; private static FieldInfo _instanceCountField; private static FieldInfo _dirtyBoundsField; private static bool _initialized; internal static void Initialize() { if (!_initialized) { _instancesField = typeof(InstanceRenderer).GetField("m_instances", BindingFlags.Instance | BindingFlags.NonPublic); _instanceCountField = typeof(InstanceRenderer).GetField("m_instanceCount", BindingFlags.Instance | BindingFlags.NonPublic); _dirtyBoundsField = typeof(InstanceRenderer).GetField("m_dirtyBounds", BindingFlags.Instance | BindingFlags.NonPublic); _initialized = true; } } internal static void Update(float tideOffset) { Initialize(); InstanceRenderer[] array = _pendingLilies.ToArray(); foreach (InstanceRenderer val in array) { if ((int)_instanceCountField.GetValue(val) > 0) { TryRegister(val); _pendingLilies.Remove(val); } } array = _pendingCattails.ToArray(); foreach (InstanceRenderer val2 in array) { if ((int)_instanceCountField.GetValue(val2) > 0) { RegisterCattails(val2); _pendingCattails.Remove(val2); } } foreach (WaterLiliesBatch waterLily in _waterLilies) { if (!((Object)(object)waterLily.Renderer == (Object)null)) { ApplyWaterLilyOffset(waterLily); } } } internal static void TryRegister(InstanceRenderer renderer) { Initialize(); if (!((Object)(object)renderer == (Object)null) && !((Object)(object)renderer.m_material == (Object)null)) { if (((Object)renderer.m_material).name == "clutter_waterlilies") { RegisterWaterLilies(renderer); } else if (((Object)renderer.m_material).name == "vass") { RegisterCattails(renderer); } } } internal static void RegisterWaterLilies(InstanceRenderer renderer) { //IL_00c1: 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_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: 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) foreach (WaterLiliesBatch waterLily in _waterLilies) { if ((Object)(object)waterLily.Renderer == (Object)(object)renderer) { return; } } Matrix4x4[] array = (Matrix4x4[])_instancesField.GetValue(renderer); int num = (int)_instanceCountField.GetValue(renderer); if (num == 0) { if (Diagnostics.DebugVegetationEnabled) { Logger.LogInfo((object)"Waterlily renderer created but has no instances yet"); } if (!_pendingLilies.Contains(renderer)) { _pendingLilies.Add(renderer); } return; } if (Diagnostics.DebugVegetationEnabled) { Logger.LogWarning((object)$"Registering water lilies. Count={num}"); } WaterLilyInstance[] array2 = new WaterLilyInstance[num]; for (int i = 0; i < num; i++) { Vector3 val = Vector4.op_Implicit(((Matrix4x4)(ref array[i])).GetColumn(3)); float groundHeight = ZoneSystem.instance.GetGroundHeight(val); array2[i] = new WaterLilyInstance { OriginalMatrix = array[i], MinOffset = groundHeight + 0.2f - TideSystem.OceanBaseY, MaxOffset = Random.Range(0.4f, 2f) }; } WaterLiliesBatch waterLiliesBatch = new WaterLiliesBatch { Renderer = renderer, WaterLilies = array2 }; _waterLilies.Add(waterLiliesBatch); ApplyWaterLilyOffset(waterLiliesBatch); } internal static void RegisterCattails(InstanceRenderer renderer) { foreach (CattailsBatch cattail in _cattails) { if ((Object)(object)cattail.Renderer == (Object)(object)renderer) { return; } } Matrix4x4[] sourceArray = (Matrix4x4[])_instancesField.GetValue(renderer); int num = (int)_instanceCountField.GetValue(renderer); if (num == 0) { if (Diagnostics.DebugVegetationEnabled) { Logger.LogInfo((object)"Cattail renderer created but has no instances yet"); } if (!_pendingCattails.Contains(renderer)) { _pendingCattails.Add(renderer); } return; } if (Diagnostics.DebugVegetationEnabled) { Logger.LogWarning((object)$"Registering cattails. Count={num}"); } Matrix4x4[] array = (Matrix4x4[])(object)new Matrix4x4[num]; Array.Copy(sourceArray, array, num); CattailsBatch cattailsBatch = new CattailsBatch { Renderer = renderer, OriginalMatrices = array }; _cattails.Add(cattailsBatch); ApplyCattailOffset(cattailsBatch); } private static void ApplyWaterLilyOffset(WaterLiliesBatch batch) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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) Matrix4x4[] array = (Matrix4x4[])_instancesField.GetValue(batch.Renderer); for (int i = 0; i < batch.WaterLilies.Length; i++) { WaterLilyInstance waterLilyInstance = batch.WaterLilies[i]; Matrix4x4 originalMatrix = waterLilyInstance.OriginalMatrix; float num = Mathf.Clamp(TideSystem._lastTideOffset, waterLilyInstance.MinOffset, waterLilyInstance.MaxOffset); ((Matrix4x4)(ref originalMatrix))[1, 3] = ((Matrix4x4)(ref originalMatrix))[1, 3] + num; array[i] = originalMatrix; } } private static void ApplyCattailOffset(CattailsBatch batch) { //IL_0035: 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_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_0048: 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_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) Matrix4x4[] array = (Matrix4x4[])_instancesField.GetValue(batch.Renderer); if (Diagnostics.DebugVegetationEnabled) { Logger.LogInfo((object)"Cattail - about to apply offset"); } for (int i = 0; i < batch.OriginalMatrices.Length; i++) { Matrix4x4 val = batch.OriginalMatrices[i]; Vector3 val2 = Vector4.op_Implicit(((Matrix4x4)(ref val)).GetColumn(3)); float groundHeight = ZoneSystem.instance.GetGroundHeight(val2); float num = TideSystem.OceanBaseY - groundHeight; float num2 = CalculateCattailOffset(num); if (Diagnostics.DebugVegetationEnabled) { Logger.LogInfo((object)$"Cattail originally at {num} from base, moved by {num2}"); } ((Matrix4x4)(ref val))[1, 3] = ((Matrix4x4)(ref val))[1, 3] + num2; array[i] = val; } } private static float CalculateCattailOffset(float depth) { if (depth <= 0.45f) { return 0f; } float num = Mathf.InverseLerp(0.45f, 1.4f, depth); return Mathf.Lerp(0f, -1.1f, num); } internal static void TestMoveVegetation(string vegetation) { foreach (IMonoUpdater instance in InstanceRenderer.Instances) { InstanceRenderer val = (InstanceRenderer)(object)((instance is InstanceRenderer) ? instance : null); if (val == null || (Object)(object)val.m_material == (Object)null) { continue; } if (Diagnostics.DebugVegetationEnabled) { Logger.LogInfo((object)("Renderer found: " + ((Object)val.m_material).name)); } if (((Object)val.m_material).name != vegetation) { continue; } Matrix4x4[] array = (Matrix4x4[])_instancesField.GetValue(val); int num = (int)_instanceCountField.GetValue(val); if (Diagnostics.DebugVegetationEnabled) { Logger.LogInfo((object)$"{vegetation}: {num}"); } for (int i = 0; i < num; i++) { float num2 = ((Matrix4x4)(ref array[i]))[1, 3]; if (Diagnostics.DebugVegetationEnabled) { Logger.LogInfo((object)$"{vegetation} instance {i}: Y={num2}"); } ref Matrix4x4 reference = ref array[i]; ((Matrix4x4)(ref reference))[1, 3] = ((Matrix4x4)(ref reference))[1, 3] + 2f; } if (Diagnostics.DebugVegetationEnabled) { Logger.LogInfo((object)("Moved " + vegetation + " +2")); } } } } } namespace Tides.Patches { internal class InstanceRendererPatches { [HarmonyPatch(typeof(InstanceRenderer), "OnEnable")] internal static class InstanceRendererPatch { private static void Postfix(InstanceRenderer __instance) { VegetationSystem.TryRegister(__instance); } } } internal class SwampMovementPatches { [HarmonyPatch(typeof(Character), "ApplyLiquidResistance")] public static class ApplyLiquidResistance_Patch { private static void Prefix(ref float speed, ref float __state) { __state = speed; } private static void Postfix(Character __instance, ref float speed, float __state) { float num = speed; float num2 = SwampMovementSystem.ComputeSwampVariant(__instance, __state); speed = Mathf.Min(num, num2); if (Diagnostics.DebugSwampMovementEnabled) { Logger.LogInfo((object)$"SWAMP RUN: Original={__state}, Vanilla={num}, SwampPeat={num2}, Final={speed}"); } } } } internal class ZNetReadyPatches { [HarmonyPatch(typeof(ZNet), "Update")] internal static class ZNet_Update_Patch { private static void Postfix() { TidesManager.Update(); } } [HarmonyPatch(typeof(ZNet), "Start")] internal static class ZNet_Start_Patch { private static void Postfix() { TidesManager.SetWorldReady(ready: true); } } [HarmonyPatch(typeof(ZNet), "OnDestroy")] internal static class ZNet_Destroy_Patch { private static void Prefix() { TidesManager.SetWorldReady(ready: false); } } } } namespace Tides.Core { internal class Diagnostics { internal static bool DebugTidesEnabled; internal static bool DebugVegetationEnabled; internal static bool DebugSwampMovementEnabled; public static void MasterSwitchOff() { DebugTidesEnabled = false; DebugVegetationEnabled = false; DebugSwampMovementEnabled = false; } } internal class TidesConfig { internal static ConfigEntry<float> TideAmplitude; internal static ConfigEntry<float> BaseWaterLevel; internal static ConfigEntry<float> TideSpeedMultiplier; internal static ConfigEntry<string> TidePresetButtons; private static bool _isApplyingPreset; internal static void CreateConfigValues(ConfigFile config) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Expected O, but got Unknown //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Expected O, but got Unknown //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Expected O, but got Unknown TidePresetButtons = config.Bind<string>("General", "Presets", "Default", new ConfigDescription(Localization.instance.Localize("$tides_config_preset_desc"), (AcceptableValueBase)null, new object[1] { GetAttrWithOrder(10, DrawPresetButtonsDrawer) })); TideAmplitude = config.Bind<float>("General", "Tide Amplitude", 1.4f, new ConfigDescription(Localization.instance.Localize("$tides_amplitude_desc"), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 3f), new object[1] { GetAttrWithOrder(8) })); BaseWaterLevel = config.Bind<float>("General", "Base Ocean Level", 30f, new ConfigDescription(Localization.instance.Localize("$tides_waterlevel_desc"), (AcceptableValueBase)(object)new AcceptableValueRange<float>(26f, 34f), new object[1] { GetAttrWithOrder(6) })); TideSpeedMultiplier = config.Bind<float>("General", "Tide Speed Multiplier", 1f, new ConfigDescription(Localization.instance.Localize("$tides_speed_desc"), (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 5f), new object[1] { GetAttrWithOrder(4) })); } internal static void RegisterChangeCallbacks() { TideAmplitude.SettingChanged += delegate { TideSystem.ApplyConfigModifications(); MarkPresetCustom(); }; BaseWaterLevel.SettingChanged += delegate { TideSystem.ApplyConfigModifications(); MarkPresetCustom(); }; TideSpeedMultiplier.SettingChanged += delegate { TideSystem.ApplyConfigModifications(); MarkPresetCustom(); }; TidePresetButtons.SettingChanged += delegate { if (TidePresetButtons.Value == "Default") { _isApplyingPreset = true; TideAmplitude.Value = 1.4f; BaseWaterLevel.Value = 30f; TideSpeedMultiplier.Value = 1f; _isApplyingPreset = false; } }; } private static void MarkPresetCustom() { if (!_isApplyingPreset) { TidePresetButtons.Value = "Custom"; } } internal static void SetupLocalizations() { if (Localization.instance.GetSelectedLanguage() == "Czech") { Localization.instance.AddWord("tides_preset_default", "Výchozí"); Localization.instance.AddWord("tides_preset_default_desc", "Doporučená nastavení. Vyvážená primárně pro hratelnost."); Localization.instance.AddWord("tides_preset_realistic", "Realistické"); Localization.instance.AddWord("tides_preset_realistic_desc", "Nejrealističtější nastavení, bez záplav, omezuje některé zajímavé herní prvky."); Localization.instance.AddWord("tides_preset_visuals", "Vizuály"); Localization.instance.AddWord("tides_preset_visuals_desc", "Upřednostňuje dramatické vizuální efekty (výrazně ovlivňuje hratelnost pro bažiny, řeky a přístavy)."); Localization.instance.AddWord("tides_config_preset_desc", "Kliknutím na předvolbu rychle nastavíte hodnoty přílivu."); Localization.instance.AddWord("tides_amplitude_desc", "Maximální Rozsah přílivu v metrech.\n1.4 = doporučená amplituda.\nUrčuje maximální výšku přílivu a minimální výšku odlivu od základní hladiny oceánu.\nPři hodnotě 0 nejsou žádné přílivy."); Localization.instance.AddWord("tides_waterlevel_desc", "Základní hladina oceánu v metrech.\n30.0 = normální hladina.\nVyšší hodnoty zvedají celkovou hladinu oceánu."); Localization.instance.AddWord("tides_speed_desc", "Násobí rychlost cyklu přílivu.\n1.0 = normální rychlost.\nVyšší hodnoty způsobují rychlejší změny přílivu.\nPři rychlosti 0.1x se příliv opakuje cca jednou za 5 dní.\nPři rychlosti 5x nastává příliv cca 10x za den."); } else { Localization.instance.AddWord("tides_preset_default", "Default"); Localization.instance.AddWord("tides_preset_default_desc", "Recommended settings. Balanced primarily for gameplay."); Localization.instance.AddWord("tides_preset_realistic", "Realistic"); Localization.instance.AddWord("tides_preset_realistic_desc", "The most realistic settings, without floods, limiting some interesting gameplay aspects."); Localization.instance.AddWord("tides_preset_visuals", "Visuals"); Localization.instance.AddWord("tides_preset_visuals_desc", "Prioritizing dramatic visual effects (heavily affects gameplay in swamps, rivers and docks)."); Localization.instance.AddWord("tides_config_preset_desc", "Click a preset button to quickly configure tide settings."); Localization.instance.AddWord("tides_amplitude_desc", "Maximum tide amplitude in meters.\n1.4 = recommended amplitude.\nDecides maximum height of high tide and minimal height of low tide from the base ocean level.\nAt value 0 there are no tides."); Localization.instance.AddWord("tides_waterlevel_desc", "Base ocean level in meters.\n30.0 = normal level.\nHigher values raise the whole ocean level."); Localization.instance.AddWord("tides_speed_desc", "Multiplies the speed of the tide cycle.\n1.0 = normal speed.\nHigher values make tides change faster.\nAt 0.1x speed high tide repeats cca once every 5 days.\nAt 5x speed high tide happens cca 10x per day."); } } private static ConfigurationManagerAttributes GetAttrWithOrder(int order, Action<ConfigEntryBase> drawer = null) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: 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_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown return new ConfigurationManagerAttributes { IsAdminOnly = true, Order = order, CustomDrawer = drawer }; } private static void DrawPresetButtonsDrawer(ConfigEntryBase entry) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Expected O, but got Unknown //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Expected O, but got Unknown GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button(new GUIContent(Localization.instance.Localize("$tides_preset_default"), Localization.instance.Localize("$tides_preset_default_desc")), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(25f) })) { TidePresetButtons.Value = "Default"; TideAmplitude.Value = 1.4f; BaseWaterLevel.Value = 30f; TideSpeedMultiplier.Value = 1f; } if (GUILayout.Button(new GUIContent(Localization.instance.Localize("$tides_preset_realistic"), Localization.instance.Localize("$tides_preset_realistic_desc")), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(25f) })) { TidePresetButtons.Value = "Realistic"; TideAmplitude.Value = 0.75f; BaseWaterLevel.Value = 29.3f; TideSpeedMultiplier.Value = 1f; } if (GUILayout.Button(new GUIContent(Localization.instance.Localize("$tides_preset_visuals"), Localization.instance.Localize("$tides_preset_visuals_desc")), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(25f) })) { TidePresetButtons.Value = "Visuals"; TideAmplitude.Value = 2.1f; BaseWaterLevel.Value = 28.1f; TideSpeedMultiplier.Value = 1f; } GUILayout.EndHorizontal(); } } internal class TidesManager { private static bool _worldReady; public static void SetWorldReady(bool ready) { _worldReady = ready; } public static void Update() { if (_worldReady) { TideSystem.UpdateTides(); VegetationSystem.Update(TideSystem._lastTideOffset); if (Diagnostics.DebugTidesEnabled) { Logger.LogInfo((object)$"_lastTideOffset={TideSystem._lastTideOffset}"); } } } } } namespace Tides.Compatibility { public static class SeasonalityCompat { public const string GUID = "RustyMods.Seasonality"; public static bool IsEnabled { get; private set; } public static bool IsWaterFrozen { get; private set; } public static void CheckForCompatibility() { IsEnabled = Chainloader.PluginInfos.TryGetValue("RustyMods.Seasonality", out var _); } public static void Initialize(Harmony harmony) { CheckForCompatibility(); if (!IsEnabled) { return; } try { if (Chainloader.PluginInfos.TryGetValue("RustyMods.Seasonality", out var value)) { Assembly assembly = ((object)value.Instance).GetType().Assembly; Type type = assembly.GetType("Seasonality.FrozenZones"); Type type2 = assembly.GetType("Seasonality.FrozenWaterLOD"); PatchMethod(harmony, type, "FreezeWater", "Prefix_FreezeWater"); PatchMethod(harmony, type, "ThawWater", "Prefix_ThawWater"); PatchMethod(harmony, type2, "Freeze", "Prefix_LOD_Freeze"); PatchMethod(harmony, type2, "Thaw", "Prefix_LOD_Thaw"); PatchMethod(harmony, type2, "SetInitialValues", "Prefix_LOD_SetInitial"); Logger.LogInfo((object)"[Tides] Successfully bound Seasonality compatibility hooks."); } } catch (Exception ex) { Debug.LogWarning((object)("[Tides] Failed to initialize Seasonality compatibility patches: " + ex.Message)); } } private static void PatchMethod(Harmony harmony, Type targetType, string methodName, string patchMethodName) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown if (!(targetType == null)) { MethodInfo method = targetType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo method2 = typeof(SeasonalityCompat).GetMethod(patchMethodName, BindingFlags.Static | BindingFlags.NonPublic); if (method != null && method2 != null) { harmony.Patch((MethodBase)method, new HarmonyMethod(method2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } } private static void ForceWaterFlatToBaseline(object frozenZonesInstance) { //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_0055: 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_0079: 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) IsWaterFrozen = true; try { object? obj = frozenZonesInstance.GetType().GetField("m_waterVolume", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(frozenZonesInstance); WaterVolume val = (WaterVolume)((obj is WaterVolume) ? obj : null); if (val != null && (Object)(object)val != (Object)null) { Vector3 position = ((Component)val).transform.position; position.y = 30f; ((Component)val).transform.position = position; if ((Object)(object)val.m_waterSurface != (Object)null) { Vector3 position2 = ((Component)val.m_waterSurface).transform.position; position2.y = 30f; ((Component)val.m_waterSurface).transform.position = position2; } } } catch (Exception ex) { Debug.LogWarning((object)("[Tides] Failed to flatten water for Seasonality: " + ex.Message)); } } private static void ForceLODToBaseline(object lodInstance) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: 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) IsWaterFrozen = true; try { FieldInfo field = lodInstance.GetType().GetField("m_originalPos", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { Vector3 val = (Vector3)field.GetValue(lodInstance); val.y = 30f; field.SetValue(lodInstance, val); } MonoBehaviour val2 = (MonoBehaviour)((lodInstance is MonoBehaviour) ? lodInstance : null); if (val2 != null && (Object)(object)val2 != (Object)null) { Vector3 position = ((Component)val2).transform.position; position.y = 29.8f; ((Component)val2).transform.position = position; } } catch (Exception ex) { Debug.LogWarning((object)("[Tides] Failed to baseline Seasonality LOD: " + ex.Message)); } } private static void Prefix_FreezeWater(object __instance) { ForceWaterFlatToBaseline(__instance); } private static void Prefix_ThawWater() { IsWaterFrozen = false; } private static void Prefix_LOD_Freeze(object __instance) { ForceLODToBaseline(__instance); } private static void Prefix_LOD_Thaw() { IsWaterFrozen = false; } private static void Prefix_LOD_SetInitial(object __instance) { if (!Chainloader.PluginInfos.TryGetValue("RustyMods.Seasonality", out var value)) { return; } try { Type type = ((object)value.Instance).GetType().Assembly.GetType("Seasonality.Configs"); if (type != null) { object? obj = type.GetField("m_season", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null); object obj2 = type.GetField("m_waterFreezes", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null); if (obj?.ToString() == "Winter" && obj2?.ToString() != "Off") { ForceLODToBaseline(__instance); } } } catch { } } } public static class SeasonsCompat { public const string GUID = "shudnal.Seasons"; private static Type s_mainSeasonsType; private static Type s_seasonStateType; private static FieldInfo s_stateField; private static PropertyInfo s_stateProp; private static MethodInfo s_getFreezeStatusMethod; private static object s_seasonStateInstance; private static bool s_isInitialized; private static bool s_lazyResolved; public static bool IsEnabled { get; private set; } public static void CheckForCompatibility() { IsEnabled = Chainloader.PluginInfos.TryGetValue("shudnal.Seasons", out var value); if (IsEnabled) { CacheTypes(value); } } private static void CacheTypes(PluginInfo info) { if (s_isInitialized) { return; } s_isInitialized = true; try { Assembly assembly = ((object)info.Instance).GetType().Assembly; s_mainSeasonsType = assembly.GetType("Seasons.Seasons"); if (s_mainSeasonsType != null) { s_stateField = s_mainSeasonsType.GetField("seasonState", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); s_stateProp = s_mainSeasonsType.GetProperty("seasonState", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } s_seasonStateType = assembly.GetType("Seasons.SeasonState") ?? assembly.GetType("Seasons.seasonstate"); if (s_seasonStateType != null) { s_getFreezeStatusMethod = s_seasonStateType.GetMethod("GetWaterSurfaceFreezeStatus", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } } catch (Exception ex) { Debug.LogWarning((object)("[Tides] Failed to cache shudnal.Seasons reflection types: " + ex.Message)); } } public static float GetWaterFreezeStatus() { float result; try { result = 0f; if (!s_lazyResolved) { s_lazyResolved = true; Type type = Type.GetType("Seasons.SeasonState, Seasons"); if (!(type == null)) { s_getFreezeStatusMethod = type.GetMethod("GetWaterSurfaceFreezeStatus", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } type = Type.GetType("Seasons.Seasons, Seasons"); if (!(type == null)) { s_stateField = type.GetField("seasonState", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } } if ((object)s_getFreezeStatusMethod != null && (object)s_stateField != null) { object value = s_stateField.GetValue(null); if (value != null) { result = Mathf.Clamp01((float)s_getFreezeStatusMethod.Invoke(value, null)); } } } catch (Exception) { result = 0f; } return result; } } } namespace Tides.Commands { public class TidesDebugCattailCommand : ConsoleCommand { public override string Name => "tides_debug_cattail"; public override string Help => "Test Move Vegetation"; public override void Run(string[] args) { Console.instance.Print("tides_debug_cattail command response."); VegetationSystem.TestMoveVegetation("vass"); } public override List<string> CommandOptionList() { return new List<string>(); } } public class TidesDebugLilyCommand : ConsoleCommand { public override string Name => "tides_debug_lily"; public override string Help => "tides debug lily"; public override void Run(string[] args) { Console.instance.Print("tides_debug_lily command response."); VegetationSystem.TestMoveVegetation("clutter_waterlilies"); } public override List<string> CommandOptionList() { return new List<string>(); } } public class TidesDiagCommand : ConsoleCommand { public override string Name => "tides_diag"; public override string Help => "Diag chosen systems tides/swampmovement/vegetation"; public override void Run(string[] args) { switch (args[0].ToLowerInvariant()) { case "off": case "false": case "0": Diagnostics.MasterSwitchOff(); Console.instance.Print("Logging disabled. All diagnostics OFF."); break; case "tides": case "t": Diagnostics.DebugTidesEnabled = true; Console.instance.Print("Logging enabled. Tides diagnostics ON."); break; case "swampmovement": case "swamp": case "s": Diagnostics.DebugSwampMovementEnabled = true; Console.instance.Print("Logging enabled. Swamp movement diagnostics ON."); break; case "vegetation": case "vege": case "v": Diagnostics.DebugVegetationEnabled = true; Console.instance.Print("Logging enabled. Vegetation diagnostics ON."); break; } } public override List<string> CommandOptionList() { return new List<string> { "off", "tides", "vegetation", "swampmovement" }; } } public class TidesInfoCommand : ConsoleCommand { public override string Name => "tides"; public override string Help => "Tides Info"; public override void Run(string[] args) { Console.instance.Print($"[Tides Info] current tides offset = {TideSystem._lastTideOffset:F2}m, base ocean level={TideSystem.OceanBaseY}m, max tide amplitude={TideSystem.TideAmplitude}m"); if (Diagnostics.DebugTidesEnabled) { Logger.LogWarning((object)$"[Config Values] base ocean level={TidesConfig.BaseWaterLevel.Value}m, amp={TidesConfig.TideAmplitude.Value}m"); Logger.LogWarning((object)$"[Time] current day={EnvMan.instance.GetCurrentDay()}, m_totalSeconds={EnvMan.instance.m_totalSeconds}, m_dayLengthSec={EnvMan.instance.m_dayLengthSec}, m_smoothDayFraction={EnvMan.instance.m_smoothDayFraction}"); } } public override List<string> CommandOptionList() { return new List<string>(); } } }