Decompiled source of ValheimRAFT v3.3.0
plugins\DynamicLocations.dll
Decompiled a week 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 System.Text; using BepInEx; using BepInEx.Configuration; using DynamicLocations.API; using DynamicLocations.Commands; using DynamicLocations.Config; using DynamicLocations.Constants; using DynamicLocations.Controllers; using DynamicLocations.Patches; using DynamicLocations.Structs; using HarmonyLib; using JetBrains.Annotations; using Jotunn; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using UnityEngine; using ZdoWatcher; using Zolantris.Shared.Debug; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("DynamicLocations")] [assembly: AssemblyDescription("Valheim Mod made to attach to an item/prefab such as a bed and place a player or object near the item wherever it is in the current game. Meant for ValheimVehicles but could be used for any movement mod. Requires Jotunn and ZdoWatcher")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Virtualize LLC")] [assembly: AssemblyProduct("DynamicLocations")] [assembly: AssemblyCopyright("Copyright © 2023-2024, GNU-v3 licensed")] [assembly: Guid("6015B165-2627-40A7-8CA1-3E6B6CD7CB49")] [assembly: AssemblyFileVersion("1.2.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.2.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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 DynamicLocations { internal class ZdoWatcherDelegate { public static readonly int DynamicLocationSpawn = StringExtensionMethods.GetStableHashCode("DynamicLocation_Spawn"); public static readonly int DynamicLocationLogout = StringExtensionMethods.GetStableHashCode("DynamicLocation_Logout"); public static Dictionary<int, ZDOID> DynamicSpawns; public void RegisterToZdoManager() { ZdoWatchController.OnDeserialize = (Action<ZDO>)Delegate.Combine(ZdoWatchController.OnDeserialize, new Action<ZDO>(OnZdoRegister)); ZdoWatchController.OnLoad = (Action<ZDO>)Delegate.Combine(ZdoWatchController.OnLoad, new Action<ZDO>(OnZdoRegister)); } private static void OnZdoRegister(ZDO zdo) { } public static void OnZdoUnRegister(ZDO zdo) { } } [BepInPlugin("zolantris.DynamicLocations", "DynamicLocations", "1.2.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] public class DynamicLocationsPlugin : BaseUnityPlugin { public const string Author = "zolantris"; public const string Version = "1.2.0"; public const string ModName = "DynamicLocations"; public const string BepInGuid = "zolantris.DynamicLocations"; private static Harmony _harmony; public const string ModDescription = "Valheim Mod made to attach to an item/prefab such as a bed and place a player or object near the item wherever it is in the current game. Meant for ValheimVehicles but could be used for any movement mod. Requires Jotunn and ZdoWatcher"; public const string CopyRight = "Copyright © 2023-2024, GNU-v3 licensed"; public static string HarmonyGuid => "zolantris.DynamicLocations"; public void Awake() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown DynamicLocationsConfig.BindConfig(((BaseUnityPlugin)this).Config); _harmony = new Harmony(HarmonyGuid); _harmony.PatchAll(typeof(DynamicLocationsPatches)); RegisterCommands(); } public void RegisterCommands() { CommandManager.Instance.AddConsoleCommand((ConsoleCommand)(object)new DynamicLocationsCommands()); } } } namespace DynamicLocations.Structs { public struct DynamicLocation { public Tuple<int, int> zoneId; public Tuple<float, float, float> position; public LocationVariation locationType; } public struct IntegrationConfig { public string ZdoTargetTargetPrefabName { get; private set; } public string Guid { get; set; } public string Version { get; set; } public string Name { get; set; } public BaseUnityPlugin Plugin { get; set; } public bool UseDefaultCallbacks { get; set; } public int MovementTimeout { get; set; } public bool ShouldFreezePlayer { get; set; } public int LoginPrefabHashCode { get; set; } public int Priority { get; set; } public List<string> RunBeforePlugins { get; } public List<string> RunAfterPlugins { get; } [UsedImplicitly] public IntegrationConfig() { UseDefaultCallbacks = false; MovementTimeout = 0; ShouldFreezePlayer = false; LoginPrefabHashCode = 0; Priority = 999; RunBeforePlugins = new List<string>(); RunAfterPlugins = new List<string>(); throw new Exception("This constructor is not supported, please provide plugin and zdoTargetPrefabName"); } public IntegrationConfig(BaseUnityPlugin plugin, string zdoTargetPrefabName) { UseDefaultCallbacks = false; MovementTimeout = 0; ShouldFreezePlayer = false; LoginPrefabHashCode = 0; Priority = 999; RunBeforePlugins = new List<string>(); RunAfterPlugins = new List<string>(); Plugin = plugin; ZdoTargetTargetPrefabName = zdoTargetPrefabName; LoginPrefabHashCode = zdoTargetPrefabName.GetHashCode(); Name = plugin.Info.Metadata.Name; Version = plugin.Info.Metadata.Version.ToString(); Guid = plugin.Info.Metadata.GUID; Logger.LogDebug((object)$"PluginVersion: {plugin.Info.Metadata.Version} stringVersion {Version}, Name: {Name}"); } } } namespace DynamicLocations.Prefabs { public class DynamicPointPrefab { public static readonly DynamicPointPrefab Instance = new DynamicPointPrefab(); public void Register(PrefabManager prefabManager, PieceManager pieceManager) { prefabManager.CreateEmptyPrefab("DynamicLocations_Prefabs_SpawnPoint", true).layer = LayerMask.NameToLayer("piece"); } } public static class PrefabNames { private const string ModNamePrefix = "DynamicLocations_Prefabs"; public const string SpawnPoint = "DynamicLocations_Prefabs_SpawnPoint"; } } namespace DynamicLocations.Patches { public class DynamicLocationsPatches { [HarmonyPatch(typeof(Bed), "Interact")] [HarmonyPostfix] private static void OnSpawnPointUpdated(Bed __instance) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) Game.instance.GetPlayerProfile().GetCustomSpawnPoint(); if (((Character)Player.m_localPlayer).InInterior()) { if (DynamicLocationsConfig.IsDebug) { Logger.LogDebug((object)"Cannot dynamic spawn inside dungeon or building. InIniterior returned true, must skip."); } return; } PlayerSpawnController instance = PlayerSpawnController.Instance; if (Object.op_Implicit((Object)(object)instance)) { instance?.SyncBedSpawnPoint(__instance.m_nview.GetZDO(), __instance); } } [HarmonyPatch(typeof(Player), "OnDeath")] [HarmonyPostfix] private static void OnDeathDestroyLogoutPoint(Player __instance) { if (((Character)__instance).m_nview.IsOwner()) { LocationController.RemoveZdoTarget(LocationVariation.Logout, __instance); } } [HarmonyPatch(typeof(Player), "ShowTeleportAnimation")] [HarmonyPostfix] private static void ShowTeleportAnimation(bool __result) { PlayerSpawnController? instance = PlayerSpawnController.Instance; if (instance != null && instance.IsTeleportingToDynamicLocation) { __result = false; } } [HarmonyPatch(typeof(Game), "Awake")] [HarmonyPostfix] private static void AddSpawnController(Game __instance) { Logger.LogDebug((object)"Game Awake called and added PlayerSpawnController and LocationController"); ((Component)__instance).gameObject.AddComponent<LocationController>(); ((Component)__instance).gameObject.AddComponent<PlayerSpawnController>(); } [HarmonyPatch(typeof(Game), "OnDestroy")] [HarmonyPostfix] private static void ResetSpawnController(Game __instance) { Logger.LogDebug((object)"Game destroy called ResetSpawnController"); LocationController.ResetCachedValues(); } [HarmonyPatch(typeof(Game), "SpawnPlayer")] [HarmonyPostfix] private static void OnSpawned(Game __instance, Player __result) { if (!ZNetView.m_forceDisableInit) { if (__instance.m_respawnAfterDeath && DynamicLocationsConfig.EnableDynamicSpawnPoint.Value && !((Character)__result).InIntro()) { PlayerSpawnController.Instance?.MovePlayerToSpawnPoint(); } else if (DynamicLocationsConfig.EnableDynamicLogoutPoint.Value && !((Character)__result).InInterior() && !((Character)__result).InIntro()) { PlayerSpawnController.Instance?.MovePlayerToLogoutPoint(); } } } } } namespace DynamicLocations.Interfaces { internal interface IModLoginAPI { BaseUnityPlugin Plugin { get; set; } bool UseDefaultCallbacks { get; } int MovementTimeout { get; } bool ShouldFreezePlayer { get; } int LoginPrefabHashCode { get; } int Priority { get; } List<string> RunBeforePlugins { get; } List<string> RunAfterPlugins { get; } IEnumerator OnLoginMoveToZDO(ZDO zdo, Vector3? offset, PlayerSpawnController playerSpawnController); bool OnLoginMatchZdoPrefab(ZDO zdo); } public interface IVehiclePiecesController { bool IsActivationComplete { get; } } } namespace DynamicLocations.Controllers { public interface ICachedLocation { Vector3? Offset { get; set; } ZDO Zdo { get; set; } } public class CacheLocationItem : ICachedLocation { public Vector3? Offset { get; set; } public ZDO Zdo { get; set; } } public class LocationController : MonoBehaviour { private const string DynamicPrefix = "Dynamic"; private const string SpawnZdoPrefix = "SpawnZdo"; private const string SpawnZdoOffsetPrefix = "SpawnZdoOffset"; private const string LogoutParentZdoOffsetPrefix = "LogoutParentZdoOffset"; private const string LogoutParentZdoPrefix = "LogoutParentZdo"; private static Dictionary<LocationVariation, ICachedLocation> _cachedLocations = new Dictionary<LocationVariation, ICachedLocation>(); public static LocationController Instance; internal static long WorldIdOverride = 0L; private static long CurrentWorldId { get { if (WorldIdOverride == 0L) { ZNet instance = ZNet.instance; if (instance == null) { return 0L; } return instance.GetWorldUID(); } return WorldIdOverride; } } public void Awake() { Instance = this; } public void OnDestroy() { _cachedLocations.Clear(); } public static ICachedLocation? GetCachedDynamicLocation(LocationVariation locationVariationType) { _cachedLocations.TryGetValue(locationVariationType, out ICachedLocation value); return value; } public static bool SetCachedDynamicLocation(LocationVariation locationVariationType, CacheLocationItem cachedLocationItem) { if (GetCachedDynamicLocation(locationVariationType) != null) { _cachedLocations[locationVariationType] = cachedLocationItem; } else { _cachedLocations.Add(locationVariationType, cachedLocationItem); } return true; } public static string GetPluginPrefix() { return "DynamicLocations"; } public static string GetFullPrefix() { return GetPluginPrefix() + "_Dynamic"; } public static string GetLogoutZdoOffsetKey() { if (Object.op_Implicit((Object)(object)ZNet.instance)) { return string.Format("{0}_{1}_{2}", GetFullPrefix(), "LogoutParentZdoOffset", CurrentWorldId); } return ""; } public static string GetLogoutZdoKey() { if (Object.op_Implicit((Object)(object)ZNet.instance)) { return string.Format("{0}_{1}_{2}", GetFullPrefix(), "LogoutParentZdo", CurrentWorldId); } return ""; } public static string GetSpawnZdoOffsetKey() { if (Object.op_Implicit((Object)(object)ZNet.instance)) { return string.Format("{0}_{1}_{2}", GetFullPrefix(), "SpawnZdoOffset", CurrentWorldId); } return ""; } public static string GetSpawnZdoKey() { if (Object.op_Implicit((Object)(object)ZNet.instance)) { return string.Format("{0}_{1}_{2}", GetFullPrefix(), "SpawnZdo", CurrentWorldId); } return ""; } private static string ZDOIDToString(ZDOID zdoid) { long userID = ((ZDOID)(ref zdoid)).UserID; uint iD = ((ZDOID)(ref zdoid)).ID; return $"{userID},{iD}"; } private static ZDOID? StringToZDOID(string zdoidString) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) string[] array = zdoidString.Split(new char[1] { ',' }); if (array.Length != 2) { return null; } long.TryParse(array[0], out var result); uint.TryParse(array[1], out var result2); if (result == 0L || result2 == 0) { Logger.LogDebug((object)"failed to parse to ZDOID"); return null; } return new ZDOID(result, result2); } private static string Vector3ToString(Vector3 val) { //IL_0005: 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_001b: Unknown result type (might be due to invalid IL or missing references) return $"{val.x},{val.y},{val.z}"; } private static Vector3? StringToVector3(string val) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) string[] array = val.Split(new char[1] { ',' }); if (array.Length != 3) { return null; } float.TryParse(array[0], out var result); float.TryParse(array[1], out var result2); float.TryParse(array[2], out var result3); return new Vector3(result, result2, result3); } internal static void DEBUG_RemoveAllDynamicLocationKeys() { KeyValuePair<string, string>[] array = Player.m_localPlayer.m_customData.ToArray(); for (int i = 0; i < array.Length; i++) { KeyValuePair<string, string> keyValuePair = array[i]; if (keyValuePair.Key.Contains(GetFullPrefix())) { Logger.LogDebug((object)("Removing: Key: " + keyValuePair.Key + " Value: " + keyValuePair.Value)); Player.m_localPlayer.m_customData.Remove(keyValuePair.Key); } } } internal static void DEBUGCOMMAND_RemoveLogout() { string logoutZdoKey = GetLogoutZdoKey(); Logger.LogInfo((object)(Player.m_localPlayer.m_customData.Remove(logoutZdoKey) ? ("Removing logout key: " + logoutZdoKey) : "No logout key found")); } internal static void DEBUGCOMMAND_ListAllKeys() { KeyValuePair<string, string>[] array = Player.m_localPlayer.m_customData.ToArray(); List<string> list = new List<string>(); List<string> list2 = new List<string>(); List<string> list3 = new List<string>(); List<string> list4 = new List<string>(); string[] value = Player.m_localPlayer.m_customData.ToArray().Where(delegate(KeyValuePair<string, string> keyValuePair) { KeyValuePair<string, string> keyValuePair4 = keyValuePair; return keyValuePair4.Key.Contains($"{CurrentWorldId}"); }).Select(delegate(KeyValuePair<string, string> keyValuePair) { KeyValuePair<string, string> keyValuePair3 = keyValuePair; return keyValuePair3.Value; }) .ToArray(); KeyValuePair<string, string>[] array2 = array; for (int i = 0; i < array2.Length; i++) { KeyValuePair<string, string> keyValuePair2 = array2[i]; if (keyValuePair2.Key.Contains(GetFullPrefix())) { if (keyValuePair2.Key.Contains("SpawnZdoOffset")) { list4.Add(keyValuePair2.Value); } else if (keyValuePair2.Key.Contains("SpawnZdo")) { list3.Add(keyValuePair2.Value); } else if (keyValuePair2.Key.Contains("LogoutParentZdoOffset")) { list2.Add(keyValuePair2.Value); } else if (keyValuePair2.Key.Contains("LogoutParentZdo")) { list.Add(keyValuePair2.Value); } } } Logger.LogInfo((object)("currentWorldItems: " + string.Join(", ", value))); Logger.LogInfo((object)("spawnKeys: " + string.Join(", ", list3))); Logger.LogInfo((object)("spawnOffsetKeys: " + string.Join(", ", list4))); Logger.LogInfo((object)("logoutKeys: " + string.Join(", ", list))); Logger.LogInfo((object)("logoutOffsetKeys: " + string.Join(", ", list2))); } public static bool RemoveZdoTarget(LocationVariation locationVariationType, Player? player) { RemoveTargetKey(locationVariationType, player); return true; } public static int? GetZdoFromStore(LocationVariation locationVariationType, Player? player) { string zdoStorageKey = GetZdoStorageKey(locationVariationType); if ((Object)(object)player == (Object)null) { return null; } if (!player.m_customData.TryGetValue(zdoStorageKey, out var value)) { return null; } if (!int.TryParse(value, out var result)) { Logger.LogError((object)("The targetKey <" + zdoStorageKey + "> zdoKey: <" + value + "> could not be parsed as an int")); return null; } Logger.LogDebug((object)$"Retreiving targetKey <{zdoStorageKey}> zdoKey: <{value}> for name: {player.GetPlayerName()} id: {player.GetPlayerID()}"); return result; } public static bool TryGetWorldUidFromKey(string storageKey, out long worldUid) { long.TryParse(storageKey.Split(new char[1] { '_' }).Last(), out var result); worldUid = result; return result == CurrentWorldId; } public static void RemoveTargetKey(LocationVariation locationVariationType, Player? player) { if (!((Object)(object)player == (Object)null) && !((Object)(object)ZNet.instance == (Object)null)) { string zdoStorageKey = GetZdoStorageKey(locationVariationType); string offsetStorageKey = GetOffsetStorageKey(locationVariationType); if (!TryGetWorldUidFromKey(zdoStorageKey, out var worldUid)) { Logger.LogWarning((object)$"Skipping key deletion due to current world {CurrentWorldId} not matching key worldUid {worldUid}"); return; } player.m_customData.Remove(zdoStorageKey); player.m_customData.Remove(offsetStorageKey); Game.instance.m_playerProfile.SavePlayerData(player); } } public static IEnumerator GetZdoFromStoreAsync(LocationVariation locationVariationType, Player? player, Action<ZDO?> onComplete) { int? zdoFromStore = GetZdoFromStore(locationVariationType, player); if (!zdoFromStore.HasValue) { onComplete(null); yield break; } ZDO zdoOutput = null; yield return ZdoWatchController.Instance.GetZdoFromServerAsync(zdoFromStore.Value, (Action<ZDO>)delegate(ZDO? output) { zdoOutput = output; }); if (zdoOutput == null) { Logger.LogDebug((object)"Removing targetKey as it's ZDO no longer exists"); RemoveTargetKey(locationVariationType, player); } else if (zdoOutput.GetInt("DynamicLocations_Point", 0) != 0) { onComplete(zdoOutput); } } public static void ResetCachedValues() { _cachedLocations.Clear(); } public static Vector3 GetOffset(LocationVariation locationVariationType, Player? player) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return GetOffset(GetOffsetStorageKey(locationVariationType), player); } public static Vector3 GetOffset(string key, Player? player) { //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_003d: 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) if ((Object)(object)player == (Object)null) { return Vector3.zero; } if (!player.m_customData.TryGetValue(key, out var value)) { return Vector3.zero; } return (Vector3)(((??)StringToVector3(value)) ?? Vector3.zero); } public static ZDO? SetZdo(LocationVariation locationVaration, Player? player, ZDO? zdo) { //IL_00af: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null) { return null; } if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return null; } if (zdo == null) { return null; } string zdoStorageKey = GetZdoStorageKey(locationVaration); int num = default(int); if (!ZdoWatchController.GetPersistentID(zdo, ref num)) { Logger.LogWarning((object)$"No persistent id found for dynamicObj {zdo}"); return null; } zdo.Set("DynamicLocations_Point", 1); if (player.m_customData.TryGetValue(zdoStorageKey, out var _)) { player.m_customData[zdoStorageKey] = num.ToString(); } else { player.m_customData.Add(zdoStorageKey, num.ToString()); } if (!player.m_customData.ContainsKey(zdoStorageKey)) { Logger.LogError((object)"Zdo string failed to set on player.customData"); } Logger.LogDebug((object)$"Setting key: {zdoStorageKey}, uid: {zdo.m_uid} for name: {player.GetPlayerName()} id: {player.GetPlayerID()}"); Game.instance.m_playerProfile.SavePlayerData(player); return zdo; } public static Vector3? SetOffset(LocationVariation locationVariationType, Player player, Vector3 offset) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return SetOffset(GetOffsetStorageKey(locationVariationType), player, offset); } public static Vector3? SetOffset(string key, Player player, Vector3 offset) { //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_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)player)) { return null; } if (Vector3.zero == offset) { if (player.m_customData.TryGetValue(key, out var _)) { player.m_customData.Remove(key); } return null; } player.m_customData[key] = Vector3ToString(offset); return offset; } public static string GetOffsetStorageKey(LocationVariation locationVariationType) { return locationVariationType switch { LocationVariation.Spawn => GetSpawnZdoOffsetKey(), LocationVariation.Logout => GetLogoutZdoOffsetKey(), _ => throw new ArgumentOutOfRangeException("locationVariationType", locationVariationType, null), }; } public static string GetZdoStorageKey(LocationVariation locationVariationType) { return locationVariationType switch { LocationVariation.Spawn => GetSpawnZdoKey(), LocationVariation.Logout => GetLogoutZdoKey(), _ => throw new ArgumentOutOfRangeException("locationVariationType", locationVariationType, null), }; } public static bool SetLocationTypeData(LocationVariation locationVariation, Player player, ZDO zdo, Vector3 offset) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) Vector3? offset2 = SetOffset(GetOffsetStorageKey(locationVariation), player, offset); ZDO val = SetZdo(locationVariation, player, zdo); if (val == null) { return false; } SetCachedDynamicLocation(locationVariation, new CacheLocationItem { Zdo = val, Offset = offset2 }); return true; } public static void SaveWorldData() { World.GetWorldSavePath((FileSource)0); _ = Game.instance.m_devWorldName + "_mod_dynamic_locations.json"; } } public class LoginAPIController { internal static readonly Dictionary<string, DynamicLoginIntegration> LoginIntegrations = new Dictionary<string, DynamicLoginIntegration>(); internal static readonly Dictionary<string, DynamicLoginIntegration> DisabledLoginIntegrations = new Dictionary<string, DynamicLoginIntegration>(); internal static List<DynamicLoginIntegration> loginIntegrationsByPriority = new List<DynamicLoginIntegration>(); private PlayerSpawnController? _playerSpawnController => PlayerSpawnController.Instance; private static string? GetModIntegrationId(DynamicLoginIntegration integration) { if (integration.Guid != "") { return integration.Guid; } Logger.LogWarning((object)"Invalid guid detected, make sure the BepInPlugin guid is a valid number"); return null; } public static List<DynamicLoginIntegration> OrderItems(List<DynamicLoginIntegration> items) { Dictionary<string, DynamicLoginIntegration> itemLookup = items.ToDictionary((DynamicLoginIntegration i) => i.Guid); List<DynamicLoginIntegration> result = new List<DynamicLoginIntegration>(); HashSet<string> placed = new HashSet<string>(); foreach (DynamicLoginIntegration item in items.OrderBy((DynamicLoginIntegration i) => i.Guid)) { AddItemWithDependencies(item, itemLookup, result, placed); } return result; } private static void AddItemWithDependencies(DynamicLoginIntegration item, Dictionary<string, DynamicLoginIntegration> itemLookup, List<DynamicLoginIntegration> result, HashSet<string> placed) { if (placed.Contains(item.Guid)) { return; } foreach (string runAfterPlugin in item.RunAfterPlugins) { if (itemLookup.TryGetValue(runAfterPlugin, out DynamicLoginIntegration value)) { AddItemWithDependencies(value, itemLookup, result, placed); } } result.Add(item); placed.Add(item.Guid); foreach (string runBeforePlugin in item.RunBeforePlugins) { if (itemLookup.TryGetValue(runBeforePlugin, out DynamicLoginIntegration value2)) { AddItemWithDependencies(value2, itemLookup, result, placed); } } } internal static void UpdateIntegrations() { foreach (string disabledLoginApiIntegration in DynamicLocationsConfig.DisabledLoginApiIntegrations) { if (LoginIntegrations.ContainsKey(disabledLoginApiIntegration)) { LoginIntegrations.Remove(disabledLoginApiIntegration); } } foreach (KeyValuePair<string, DynamicLoginIntegration> disabledLoginIntegration in DisabledLoginIntegrations) { bool flag = false; foreach (string disabledLoginApiIntegration2 in DynamicLocationsConfig.DisabledLoginApiIntegrations) { if (DisabledLoginIntegrations.ContainsKey(disabledLoginApiIntegration2)) { flag = true; } } if (!flag) { LoginIntegrations.Add(disabledLoginIntegration.Key, disabledLoginIntegration.Value); } } loginIntegrationsByPriority = OrderItems(LoginIntegrations.Values.ToList()); foreach (DynamicLoginIntegration item in loginIntegrationsByPriority) { Logger.LogInfo((object)$"item ----> name:{item.Name}, guid: {item.Guid}, priority: {item.Priority}"); } } public static bool AddLoginApiIntegration(DynamicLoginIntegration loginIntegration) { string modIntegrationId = GetModIntegrationId(loginIntegration); if (modIntegrationId == null) { return false; } if (!LoginIntegrations.ContainsKey(modIntegrationId)) { LoginIntegrations.Add(modIntegrationId, loginIntegration); UpdateIntegrations(); return true; } if (loginIntegration.LoginPrefabHashCode == 0) { Logger.LogWarning((object)$"LoginIntegration provided invalid prefab identifier, the hashcode was {loginIntegration.LoginPrefabHashCode}."); } if (DynamicLocationsConfig.IsDebug) { if (!ZNetScene.instance.m_namedPrefabs.TryGetValue(loginIntegration.LoginPrefabHashCode, out var value)) { Logger.LogError((object)$"Prefab not found for stableHashCode {loginIntegration.LoginPrefabHashCode}"); } else { Logger.LogDebug((object)$"Found prefab for stableHashCode {loginIntegration.LoginPrefabHashCode} name {((Object)value).name}"); } } Logger.LogError((object)"Could not integrate component due to collision in registered plugin GUID and plugin_version, this ModAPI plugin will not be loaded. Make sure your plugin only creates 1 instance of ModLoginApi and that your plugin GUID or plugin.Name_plugin_Version are unique."); return false; } private static void LogResults(DynamicLoginIntegration? selectedIntegration) { if (DynamicLocationsConfig.IsDebug) { Logger.LogDebug((object)((selectedIntegration != null) ? ("Successfully handled ModApi " + selectedIntegration.Name + " matched") : "No matches found for registered integrations")); } } public static IEnumerator RunAllIntegrations_OnLoginMoveToZdo(ZDO zdo, Vector3? offset, PlayerSpawnController playerSpawnController) { if ((Object)(object)playerSpawnController == (Object)null) { yield break; } DynamicLoginIntegration selectedIntegration = null; foreach (DynamicLoginIntegration item in loginIntegrationsByPriority) { if (item.OnLoginMatchZdoPrefab(zdo)) { selectedIntegration = item; yield return item.API_OnLoginMoveToZDO(zdo, offset, playerSpawnController); break; } } if (selectedIntegration != null) { yield return (object)new WaitUntil((Func<bool>)(() => selectedIntegration.IsComplete)); } LogResults(selectedIntegration); } } public class PlayerSpawnController : MonoBehaviour { public delegate TResult Func<in T, out TResult>(T arg); internal bool CanUpdateLogoutPoint = true; internal bool CanRemoveLogoutAfterSync = true; internal bool IsTeleportingToDynamicLocation; private bool IsRunningFindDynamicZdo; public static Dictionary<long, PlayerSpawnController> Instances = new Dictionary<long, PlayerSpawnController>(); public static PlayerSpawnController? Instance; public static Coroutine? MoveToLogoutRoutine; public static Coroutine? MoveToSpawnRoutine; internal static List<DebugSafeTimer> Timers = new List<DebugSafeTimer>(); private bool MovePlayerToZdoComplete; private static Player? player => Player.m_localPlayer; private void Awake() { Setup(); } private void Update() { DebugSafeTimer.UpdateTimersFromList(Timers); } public void DEBUG_MoveTo(LocationVariation locationVariationType) { CanUpdateLogoutPoint = true; CanRemoveLogoutAfterSync = false; switch (locationVariationType) { case LocationVariation.Spawn: Instance?.MovePlayerToSpawnPoint(); break; case LocationVariation.Logout: Instance?.MovePlayerToLogoutPoint(); break; default: throw new ArgumentOutOfRangeException("locationVariationType", locationVariationType, null); } } internal void Reset() { IsRunningFindDynamicZdo = false; IsTeleportingToDynamicLocation = false; CanUpdateLogoutPoint = true; CanRemoveLogoutAfterSync = true; MovePlayerToZdoComplete = true; ResetRoutine(ref MoveToLogoutRoutine); ResetRoutine(ref MoveToSpawnRoutine); } internal void OnMovePlayerToZdoComplete(bool success = false, string errorMessage = "OnMovePlayerToZdo exited but failed") { Reset(); Timers.Clear(); IsTeleportingToDynamicLocation = false; MovePlayerToZdoComplete = true; if (!success) { Logger.LogError((object)errorMessage); } } internal static void ResetRoutine(ref Coroutine? routine) { if (routine != null) { PlayerSpawnController? instance = Instance; if (instance != null) { ((MonoBehaviour)instance).StopCoroutine(routine); } routine = null; } } private void OnDestroy() { Reset(); Logger.LogDebug((object)"Called onDestroy"); } private void OnDisable() { Reset(); ((MonoBehaviour)this).StopAllCoroutines(); } private void Setup() { Instance = this; _ = (Object)(object)player == (Object)null; } public bool PersistDynamicPoint(ZDO zdo, LocationVariation locationVariationType, out int id) { id = 0; if ((Object)(object)ZdoWatchController.Instance == (Object)null) { return false; } id = ZdoWatchController.Instance.GetOrCreatePersistentID(zdo); if (id == 0) { if (locationVariationType == LocationVariation.Spawn) { Logger.LogError((object)"No persistent ID returned for bed, this should not be possible. Please report this error"); RemoveDynamicPoint(zdo, locationVariationType); } return false; } AddDynamicPoint(zdo, locationVariationType); return true; } public void AddDynamicPoint(ZDO zdo, LocationVariation locationVariationType) { zdo.Set("DynamicLocations_Point", 1); } public void RemoveDynamicPoint(ZDO? zdo, LocationVariation locationVariationType) { LocationController.RemoveZdoTarget(locationVariationType, player); if (zdo != null) { zdo.RemoveInt("DynamicLocations_Point"); } } public bool SyncBedSpawnPoint(ZDO zdo, Bed bed) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null) { return false; } if (!bed.IsMine()) { return false; } PersistDynamicPoint(zdo, LocationVariation.Spawn, out var _); return LocationController.SetLocationTypeData(LocationVariation.Spawn, player, zdo, ((Component)bed).transform.position - ((Component)player).transform.position); } public bool SyncLogoutPoint(ZDO? zdo, bool shouldRemove = false) { //IL_00a6: 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_00d1: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null) { return false; } if (zdo == null && !shouldRemove) { Logger.LogError((object)"ZDO not found for netview, this likely means something is wrong with the are it is being called in"); return false; } if (shouldRemove) { RemoveDynamicPoint(zdo, LocationVariation.Logout); Game.instance.m_playerProfile.SavePlayerData(player); return true; } int id; bool flag = PersistDynamicPoint(zdo, LocationVariation.Logout, out id); if (!shouldRemove && !flag) { Logger.LogDebug((object)"vehicleZdoId is invalid"); return false; } if (LocationController.GetZdoFromStore(LocationVariation.Logout, player) == id) { Logger.LogDebug((object)"Matching ZDOID found already stored, skipping sync/save"); return false; } if ((Object)(object)player == (Object)null) { return false; } if (((Component)player).transform.localPosition != ((Component)player).transform.position) { LocationController.SetOffset(LocationVariation.Logout, player, ((Component)player).transform.localPosition); } LocationController.SetZdo(LocationVariation.Logout, player, zdo); Game.instance.m_playerProfile.SavePlayerData(player); return true; } [UsedImplicitly] public bool DynamicTeleport(Vector3 position, Quaternion rotation) { //IL_002e: 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) if ((Object)(object)player == (Object)null) { return false; } player.m_teleportCooldown = 15f; player.m_teleporting = false; return ((Character)player).TeleportTo(position, rotation, !DynamicLocationsConfig.DebugDisableDistancePortal.Value); } public void MovePlayerToLogoutPoint() { MoveToLogoutRoutine = ((MonoBehaviour)this).StartCoroutine(UpdateLocation(LocationVariation.Logout)); } public IEnumerator FindDynamicZdo(LocationVariation locationVariationType, Action<ZDO?> onComplete, bool shouldAdjustReferencePoint = false) { IsRunningFindDynamicZdo = true; ZDO zdoOutput = null; yield return LocationController.GetZdoFromStoreAsync(locationVariationType, player, delegate(ZDO? output) { zdoOutput = output; }); onComplete(zdoOutput); if (shouldAdjustReferencePoint && (Object)(object)ZNet.instance != (Object)null && zdoOutput != null) { ZNet.instance.SetReferencePosition(zdoOutput.GetPosition()); } IsRunningFindDynamicZdo = false; } private IEnumerator UpdateLocation(LocationVariation locationVariationType) { DebugSafeTimer timer = DebugSafeTimer.StartNew(Timers); IsTeleportingToDynamicLocation = false; Vector3 offset = LocationController.GetOffset(locationVariationType, player); ZDO zdoOutput = null; yield return FindDynamicZdo(locationVariationType, delegate(ZDO? output) { zdoOutput = output; }); if (zdoOutput == null) { yield break; } switch (locationVariationType) { case LocationVariation.Spawn: yield return MovePlayerToZdo(zdoOutput, offset); break; case LocationVariation.Logout: yield return LoginAPIController.RunAllIntegrations_OnLoginMoveToZdo(zdoOutput, offset, this); break; default: throw new ArgumentOutOfRangeException("locationVariationType", locationVariationType, null); } IsTeleportingToDynamicLocation = false; LocationVariation locationVariation = locationVariationType; if (locationVariation != 0) { if (locationVariation != LocationVariation.Logout || !((Object)(object)player != (Object)null)) { throw new ArgumentOutOfRangeException("locationVariationType", locationVariationType, null); } if (CanRemoveLogoutAfterSync && DynamicLocationsConfig.DEBUG_ShouldNotRemoveTargetKey.Value) { LocationController.RemoveZdoTarget(LocationVariation.Logout, player); } } timer.Clear(); yield return true; } public Coroutine MovePlayerToSpawnPoint() { ResetRoutine(ref MoveToSpawnRoutine); ResetRoutine(ref MoveToLogoutRoutine); MoveToSpawnRoutine = ((MonoBehaviour)this).StartCoroutine(UpdateLocation(LocationVariation.Spawn)); return MoveToSpawnRoutine; } private void SyncPlayerPosition(Vector3 newPosition) { //IL_0042: 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_0058: 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_0086: 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_008e: 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_0069: Unknown result type (might be due to invalid IL or missing references) Logger.LogDebug((object)"Running PlayerPosition Sync"); if (ZNetView.m_forceDisableInit || (Object)(object)player == (Object)null) { return; } ZDO zDO = ((Character)player).m_nview.GetZDO(); if (zDO == null) { Logger.LogDebug((object)"Player zdo invalid exiting"); return; } Logger.LogDebug((object)$"Syncing Player Position and sector, {newPosition}"); if (!ZoneSystem.instance.IsZoneLoaded(ZoneSystem.GetZone(newPosition))) { Logger.LogDebug((object)$"zone not loaded, exiting SyncPlayerPosition for position: {newPosition}"); return; } ZNet.instance.SetReferencePosition(newPosition); zDO.SetPosition(newPosition); zDO.SetSector(ZoneSystem.GetZone(newPosition)); ((Component)player).transform.position = newPosition; } public static bool HasExpiredTimer(Stopwatch timer, int timeInMs = 1000) { int num = ((timeInMs > 1000) ? timeInMs : DynamicLocationsConfig.LocationControlsTimeoutInMs.Value); return timer.ElapsedMilliseconds > num; } public static bool HasExpiredTimer(DebugSafeTimer timer, int timeInMs = 1000) { int num = ((timeInMs > 1000) ? timeInMs : DynamicLocationsConfig.LocationControlsTimeoutInMs.Value); return timer.ElapsedMilliseconds > (float)num; } [UsedImplicitly] public bool CanFreezePlayer(bool val) { return !DynamicLocationsConfig.DebugDisableFreezePlayerTeleportMechanics.Value && val; } public IEnumerator MovePlayerToZdo(ZDO? zdo, Vector3? offset, bool freezePlayerOnTeleport = false, bool shouldKeepPlayerFrozen = false) { ZDO zdo2 = zdo; if (!Object.op_Implicit((Object)(object)player) || zdo2 == null) { OnMovePlayerToZdoComplete(); yield break; } DebugSafeTimer timer = DebugSafeTimer.StartNew(); bool hasKinematicPlayerFreeze = CanFreezePlayer(freezePlayerOnTeleport); bool hasKeepPlayerFrozen = CanFreezePlayer(shouldKeepPlayerFrozen); if (DynamicLocationsConfig.IsDebug) { Logger.LogDebug((object)"Running MovePlayerToZdo"); } Vector3 val = Vector3.up * (float)DynamicLocationsConfig.RespawnHeightOffset.Value; Vector3 position = zdo2.GetPosition() + val; IsTeleportingToDynamicLocation = DynamicTeleport(position, zdo2.GetRotation()); Vector2i zone = ZoneSystem.GetZone(zdo2.GetPosition()); ZoneSystem.instance.PokeLocalZone(zone); bool zoneIsNotLoaded = false; while (!zoneIsNotLoaded) { zone = ZoneSystem.GetZone(zdo2.GetPosition()); zoneIsNotLoaded = ZoneSystem.instance.IsZoneLoaded(zone); yield return (object)new WaitForFixedUpdate(); } if (!IsTeleportingToDynamicLocation) { OnMovePlayerToZdoComplete(); Logger.LogError((object)"Teleport command failed for player, exiting dynamic spawn MovePlayerToZdo."); yield break; } if ((Object)(object)player != (Object)null && CanFreezePlayer(freezePlayerOnTeleport) && ((Character)player).IsDebugFlying()) { player.ToggleDebugFly(); } ZNetView zdoNetViewInstance = null; zone = ZoneSystem.GetZone(zdo2.GetPosition()); ZoneSystem.instance.PokeLocalZone(zone); yield return (object)new WaitUntil((Func<bool>)(() => !((Character)Player.m_localPlayer).IsTeleporting() || HasExpiredTimer(timer, DynamicLocationsConfig.LocationControlsTimeoutInMs.Value))); zdoNetViewInstance = ZNetScene.instance.FindInstance(zdo2); yield return (object)new WaitUntil((Func<bool>)delegate { zdoNetViewInstance = ZNetScene.instance.FindInstance(zdo2); return (Object)(object)zdoNetViewInstance != (Object)null || HasExpiredTimer(timer, DynamicLocationsConfig.LocationControlsTimeoutInMs.Value); }); if (HasExpiredTimer(timer, DynamicLocationsConfig.LocationControlsTimeoutInMs.Value)) { Logger.LogError((object)"Error attempting to find NetView instance of the ZDO"); yield break; } if ((Object)(object)player != (Object)null && hasKinematicPlayerFreeze && !hasKeepPlayerFrozen && ((Character)player).IsDebugFlying()) { player.ToggleDebugFly(); } if (DynamicLocationsConfig.DebugForceUpdatePositionAfterTeleport.Value && DynamicLocationsConfig.DebugForceUpdatePositionDelay.Value > 0f) { yield return (object)new WaitForSeconds(DynamicLocationsConfig.DebugForceUpdatePositionDelay.Value); } if ((Object)(object)player != (Object)null && DynamicLocationsConfig.DebugForceUpdatePositionAfterTeleport.Value) { ZNetView obj = zdoNetViewInstance; Vector3? obj2; if (obj == null) { obj2 = null; } else { Vector3 position2 = ((Component)obj).transform.position; Vector3? val2 = offset; obj2 = (val2.HasValue ? new Vector3?(position2 + val2.GetValueOrDefault()) : null); } position = (Vector3)(((??)obj2) ?? zdo2.GetPosition()) + Vector3.up * (float)DynamicLocationsConfig.RespawnHeightOffset.Value; ((Component)player).transform.position = position; } timer.Clear(); yield return null; } } } namespace DynamicLocations.Constants { public enum LocationVariation { Spawn, Logout } public static class LocationVariationUtils { public const string LogoutString = "logout"; public const string SpawnString = "spawn"; public static LocationVariation? ToLocationVaration(string? locationVarationString) { string text = locationVarationString?.ToLower(); if (!(text == "logout")) { if (text == "spawn") { return LocationVariation.Spawn; } return null; } return LocationVariation.Logout; } } public static class ZdoVarKeys { public const string DynamicLocationsPoint = "DynamicLocations_Point"; } } namespace DynamicLocations.Config { public static class DynamicLocationsConfig { private const string MainSection = "Main"; private const string DebugSection = "Debug"; public static ConfigFile? Config { get; private set; } public static ConfigEntry<string> DisabledLoginApiIntegrationsString { get; private set; } public static ConfigEntry<int> LocationControlsTimeoutInMs { get; private set; } public static List<string> DisabledLoginApiIntegrations => DisabledLoginApiIntegrationsString?.Value.Split(new char[1] { ',' }).ToList() ?? new List<string>(); public static ConfigEntry<bool> HasCustomSpawnDelay { get; private set; } public static ConfigEntry<bool> DEBUG_ShouldNotRemoveTargetKey { get; private set; } public static ConfigEntry<float> CustomSpawnDelay { get; private set; } public static ConfigEntry<int> RespawnHeightOffset { get; set; } public static ConfigEntry<bool> EnableDynamicSpawnPoint { get; private set; } public static ConfigEntry<bool> EnableDynamicLogoutPoint { get; private set; } public static ConfigEntry<bool> DebugDisableFreezePlayerTeleportMechanics { get; private set; } private static ConfigEntry<bool> Debug { get; set; } public static bool IsDebug => Debug.Value; public static ConfigEntry<bool> DebugDisableDistancePortal { get; private set; } public static ConfigEntry<float> DebugForceUpdatePositionDelay { get; private set; } public static ConfigEntry<bool> DebugForceUpdatePositionAfterTeleport { get; private set; } public static void BindConfig(ConfigFile config) { //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_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Expected O, but got Unknown //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown //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) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Expected O, but got Unknown //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Expected O, but got Unknown //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_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Expected O, but got Unknown //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Expected O, but got Unknown //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_0170: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Expected O, but got Unknown //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Expected O, but got Unknown //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Expected O, but got Unknown //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Expected O, but got Unknown //IL_01f0: 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_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_0209: Expected O, but got Unknown //IL_0209: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Expected O, but got Unknown //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_024d: Unknown result type (might be due to invalid IL or missing references) //IL_0254: Unknown result type (might be due to invalid IL or missing references) //IL_0261: Expected O, but got Unknown //IL_0261: Unknown result type (might be due to invalid IL or missing references) //IL_026b: Expected O, but got Unknown //IL_028e: Unknown result type (might be due to invalid IL or missing references) //IL_0293: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Expected O, but got Unknown //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Expected O, but got Unknown //IL_02d4: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: 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_02ed: Expected O, but got Unknown //IL_02ed: Unknown result type (might be due to invalid IL or missing references) //IL_02f7: Expected O, but got Unknown //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_0326: Unknown result type (might be due to invalid IL or missing references) //IL_0333: Expected O, but got Unknown //IL_0333: Unknown result type (might be due to invalid IL or missing references) //IL_033d: Expected O, but got Unknown //IL_0368: 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_0374: Unknown result type (might be due to invalid IL or missing references) //IL_0381: Expected O, but got Unknown //IL_0381: Unknown result type (might be due to invalid IL or missing references) //IL_038b: Expected O, but got Unknown //IL_03ae: Unknown result type (might be due to invalid IL or missing references) //IL_03b3: Unknown result type (might be due to invalid IL or missing references) //IL_03ba: Unknown result type (might be due to invalid IL or missing references) //IL_03c7: Expected O, but got Unknown //IL_03c7: Unknown result type (might be due to invalid IL or missing references) //IL_03d1: Expected O, but got Unknown Config = config; DEBUG_ShouldNotRemoveTargetKey = Config.Bind<bool>("Main", "DEBUG_ShouldNotRemoveTargetKey", true, new ConfigDescription("Debug only command: will prevent removing of data on the player. This is meant to debug issues with the player spawn points. Should not be enabled in production builds.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true, IsAdvanced = true } })); LocationControlsTimeoutInMs = Config.Bind<int>("Main", "LocationControls Timeout In Ms", 20000, new ConfigDescription("Allows for setting the delay in which the spawn will exit logic to prevent degraded performance.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1000, 40000), new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true, IsAdvanced = false } })); HasCustomSpawnDelay = Config.Bind<bool>("Main", "HasCustomSpawnDelay", false, new ConfigDescription("Enables custom spawn delay. This is meant to speed-up the game.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true, IsAdvanced = false } })); CustomSpawnDelay = Config.Bind<float>("Main", "CustomSpawnDelay", 1f, new ConfigDescription("Will significantly speed-up respawn and login process. This mod will NOT support respawn delays above default(10) seconds, this is too punishing for players. Try to make other consequences instead of preventing people from playing.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true, IsAdvanced = false } })); DisabledLoginApiIntegrationsString = Config.Bind<string>("Main", "DisabledLoginApiIntegrations", "", new ConfigDescription("A list of disabled plugins by GUID or name. Each item must be separated by a comma. This list will force disable any plugins matching either the guid or name. e.g. if you don't want ValheimRAFT to be enabling dynamic locations login integrations add \"zolantris.ValheimRAFT\" or \"ValheimRAFT.2.3.0\".", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = false, IsAdvanced = false } })); DebugDisableFreezePlayerTeleportMechanics = Config.Bind<bool>("Debug", "DEBUG_DisableFreezePlayerMechanics", false, new ConfigDescription("This will disable freezing of players from integrations. Do not disable this unless you know what you are doing. Freezing is used to prevent physics happening during teleport.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = false, IsAdvanced = false } })); DebugDisableDistancePortal = Config.Bind<bool>("Debug", "DebugDistancePortal", false, new ConfigDescription("distance portal enabled, disabling this could break portals", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true, IsAdvanced = true } })); DebugForceUpdatePositionDelay = Config.Bind<float>("Debug", "DebugForceUpdatePositionDelay", 0f, new ConfigDescription("distance portal enabled, disabling this could break portals", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true, IsAdvanced = true } })); DebugForceUpdatePositionAfterTeleport = Config.Bind<bool>("Debug", "DebugForceUpdatePositionAfterTeleport", false, new ConfigDescription("distance portal enabled, disabling this could break portals", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true, IsAdvanced = true } })); EnableDynamicSpawnPoint = Config.Bind<bool>("Main", "enableDynamicSpawnPoints", true, new ConfigDescription("Enable dynamic spawn points. This will allow the user to re-spawn in a new area of the map if a vehicle has moved.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true, IsAdvanced = true } })); EnableDynamicLogoutPoint = Config.Bind<bool>("Main", "enableDynamicLogoutPoints", true, new ConfigDescription("Enable dynamic logout points. This will allow the user to login to a new area of the map if a vehicle has moved", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true, IsAdvanced = true } })); RespawnHeightOffset = Config.Bind<int>("Main", "respawnHeightOffset", 0, new ConfigDescription("Sets the respawn height for beds. Useful if the player is spawning within the bed instead of above it", (AcceptableValueBase)(object)new AcceptableValueRange<int>(-5, 10), new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = false, IsAdvanced = true } })); Debug = Config.Bind<bool>("Main", "debug", false, new ConfigDescription("Enable additional logging and debug drawing around spawn and logout points. Useful for debugging this mod", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true, IsAdvanced = true } })); DisabledLoginApiIntegrationsString.SettingChanged += delegate { LoginAPIController.UpdateIntegrations(); }; _ = Debug.Value; } } } namespace DynamicLocations.Commands { public class KeyValueSerializer { public static string Serialize(object obj, int indentLevel = 0) { if (obj == null) { return string.Empty; } StringBuilder stringBuilder = new StringBuilder(); string indent = new string(' ', indentLevel * 4); Type type = obj.GetType(); PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public); PropertyInfo[] array = properties; foreach (PropertyInfo propertyInfo in array) { object value = propertyInfo.GetValue(obj); SerializeValue(stringBuilder, propertyInfo.Name, value, indent, indentLevel); } FieldInfo[] array2 = fields; foreach (FieldInfo fieldInfo in array2) { object value2 = fieldInfo.GetValue(obj); SerializeValue(stringBuilder, fieldInfo.Name, value2, indent, indentLevel); } return stringBuilder.ToString(); } private static void SerializeValue(StringBuilder sb, string name, object value, string indent, int indentLevel) { if (value == null) { sb.AppendLine(indent + name + ": null"); return; } if (value is string || value.GetType().IsPrimitive) { sb.AppendLine($"{indent}{name}: {value}"); return; } if (value is IEnumerable enumerable) { sb.AppendLine(indent + name + ":"); { foreach (object item in enumerable) { SerializeValue(sb, "- Item", item, indent + " ", indentLevel + 1); } return; } } sb.AppendLine(indent + name + ":"); sb.Append(Serialize(value, indentLevel + 1)); } } public class ListAllKeysCommand : ConsoleCommand { public override string Name => "list-all-keys"; public override string Help { get; } = "list all keys"; public override void Run(string[] args) { if (args.Length != 0) { LocationController.DEBUGCOMMAND_ListAllKeys(); } } } public class ModIntegrationsCommand : ConsoleCommand { private const string Indent = "\n- "; public override string Name => "mod-integrations"; public override string Help { get; } = "Lists all mods using this plugin, e.g. ValheimRaft/Vehicles. \n- Name + version will be output only.\n- To see everything add -v will output the whole object per integration."; private static void ModIntegrationsCommands(bool isVerbose) { Logger.LogMessage((object)"Listing all integrations by order"); int num = 1; foreach (DynamicLoginIntegration item in LoginAPIController.loginIntegrationsByPriority) { if (isVerbose) { Logger.LogMessage((object)KeyValueSerializer.Serialize(item)); } else { Logger.LogMessage((object)$"[LoginIntegration]: [index: {num}] -> ModName: {item.Name} ModVersion {item.Version}, priority {item.Priority}, guid: {item.Guid}"); } num++; } } private static bool IsVerboseFlag(string arg) { switch (arg) { case "-v": case "-verbose": case "--verbose": return true; default: return false; } } public override void Run(string[] args) { if (args.Length != 0) { ModIntegrationsCommands(IsVerboseFlag(args.First())); } } public override List<string> CommandOptionList() { return new List<string>(1) { "-v" }; } } public class MoveToCommand : ConsoleCommand { public override bool IsCheat => true; public override string Name => "move-to"; public override string Help { get; } = "Moves to logout point. Requires Admin privileges"; public override void Run(string[] args) { if (args.Length == 0) { Logger.LogMessage((object)("Requires an argument of " + string.Join(",", ((ConsoleCommand)this).CommandOptionList().ToArray()))); return; } string text = args.First(); LocationVariation? locationVariation = LocationVariationUtils.ToLocationVaration(text); if (!locationVariation.HasValue) { Logger.LogMessage((object)("Invalid input " + text)); } else { PlayerSpawnController.Instance?.DEBUG_MoveTo(locationVariation.Value); } } public override List<string> CommandOptionList() { return new List<string>(2) { "logout", "spawn" }; } } public class DynamicLocationsCommands : ConsoleCommand { private enum CommandsEnum { Help, MoveToLocation, ClearAll, ClearSpawn, ClearLogout, ListAllKeys, ListIntegrations } private const string playerClearAllCommand = "playerClearAll"; private const string playerClearSpawnCommand = "playerClearSpawn"; private const string playerClearLogoutCommand = "playerClearLogout"; private const string serverClearAllCommand = "serverClearAll"; private const string helpCommand = "help"; private static readonly ListAllKeysCommand ListAllKeysCommandInstance = new ListAllKeysCommand(); private static readonly ModIntegrationsCommand ModIntegrationsCommandInstance = new ModIntegrationsCommand(); private static readonly MoveToCommand MoveToCommandInstance = new MoveToCommand(); private static string helpCommandItems = string.Join("\n", "DynamicLocationsCLI Mod CLI: ", FormatCommand("playerClearLogout") + " removes logout for the current world, will not change other worlds", FormatCommand("playerClearAll") + " clears all dynamicLogin and dynamicSpawn points for a player for the corresponding world", FormatCommand((ConsoleCommand)(object)MoveToCommandInstance), FormatCommand((ConsoleCommand)(object)ListAllKeysCommandInstance), FormatCommand((ConsoleCommand)(object)ModIntegrationsCommandInstance)); public override string Help => OnHelp(); public override string Name => "dynamic-locations"; private static string FormatCommand(string? command) { if (command != null) { return "<" + command + ">:"; } return ""; } private static string FormatCommand(string command, List<string>? args, string description) { return "<" + command + ">: " + string.Join("", args?.Select((string arg) => " " + FormatCommand(arg)) ?? Array.Empty<string>()) + " " + description; } private static string FormatCommand(ConsoleCommand consoleCommand) { return FormatCommand(consoleCommand.Name, consoleCommand.CommandOptionList(), consoleCommand.Help); } private static string OnHelp() { return helpCommandItems; } private static CommandsEnum? GetCommandArg(string commandString) { if (((ConsoleCommand)ModIntegrationsCommandInstance).Name == commandString) { return CommandsEnum.ListIntegrations; } if (((ConsoleCommand)ListAllKeysCommandInstance).Name == commandString) { return CommandsEnum.ListAllKeys; } if (((ConsoleCommand)MoveToCommandInstance).Name == commandString) { return CommandsEnum.MoveToLocation; } return commandString switch { "playerClearAll" => CommandsEnum.ClearAll, "playerClearLogout" => CommandsEnum.ClearLogout, "help" => CommandsEnum.Help, _ => null, }; } public override void Run(string[] args) { if (args.Length != 0) { ParseFirstArg(args); } } private static void ParseFirstArg(string[]? args) { string text = args?.First() ?? ""; if (text == "") { Logger.LogMessage((object)"Must provide a argument for a command. Please run help for more information."); } CommandsEnum? commandArg = GetCommandArg(text); if (!commandArg.HasValue) { Logger.LogMessage((object)("Command " + text + " not recognized. Please run help for more information.")); return; } string[] array = args?.Skip(1)?.ToArray() ?? Array.Empty<string>(); if (commandArg.HasValue) { switch (commandArg.GetValueOrDefault()) { case CommandsEnum.ClearAll: PlayerClearAll(array); break; case CommandsEnum.ClearSpawn: case CommandsEnum.ClearLogout: case CommandsEnum.ListAllKeys: ((ConsoleCommand)ListAllKeysCommandInstance).Run(array); break; case CommandsEnum.ListIntegrations: ((ConsoleCommand)ModIntegrationsCommandInstance).Run(array); break; case CommandsEnum.Help: OnHelp(); break; case CommandsEnum.MoveToLocation: ((ConsoleCommand)MoveToCommandInstance).Run(array); break; default: throw new ArgumentOutOfRangeException(); } } } private bool IsAdmin() { if (!SynchronizationManager.Instance.PlayerIsAdmin) { Logger.LogMessage((object)"Player is not admin, must be admin to run this command"); return false; } return true; } public static void PlayerClearAll(string[] args) { if (args.Length == 0) { LocationController.DEBUG_RemoveAllDynamicLocationKeys(); } } public void PlayerListAllDynamicLocationKeys() { LocationController.DEBUGCOMMAND_ListAllKeys(); } public static void PlayerClearLogout() { LocationController.DEBUGCOMMAND_RemoveLogout(); } public override List<string> CommandOptionList() { return new List<string>(5) { ((ConsoleCommand)ListAllKeysCommandInstance).Name, ((ConsoleCommand)MoveToCommandInstance).Name, ((ConsoleCommand)ModIntegrationsCommandInstance).Name, "playerClearLogout", "playerClearAll" }; } } } namespace DynamicLocations.API { public class DynamicLoginIntegration { private const int DefaultMovementTimeoutMs = 5000; private readonly DebugSafeTimer _timerInstance = new DebugSafeTimer(); private bool _isRunningOnLoginMoveToZdo; private bool _hasCompleted; private Coroutine? _onLoginMoveToZdoCoroutine; public int LoginPrefabHashCode => Config.LoginPrefabHashCode; internal string Guid => Config.Guid; internal string Name => Config.Name; internal string Version => Config.Version; public bool ShouldFreezePlayer => Config.ShouldFreezePlayer; public List<string> RunBeforePlugins => Config.RunBeforePlugins; public List<string> RunAfterPlugins => Config.RunAfterPlugins; public int Priority { get { if (Config.Priority <= 0) { return 999; } return Config.Priority; } } public int MovementTimeoutMs => GetMovementTimeout(); public bool IsComplete { get { if (_hasCompleted && !_isRunningOnLoginMoveToZdo) { return _onLoginMoveToZdoCoroutine == null; } return false; } } public IntegrationConfig Config { get; set; } protected DynamicLoginIntegration(IntegrationConfig config) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown Config = config; } private int GetMovementTimeout() { int movementTimeout = Config.MovementTimeout; if (movementTimeout < 2000 || movementTimeout > 20000) { return 5000; } return Config.MovementTimeout; } public static IntegrationConfig CreateConfig(BaseUnityPlugin plugin, string zdoTargetPrefabName) { return new IntegrationConfig(plugin, zdoTargetPrefabName); } private void OnStart() { _timerInstance.Restart(); PlayerSpawnController.ResetRoutine(ref _onLoginMoveToZdoCoroutine); _hasCompleted = false; _isRunningOnLoginMoveToZdo = true; } private void OnComplete() { _timerInstance.Reset(); PlayerSpawnController.ResetRoutine(ref _onLoginMoveToZdoCoroutine); _isRunningOnLoginMoveToZdo = false; _hasCompleted = true; } protected internal IEnumerator API_OnLoginMoveToZDO(ZDO zdo, Vector3? offset, PlayerSpawnController playerSpawnController) { OnStart(); _onLoginMoveToZdoCoroutine = ((MonoBehaviour)playerSpawnController).StartCoroutine(OnLoginMoveToZDO(zdo, offset, playerSpawnController)); yield return _onLoginMoveToZdoCoroutine; yield return (object)new WaitUntil((Func<bool>)(() => _onLoginMoveToZdoCoroutine == null || _timerInstance.ElapsedMilliseconds >= (float)GetMovementTimeout())); OnComplete(); yield return true; } protected virtual IEnumerator OnLoginMoveToZDO(ZDO zdo, Vector3? offset, PlayerSpawnController playerSpawnController) { if (DynamicLocationsConfig.IsDebug) { Logger.LogDebug((object)"Not overridden custom handler, running MovePlayerToZdo default call."); } if (OnLoginMatchZdoPrefab(zdo)) { yield return playerSpawnController.MovePlayerToZdo(zdo, (Vector3)(((??)offset) ?? Vector3.zero)); yield return (object)new WaitUntil((Func<bool>)(() => PlayerSpawnController.MoveToLogoutRoutine == null)); } } [UsedImplicitly] public virtual bool OnLoginMatchZdoPrefab(ZDO zdo) { if (LoginPrefabHashCode == 0) { Logger.LogError((object)("Login Prefab Hash was zero, this likely means the mod " + Config.Name + " " + Config.Version + " has not properly been integrated for DynamicLoginIntegration")); return false; } return zdo.GetPrefab() == LoginPrefabHashCode; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { internal IgnoresAccessChecksToAttribute(string assemblyName) { } } }
plugins\Newtonsoft.Json.dll
Decompiled a week 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.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; 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 System.Xml; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Newtonsoft.Json.Bson; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq.JsonPath; using Newtonsoft.Json.Schema; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AllowPartiallyTrustedCallers] [assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")] [assembly: CLSCompliant(true)] [assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")] [assembly: AssemblyCompany("Newtonsoft")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © James Newton-King 2008")] [assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")] [assembly: AssemblyFileVersion("13.0.3.27908")] [assembly: AssemblyInformationalVersion("13.0.3+0a2e291c0d9c0c7675d445703e51750363a549ef")] [assembly: AssemblyProduct("Json.NET")] [assembly: AssemblyTitle("Json.NET .NET 4.5")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/JamesNK/Newtonsoft.Json")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("13.0.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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 System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } } namespace Newtonsoft.Json { public enum ConstructorHandling { Default, AllowNonPublicDefaultConstructor } public enum DateFormatHandling { IsoDateFormat, MicrosoftDateFormat } public enum DateParseHandling { None, DateTime, DateTimeOffset } public enum DateTimeZoneHandling { Local, Utc, Unspecified, RoundtripKind } public class DefaultJsonNameTable : JsonNameTable { private class Entry { internal readonly string Value; internal readonly int HashCode; internal Entry Next; internal Entry(string value, int hashCode, Entry next) { Value = value; HashCode = hashCode; Next = next; } } private static readonly int HashCodeRandomizer; private int _count; private Entry[] _entries; private int _mask = 31; static DefaultJsonNameTable() { HashCodeRandomizer = Environment.TickCount; } public DefaultJsonNameTable() { _entries = new Entry[_mask + 1]; } public override string? Get(char[] key, int start, int length) { if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; num += (num << 7) ^ key[start]; int num2 = start + length; for (int i = start + 1; i < num2; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; int num3 = Volatile.Read(ref _mask); int num4 = num & num3; for (Entry entry = _entries[num4]; entry != null; entry = entry.Next) { if (entry.HashCode == num && TextEquals(entry.Value, key, start, length)) { return entry.Value; } } return null; } public string Add(string key) { if (key == null) { throw new ArgumentNullException("key"); } int length = key.Length; if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; for (int i = 0; i < key.Length; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; for (Entry entry = _entries[num & _mask]; entry != null; entry = entry.Next) { if (entry.HashCode == num && entry.Value.Equals(key, StringComparison.Ordinal)) { return entry.Value; } } return AddEntry(key, num); } private string AddEntry(string str, int hashCode) { int num = hashCode & _mask; Entry entry = new Entry(str, hashCode, _entries[num]); _entries[num] = entry; if (_count++ == _mask) { Grow(); } return entry.Value; } private void Grow() { Entry[] entries = _entries; int num = _mask * 2 + 1; Entry[] array = new Entry[num + 1]; for (int i = 0; i < entries.Length; i++) { Entry entry = entries[i]; while (entry != null) { int num2 = entry.HashCode & num; Entry next = entry.Next; entry.Next = array[num2]; array[num2] = entry; entry = next; } } _entries = array; Volatile.Write(ref _mask, num); } private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length) { if (str1.Length != str2Length) { return false; } for (int i = 0; i < str1.Length; i++) { if (str1[i] != str2[str2Start + i]) { return false; } } return true; } } [Flags] public enum DefaultValueHandling { Include = 0, Ignore = 1, Populate = 2, IgnoreAndPopulate = 3 } public enum FloatFormatHandling { String, Symbol, DefaultValue } public enum FloatParseHandling { Double, Decimal } public enum Formatting { None, Indented } public interface IArrayPool<T> { T[] Rent(int minimumLength); void Return(T[]? array); } public interface IJsonLineInfo { int LineNumber { get; } int LinePosition { get; } bool HasLineInfo(); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonArrayAttribute : JsonContainerAttribute { private bool _allowNullItems; public bool AllowNullItems { get { return _allowNullItems; } set { _allowNullItems = value; } } public JsonArrayAttribute() { } public JsonArrayAttribute(bool allowNullItems) { _allowNullItems = allowNullItems; } public JsonArrayAttribute(string id) : base(id) { } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)] public sealed class JsonConstructorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public abstract class JsonContainerAttribute : Attribute { internal bool? _isReference; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; private Type? _namingStrategyType; private object[]? _namingStrategyParameters; public string? Id { get; set; } public string? Title { get; set; } public string? Description { get; set; } public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get { return _namingStrategyType; } set { _namingStrategyType = value; NamingStrategyInstance = null; } } public object[]? NamingStrategyParameters { get { return _namingStrategyParameters; } set { _namingStrategyParameters = value; NamingStrategyInstance = null; } } internal NamingStrategy? NamingStrategyInstance { get; set; } public bool IsReference { get { return _isReference.GetValueOrDefault(); } set { _isReference = value; } } public bool ItemIsReference { get { return _itemIsReference.GetValueOrDefault(); } set { _itemIsReference = value; } } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } protected JsonContainerAttribute() { } protected JsonContainerAttribute(string id) { Id = id; } } public static class JsonConvert { public static readonly string True = "true"; public static readonly string False = "false"; public static readonly string Null = "null"; public static readonly string Undefined = "undefined"; public static readonly string PositiveInfinity = "Infinity"; public static readonly string NegativeInfinity = "-Infinity"; public static readonly string NaN = "NaN"; public static Func<JsonSerializerSettings>? DefaultSettings { get; set; } public static string ToString(DateTime value) { return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); } public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling); using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(DateTimeOffset value) { return ToString(value, DateFormatHandling.IsoDateFormat); } public static string ToString(DateTimeOffset value, DateFormatHandling format) { using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(bool value) { if (!value) { return False; } return True; } public static string ToString(char value) { return ToString(char.ToString(value)); } public static string ToString(Enum value) { return value.ToString("D"); } public static string ToString(int value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(short value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ushort value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(uint value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(long value) { return value.ToString(null, CultureInfo.InvariantCulture); } private static string ToStringInternal(BigInteger value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ulong value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(float value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value))) { return text; } if (floatFormatHandling == FloatFormatHandling.DefaultValue) { if (nullable) { return Null; } return "0.0"; } return quoteChar + text + quoteChar; } public static string ToString(double value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureDecimalPlace(double value, string text) { if (double.IsNaN(value) || double.IsInfinity(value) || StringUtils.IndexOf(text, '.') != -1 || StringUtils.IndexOf(text, 'E') != -1 || StringUtils.IndexOf(text, 'e') != -1) { return text; } return text + ".0"; } private static string EnsureDecimalPlace(string text) { if (StringUtils.IndexOf(text, '.') != -1) { return text; } return text + ".0"; } public static string ToString(byte value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(sbyte value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(decimal value) { return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture)); } public static string ToString(Guid value) { return ToString(value, '"'); } internal static string ToString(Guid value, char quoteChar) { string text = value.ToString("D", CultureInfo.InvariantCulture); string text2 = quoteChar.ToString(CultureInfo.InvariantCulture); return text2 + text + text2; } public static string ToString(TimeSpan value) { return ToString(value, '"'); } internal static string ToString(TimeSpan value, char quoteChar) { return ToString(value.ToString(), quoteChar); } public static string ToString(Uri? value) { if (value == null) { return Null; } return ToString(value, '"'); } internal static string ToString(Uri value, char quoteChar) { return ToString(value.OriginalString, quoteChar); } public static string ToString(string? value) { return ToString(value, '"'); } public static string ToString(string? value, char delimiter) { return ToString(value, delimiter, StringEscapeHandling.Default); } public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling) { if (delimiter != '"' && delimiter != '\'') { throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter"); } return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling); } public static string ToString(object? value) { if (value == null) { return Null; } return ConvertUtils.GetTypeCode(value.GetType()) switch { PrimitiveTypeCode.String => ToString((string)value), PrimitiveTypeCode.Char => ToString((char)value), PrimitiveTypeCode.Boolean => ToString((bool)value), PrimitiveTypeCode.SByte => ToString((sbyte)value), PrimitiveTypeCode.Int16 => ToString((short)value), PrimitiveTypeCode.UInt16 => ToString((ushort)value), PrimitiveTypeCode.Int32 => ToString((int)value), PrimitiveTypeCode.Byte => ToString((byte)value), PrimitiveTypeCode.UInt32 => ToString((uint)value), PrimitiveTypeCode.Int64 => ToString((long)value), PrimitiveTypeCode.UInt64 => ToString((ulong)value), PrimitiveTypeCode.Single => ToString((float)value), PrimitiveTypeCode.Double => ToString((double)value), PrimitiveTypeCode.DateTime => ToString((DateTime)value), PrimitiveTypeCode.Decimal => ToString((decimal)value), PrimitiveTypeCode.DBNull => Null, PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), PrimitiveTypeCode.Guid => ToString((Guid)value), PrimitiveTypeCode.Uri => ToString((Uri)value), PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), PrimitiveTypeCode.BigInteger => ToStringInternal((BigInteger)value), _ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), }; } [DebuggerStepThrough] public static string SerializeObject(object? value) { return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, JsonSerializerSettings? settings) { return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); return SerializeObjectInternal(value, type, jsonSerializer); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings) { return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); jsonSerializer.Formatting = formatting; return SerializeObjectInternal(value, type, jsonSerializer); } private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer) { StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture); using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter)) { jsonTextWriter.Formatting = jsonSerializer.Formatting; jsonSerializer.Serialize(jsonTextWriter, value, type); } return stringWriter.ToString(); } [DebuggerStepThrough] public static object? DeserializeObject(string value) { return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static object? DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value) { return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject) { return DeserializeObject<T>(value); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject<T>(value, settings); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, params JsonConverter[] converters) { return (T)DeserializeObject(value, typeof(T), converters); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings) { return (T)DeserializeObject(value, typeof(T), settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return DeserializeObject(value, type, settings); } public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings) { ValidationUtils.ArgumentNotNull(value, "value"); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); if (!jsonSerializer.IsCheckAdditionalContentSet()) { jsonSerializer.CheckAdditionalContent = true; } using JsonTextReader reader = new JsonTextReader(new StringReader(value)); return jsonSerializer.Deserialize(reader, type); } [DebuggerStepThrough] public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); } public static void PopulateObject(string value, object target, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); using JsonReader jsonReader = new JsonTextReader(new StringReader(value)); jsonSerializer.Populate(jsonReader, target); if (settings == null || !settings.CheckAdditionalContent) { return; } while (jsonReader.Read()) { if (jsonReader.TokenType != JsonToken.Comment) { throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object."); } } } public static string SerializeXmlNode(XmlNode? node) { return SerializeXmlNode(node, Formatting.None); } public static string SerializeXmlNode(XmlNode? node, Formatting formatting) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); return SerializeObject(node, formatting, xmlNodeConverter); } public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } public static XmlDocument? DeserializeXmlNode(string value) { return DeserializeXmlNode(value, null); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), xmlNodeConverter); } public static string SerializeXNode(XObject? node) { return SerializeXNode(node, Formatting.None); } public static string SerializeXNode(XObject? node, Formatting formatting) { return SerializeXNode(node, formatting, omitRootObject: false); } public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } public static XDocument? DeserializeXNode(string value) { return DeserializeXNode(value, null); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XDocument)DeserializeObject(value, typeof(XDocument), xmlNodeConverter); } } public abstract class JsonConverter { public virtual bool CanRead => true; public virtual bool CanWrite => true; public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer); public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer); public abstract bool CanConvert(Type objectType); } public abstract class JsonConverter<T> : JsonConverter { public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (!((value != null) ? (value is T) : ReflectionUtils.IsNullable(typeof(T)))) { throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } WriteJson(writer, (T)value, serializer); } public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer); public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { bool flag = existingValue == null; if (!flag && !(existingValue is T)) { throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } return ReadJson(reader, objectType, flag ? default(T) : ((T)existingValue), !flag, serializer); } public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer); public sealed override bool CanConvert(Type objectType) { return typeof(T).IsAssignableFrom(objectType); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonConverterAttribute : Attribute { private readonly Type _converterType; public Type ConverterType => _converterType; public object[]? ConverterParameters { get; } public JsonConverterAttribute(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } _converterType = converterType; } public JsonConverterAttribute(Type converterType, params object[] converterParameters) : this(converterType) { ConverterParameters = converterParameters; } } public class JsonConverterCollection : Collection<JsonConverter> { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonDictionaryAttribute : JsonContainerAttribute { public JsonDictionaryAttribute() { } public JsonDictionaryAttribute(string id) : base(id) { } } [Serializable] public class JsonException : Exception { public JsonException() { } public JsonException(string message) : base(message) { } public JsonException(string message, Exception? innerException) : base(message, innerException) { } public JsonException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message) { message = JsonPosition.FormatMessage(lineInfo, path, message); return new JsonException(message); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class JsonExtensionDataAttribute : Attribute { public bool WriteData { get; set; } public bool ReadData { get; set; } public JsonExtensionDataAttribute() { WriteData = true; ReadData = true; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonIgnoreAttribute : Attribute { } public abstract class JsonNameTable { public abstract string? Get(char[] key, int start, int length); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonObjectAttribute : JsonContainerAttribute { private MemberSerialization _memberSerialization; internal MissingMemberHandling? _missingMemberHandling; internal Required? _itemRequired; internal NullValueHandling? _itemNullValueHandling; public MemberSerialization MemberSerialization { get { return _memberSerialization; } set { _memberSerialization = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public NullValueHandling ItemNullValueHandling { get { return _itemNullValueHandling.GetValueOrDefault(); } set { _itemNullValueHandling = value; } } public Required ItemRequired { get { return _itemRequired.GetValueOrDefault(); } set { _itemRequired = value; } } public JsonObjectAttribute() { } public JsonObjectAttribute(MemberSerialization memberSerialization) { MemberSerialization = memberSerialization; } public JsonObjectAttribute(string id) : base(id) { } } internal enum JsonContainerType { None, Object, Array, Constructor } internal struct JsonPosition { private static readonly char[] SpecialCharacters = new char[18] { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' }; internal JsonContainerType Type; internal int Position; internal string? PropertyName; internal bool HasIndex; public JsonPosition(JsonContainerType type) { Type = type; HasIndex = TypeHasIndex(type); Position = -1; PropertyName = null; } internal int CalculateLength() { switch (Type) { case JsonContainerType.Object: return PropertyName.Length + 5; case JsonContainerType.Array: case JsonContainerType.Constructor: return MathUtils.IntLength((ulong)Position) + 2; default: throw new ArgumentOutOfRangeException("Type"); } } internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer) { switch (Type) { case JsonContainerType.Object: { string propertyName = PropertyName; if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append("['"); if (writer == null) { writer = new StringWriter(sb); } JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer); sb.Append("']"); } else { if (sb.Length > 0) { sb.Append('.'); } sb.Append(propertyName); } break; } case JsonContainerType.Array: case JsonContainerType.Constructor: sb.Append('['); sb.Append(Position); sb.Append(']'); break; } } internal static bool TypeHasIndex(JsonContainerType type) { if (type != JsonContainerType.Array) { return type == JsonContainerType.Constructor; } return true; } internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition) { int num = 0; if (positions != null) { for (int i = 0; i < positions.Count; i++) { num += positions[i].CalculateLength(); } } if (currentPosition.HasValue) { num += currentPosition.GetValueOrDefault().CalculateLength(); } StringBuilder stringBuilder = new StringBuilder(num); StringWriter writer = null; char[] buffer = null; if (positions != null) { foreach (JsonPosition position in positions) { position.WriteTo(stringBuilder, ref writer, ref buffer); } } currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer); return stringBuilder.ToString(); } internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message) { if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { message = message.Trim(); if (!StringUtils.EndsWith(message, '.')) { message += "."; } message += " "; } message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path); if (lineInfo != null && lineInfo.HasLineInfo()) { message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); } message += "."; return message; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonPropertyAttribute : Attribute { internal NullValueHandling? _nullValueHandling; internal DefaultValueHandling? _defaultValueHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal ObjectCreationHandling? _objectCreationHandling; internal TypeNameHandling? _typeNameHandling; internal bool? _isReference; internal int? _order; internal Required? _required; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get; set; } public object[]? NamingStrategyParameters { get; set; } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public TypeNameHandling TypeNameHandling { get { return _typeNameHandling.GetValueOrDefault(); } set { _typeNameHandling = value; } } public bool IsReference { get { return _isReference.GetValueOrDefault(); } set { _isReference = value; } } public int Order { get { return _order.GetValueOrDefault(); } set { _order = value; } } public Required Required { get { return _required.GetValueOrDefault(); } set { _required = value; } } public string? PropertyName { get; set; } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } public bool ItemIsReference { get { return _itemIsReference.GetValueOrDefault(); } set { _itemIsReference = value; } } public JsonPropertyAttribute() { } public JsonPropertyAttribute(string propertyName) { PropertyName = propertyName; } } public abstract class JsonReader : IDisposable { protected internal enum State { Start, Complete, Property, ObjectStart, Object, ArrayStart, Array, Closed, PostValue, ConstructorStart, Constructor, Error, Finished } private JsonToken _tokenType; private object? _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; private CultureInfo? _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string? _dateFormatString; private List<JsonPosition>? _stack; protected State CurrentState => _currentState; public bool CloseInput { get; set; } public bool SupportMultipleContent { get; set; } public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException("value"); } _dateTimeZoneHandling = value; } } public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset) { throw new ArgumentOutOfRangeException("value"); } _dateParseHandling = value; } } public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) { throw new ArgumentOutOfRangeException("value"); } _floatParseHandling = value; } } public string? DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; } } public virtual JsonToken TokenType => _tokenType; public virtual object? Value => _value; public virtual Type? ValueType => _value?.GetType(); public virtual int Depth { get { int num = _stack?.Count ?? 0; if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) { return num; } return num + 1; } } public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null); return JsonPosition.BuildPath(_stack, currentPosition); } } public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } public virtual Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<bool>() ?? Read().ToAsync(); } public async Task SkipAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (TokenType == JsonToken.PropertyName) { await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) && depth < Depth) { } } } internal async Task ReaderReadAndAssertAsync(CancellationToken cancellationToken) { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { throw CreateUnexpectedEndException(); } } public virtual Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<bool?>() ?? Task.FromResult(ReadAsBoolean()); } public virtual Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<byte[]>() ?? Task.FromResult(ReadAsBytes()); } internal async Task<byte[]?> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken) { List<byte> buffer = new List<byte>(); do { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { SetToken(JsonToken.None); } } while (!ReadArrayElementIntoByteArrayReportDone(buffer)); byte[] array = buffer.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } public virtual Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<DateTime?>() ?? Task.FromResult(ReadAsDateTime()); } public virtual Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<DateTimeOffset?>() ?? Task.FromResult(ReadAsDateTimeOffset()); } public virtual Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<decimal?>() ?? Task.FromResult(ReadAsDecimal()); } public virtual Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult(ReadAsDouble()); } public virtual Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<int?>() ?? Task.FromResult(ReadAsInt32()); } public virtual Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<string>() ?? Task.FromResult(ReadAsString()); } internal async Task<bool> ReadAndMoveToContentAsync(CancellationToken cancellationToken) { bool flag = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (flag) { flag = await MoveToContentAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } return flag; } internal Task<bool> MoveToContentAsync(CancellationToken cancellationToken) { JsonToken tokenType = TokenType; if (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { return MoveToContentFromNonContentAsync(cancellationToken); } return AsyncUtils.True; } private async Task<bool> MoveToContentFromNonContentAsync(CancellationToken cancellationToken) { JsonToken tokenType; do { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { return false; } tokenType = TokenType; } while (tokenType == JsonToken.None || tokenType == JsonToken.Comment); return true; } internal JsonPosition GetPosition(int depth) { if (_stack != null && depth < _stack.Count) { return _stack[depth]; } return _currentPosition; } protected JsonReader() { _currentState = State.Start; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; _maxDepth = 64; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); return; } if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); if (!_maxDepth.HasValue || !(Depth + 1 > _maxDepth) || _hasExceededMaxDepth) { return; } _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } private JsonContainerType Pop() { JsonPosition currentPosition; if (_stack != null && _stack.Count > 0) { currentPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { currentPosition = _currentPosition; _currentPosition = default(JsonPosition); } if (_maxDepth.HasValue && Depth <= _maxDepth) { _hasExceededMaxDepth = false; } return currentPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } public abstract bool Read(); public virtual int? ReadAsInt32() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is int) { return (int)value; } int num; if (value is BigInteger bigInteger) { num = (int)bigInteger; } else { try { num = Convert.ToInt32(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } } SetToken(JsonToken.Integer, num, updateIndex: false); return num; } case JsonToken.String: { string s = (string)Value; return ReadInt32String(s); } default: throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal int? ReadInt32String(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out var result)) { SetToken(JsonToken.Integer, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual string? ReadAsString() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.String: return (string)Value; default: if (JsonTokenUtils.IsPrimitiveToken(contentToken)) { object value = Value; if (value != null) { string text = ((!(value is IFormattable formattable)) ? ((value is Uri uri) ? uri.OriginalString : value.ToString()) : formattable.ToString(null, Culture)); SetToken(JsonToken.String, text, updateIndex: false); return text; } } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } public virtual byte[]? ReadAsBytes() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.StartObject: { ReadIntoWrappedTypeObject(); byte[] array2 = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, array2, updateIndex: false); return array2; } case JsonToken.String: { string text = (string)Value; Guid g; byte[] array3 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray())); SetToken(JsonToken.Bytes, array3, updateIndex: false); return array3; } case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Bytes: if (Value is Guid guid) { byte[] array = guid.ToByteArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); default: throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal byte[] ReadArrayIntoByteArray() { List<byte> list = new List<byte>(); do { if (!Read()) { SetToken(JsonToken.None); } } while (!ReadArrayElementIntoByteArrayReportDone(list)); byte[] array = list.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer) { switch (TokenType) { case JsonToken.None: throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); case JsonToken.Integer: buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); return false; case JsonToken.EndArray: return true; case JsonToken.Comment: return false; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } public virtual double? ReadAsDouble() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is double) { return (double)value; } double num = ((!(value is BigInteger bigInteger)) ? Convert.ToDouble(value, CultureInfo.InvariantCulture) : ((double)bigInteger)); SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDoubleString((string)Value); default: throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal double? ReadDoubleString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual bool? ReadAsBoolean() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { bool flag = ((!(Value is BigInteger bigInteger)) ? Convert.ToBoolean(Value, CultureInfo.InvariantCulture) : (bigInteger != 0L)); SetToken(JsonToken.Boolean, flag, updateIndex: false); return flag; } case JsonToken.String: return ReadBooleanString((string)Value); case JsonToken.Boolean: return (bool)Value; default: throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal bool? ReadBooleanString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (bool.TryParse(s, out var result)) { SetToken(JsonToken.Boolean, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual decimal? ReadAsDecimal() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is decimal) { return (decimal)value; } decimal num; if (value is BigInteger bigInteger) { num = (decimal)bigInteger; } else { try { num = Convert.ToDecimal(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } } SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDecimalString((string)Value); default: throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal decimal? ReadDecimalString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out result) == ParseResult.Success) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTime? ReadAsDateTime() { switch (GetContentToken()) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTimeOffset dateTimeOffset) { SetToken(JsonToken.Date, dateTimeOffset.DateTime, updateIndex: false); } return (DateTime)Value; case JsonToken.String: return ReadDateTimeString((string)Value); default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } internal DateTime? ReadDateTimeString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTimeOffset? ReadAsDateTimeOffset() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTime dateTime) { SetToken(JsonToken.Date, new DateTimeOffset(dateTime), updateIndex: false); } return (DateTimeOffset)Value; case JsonToken.String: { string s = (string)Value; return ReadDateTimeOffsetString(s); } default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal DateTimeOffset? ReadDateTimeOffsetString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } internal void ReaderReadAndAssert() { if (!Read()) { throw CreateUnexpectedEndException(); } } internal JsonReaderException CreateUnexpectedEndException() { return JsonReaderException.Create(this, "Unexpected end when reading JSON."); } internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); if (Value != null && Value.ToString() == "$type") { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == "$value") { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } public void Skip() { if (TokenType == JsonToken.PropertyName) { Read(); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && depth < Depth) { } } } protected void SetToken(JsonToken newToken) { SetToken(newToken, null, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value) { SetToken(newToken, value, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Raw: case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: SetPostValueState(updateIndex); break; case JsonToken.Comment: break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != 0 || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } if (updateIndex) { UpdateScopeWithFinishedValue(); } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void ValidateEnd(JsonToken endToken) { JsonContainerType jsonContainerType = Pop(); if (GetTypeForCloseToken(endToken) != jsonContainerType) { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType)); } if (Peek() != 0 || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } } protected void SetStateBasedOnCurrent() { JsonContainerType jsonContainerType = Peek(); switch (jsonContainerType) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType)); } } private void SetFinished() { _currentState = ((!SupportMultipleContent) ? State.Finished : State.Start); } private JsonContainerType GetTypeForCloseToken(JsonToken token) { return token switch { JsonToken.EndObject => JsonContainerType.Object, JsonToken.EndArray => JsonContainerType.Array, JsonToken.EndConstructor => JsonContainerType.Constructor, _ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), }; } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } internal void ReadAndAssert() { if (!Read()) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter) { if (!ReadForType(contract, hasConverter)) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal bool ReadForType(JsonContract? contract, bool hasConverter) { if (hasConverter) { return Read(); } switch (contract?.InternalReadType ?? ReadType.Read) { case ReadType.Read: return ReadAndMoveToContent(); case ReadType.ReadAsInt32: ReadAsInt32(); break; case ReadType.ReadAsInt64: { bool result = ReadAndMoveToContent(); if (TokenType == JsonToken.Undefined) { throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long))); } return result; } case ReadType.ReadAsDecimal: ReadAsDecimal(); break; case ReadType.ReadAsDouble: ReadAsDouble(); break; case ReadType.ReadAsBytes: ReadAsBytes(); break; case ReadType.ReadAsBoolean: ReadAsBoolean(); break; case ReadType.ReadAsString: ReadAsString(); break; case ReadType.ReadAsDateTime: ReadAsDateTime(); break; case ReadType.ReadAsDateTimeOffset: ReadAsDateTimeOffset(); break; default: throw new ArgumentOutOfRangeException(); } return TokenType != JsonToken.None; } internal bool ReadAndMoveToContent() { if (Read()) { return MoveToContent(); } return false; } internal bool MoveToContent() { JsonToken tokenType = TokenType; while (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { if (!Read()) { return false; } tokenType = TokenType; } return true; } private JsonToken GetContentToken() { JsonToken tokenType; do { if (!Read()) { SetToken(JsonToken.None); return JsonToken.None; } tokenType = TokenType; } while (tokenType == JsonToken.Comment); return tokenType; } } [Serializable] public class JsonReaderException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonReaderException() { } public JsonReaderException(string message) : base(message) { } public JsonReaderException(string message, Exception innerException) : base(message, innerException) { } public JsonReaderException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonReaderException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonReaderException(message, path, lineNumber, linePosition, ex); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonRequiredAttribute : Attribute { } [Serializable] public class JsonSerializationException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonSerializationException() { } public JsonSerializationException(string message) : base(message) { } public JsonSerializationException(string message, Exception innerException) : base(message, innerException) { } public JsonSerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonSerializationException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonSerializationException(message, path, lineNumber, linePosition, ex); } } public class JsonSerializer { internal TypeNameHandling _typeNameHandling; internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; internal JsonConverterCollection? _converters; internal IContractResolver _contractResolver; internal ITraceWriter? _traceWriter; internal IEqualityComparer? _equalityComparer; internal ISerializationBinder _serializationBinder; internal StreamingContext _context; private IReferenceResolver? _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string? _dateFormatString; private bool _dateFormatStringSet; public virtual IReferenceResolver? ReferenceResolver { get { return GetReferenceResolver(); } set { if (value == null) { throw new ArgumentNullException("value", "Reference resolver cannot be null."); } _referenceResolver = value; } } [Obsolete("Binder is obsolete. Use SerializationBinder instead.")] public virtual SerializationBinder Binder { get { if (_serializationBinder is SerializationBinder result) { return result; } if (_serializationBinder is SerializationBinderAdapter serializationBinderAdapter) { return serializationBinderAdapter.SerializationBinder; } throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set."); } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = (value as ISerializationBinder) ?? new SerializationBinderAdapter(value); } } public virtual ISerializationBinder SerializationBinder { get { return _serializationBinder; } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = value; } } public virtual ITraceWriter? TraceWriter { get { return _traceWriter; } set { _traceWriter = value; } } public virtual IEqualityComparer? EqualityComparer { get { return _equalityComparer; } set { _equalityComparer = value; } } public virtual TypeNameHandling TypeNameHandling { get { return _typeNameHandling; } set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) { throw new ArgumentOutOfRangeException("value"); } _typeNameHandling = value; } } [Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")] public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get { return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling; } set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value; } } public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling { get { return _typeNameAssemblyFormatHandling; } set { if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = value; } } public virtual PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling; } set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) { throw new ArgumentOutOfRangeException("value"); } _preserveReferencesHandling = value; } } public virtual ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) { throw new ArgumentOutOfRangeException("value"); } _referenceLoopHandling = value; } } public virtual MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) { throw new ArgumentOutOfRangeException("value"); } _missingMemberHandling = value; } } public virtual NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _nullValueHandling = value; } } public virtual DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) { throw new ArgumentOutOfRangeException("value"); } _defaultValueHandling = value; } } public virtual ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) { throw new ArgumentOutOfRangeException("value"); } _objectCreationHandling = value; } } public virtual ConstructorHandling ConstructorHandling { get { return _constructorHandling; } set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) { throw new ArgumentOutOfRangeException("value"); } _constructorHandling = value; } } public virtual MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling; } set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _metadataPropertyHandling = value; } } public virtual JsonConverterCollection Converters { get { if (_converters == null) { _converters = new JsonConverterCollection(); } return _converters; } } public virtual IContractResolver ContractResolver { get { return _contractResolver; } set { _contractResolver = value ?? DefaultContractResolver.Instance; } } public virtual StreamingContext Context { get { return _context; } set { _context = value; } } public virtual Formatting Formatting { get { return _formatting.GetValueOrDefault(); } set { _formatting = value; } } public virtual DateFormatHandling DateFormatHandling { get { return _dateFormatHandling.GetValueOrDefault(); } set { _dateFormatHandling = value; } } public virtual DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind; } set { _dateTimeZoneHandling = value; } } public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling ?? DateParseHandling.DateTime; } set { _dateParseHandling = value; } } public virtual FloatParseHandling FloatParseHandling { get { return _floatParseHandling.GetValueOrDefault(); } set { _floatParseHandling = value; } } public virtual FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling.GetValueOrDefault(); } set { _floatFormatHandling = value; } } public virtual StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling.GetValueOrDefault(); } set { _stringEscapeHandling = value; } } public virtual string DateFormatString { get { return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; } set { _dateFormatString = value; _dateFormatStringSet = true; } } public virtual CultureInfo Culture { get { return _culture ?? JsonSerializerSettings.DefaultCulture; } set { _culture = value; } } public virtual int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; _maxDepthSet = true; } } public virtual bool CheckAdditionalContent { get { return _checkAdditionalContent.GetValueOrDefault(); } set { _checkAdditionalContent = value; } } public virtual event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error; internal bool IsCheckAdditionalContentSet() { return _checkAdditionalContent.HasValue; } public JsonSerializer() { _referenceLoopHandling = ReferenceLoopHandling.Error; _missingMemberHandling = MissingMemberHandling.Ignore; _nullValueHandling = NullValueHandling.Include; _defaultValueHandling = DefaultValueHandling.Include; _objectCreationHandling = ObjectCreationHandling.Auto; _preserveReferencesHandling = PreserveReferencesHandling.None; _constructorHandling = ConstructorHandling.Default; _typeNameHandling = TypeNameHandling.None; _metadataPropertyHandling = MetadataPropertyHandling.Default; _context = JsonSerializerSettings.DefaultContext; _serializationBinder = DefaultSerializationBinder.Instance; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } public static JsonSerializer Create() { return new JsonSerializer(); } public static JsonSerializer Create(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = Create(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } public static JsonSerializer CreateDefault() { return Create(JsonConvert.DefaultSettings?.Invoke()); } public static JsonSerializer CreateDefault(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = CreateDefault(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } if (settings._typeNameHandling.HasValue) { serializer.TypeNameHandling = settings.TypeNameHandling; } if (settings._metadataPropertyHandling.HasValue) { serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; } if (settings._typeNameAssemblyFormatHandling.HasValue) { serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling; } if (settings._preserveReferencesHandling.HasValue) { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; } if (settings._referenceLoopHandling.HasValue) { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; } if (settings._missingMemberHandling.HasValue) { serializer.MissingMemberHandling = settings.MissingMemberHandling; } if (settings._objectCreationHandling.HasValue) { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; } if (settings._nullValueHandling.HasValue) { serializer.NullValueHandling = settings.NullValueHandling; } if (settings._defaultValueHandling.HasValue) { serializer.DefaultValueHandling = settings.DefaultValueHandling; } if (settings._constructorHandling.HasValue) { serializer.ConstructorHandling = settings.ConstructorHandling; } if (settings._context.HasValue) { serializer.Context = settings.Context; } if (settings._checkAdditionalContent.HasValue) { serializer._checkAdditionalContent = settings._checkAdditionalContent; } if (settings.Error != null) { serializer.Error += settings.Error; } if (settings.ContractResolver != null) { serializer.ContractResolver = settings.ContractResolver; } if (settings.ReferenceResolverProvider != null) { serializer.ReferenceResolver = settings.ReferenceResolverProvider(); } if (settings.TraceWriter != null) { serializer.TraceWriter = settings.TraceWriter; } if (settings.EqualityComparer != null) { serializer.EqualityComparer = settings.EqualityComparer; } if (settings.SerializationBinder != null) { serializer.SerializationBinder = settings.SerializationBinder; } if (settings._formatting.HasValue) { serializer._formatting = settings._formatting; } if (settings._dateFormatHandling.HasValue) { serializer._dateFormatHandling = settings._dateFormatHandling; } if (settings._dateTimeZoneHandling.HasValue) { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; } if (settings._dateParseHandling.HasValue) { serializer._dateParseHandling = settings._dateParseHandling; } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling.HasValue) { serializer._floatFormatHandling = settings._floatFormatHandling; } if (settings._floatParseHandling.HasValue) { serializer._floatParseHandling = settings._floatParseHandling; } if (settings._stringEscapeHandling.HasValue) { serializer._stringEscapeHandling = settings._stringEscapeHandling; } if (settings._culture != null) { serializer._culture = settings._culture; } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } } [DebuggerStepThrough] public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } [DebuggerStepThrough] public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, "reader"); ValidationUtils.ArgumentNotNull(target, "target"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader) { return Deserialize(reader, null); } [DebuggerStepThrough] public object? Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } [DebuggerStepThrough] public T? Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader, Type? objectType) { return DeserializeInternal(reader, objectType); } internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType) { ValidationUtils.ArgumentNotNull(reader, "reader"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); object? result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); return result; } internal void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString) { if (_culture != null && !_culture.Equals(reader.Culture)) { previousCulture = reader.Culture; reader.Culture = _culture; } else { previousCulture = null; } if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } else { previousDateTimeZoneHandling = null; } if (_dateParseHandling.HasValue && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.GetValueOrDefault(); } else { previousDateParseHandling = null; } if (_floatParseHandling.HasValue && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault(); } else { previousFloatParseHandling = null; } if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } else { previousMaxDepth = null; } if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) { previousDateFormatString = reader.DateFormatString; reader.DateFormatString = _dateFormatString; } else { previousDateFormatString = null; } if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable == null && _contractResolver is DefaultContractResolver defaultContractResolver) { jsonTextReader.PropertyNameTable = defaultContractResolver.GetNameTable(); } } private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString) { if (previousCulture != null) { reader.Culture = previousCulture; } if (previousDateTimeZoneHandling.HasValue) { reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousDateParseHandling.HasValue) { reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault(); } if (previousFloatParseHandling.HasValue) { reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault(); } if (_maxDepthSet) { reader.MaxDepth = previousMaxDepth; } if (_dateFormatStringSet) { reader.DateFormatString = previousDateFormatString; } if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable != null && _contractResolver is DefaultContractResolver defaultContractResolver && jsonTextReader.PropertyNameTable == defaultContractResolver.GetNameTable()) { jsonTextReader.PropertyNameTable = null; } } public void Serialize(TextWriter textWriter, object? value) { Serialize(new JsonTextWriter(textWriter), value); } public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType) { SerializeInternal(jsonWriter, value, objectType); } public void Serialize(TextWriter textWriter, object? value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } public void Serialize(JsonWriter jsonWriter, object? value) { SerializeInternal(jsonWriter, value, null); } private TraceJsonReader CreateTraceJsonReader(JsonReader reader) { TraceJsonReader traceJsonReader = new TraceJsonReader(reader); if (reader.TokenType != 0) { traceJsonReader.WriteCurrentToken(); } return traceJsonReader; } internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter"); Formatting? formatting = null; if (_formatting.HasValue && jsonWriter.Formatting != _formatting) { formatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.GetValueOrDefault(); } DateFormatHandling? dateFormatHandling = null; if (_dateFormatHandling.HasValue && jsonWriter.DateFormatHandling != _dateFormatHandling) { dateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault(); } DateTimeZoneHandling? dateTimeZoneHandling = null; if (_dateTimeZoneHandling.HasValue && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) { dateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } FloatFormatHandling? floatFormatHandling = null; if (_floatFormatHandling.HasValue && jsonWriter.FloatFormatHandling != _floatFormatHandling) { floatFormatHandling = jsonWriter.FloatFormatHandling; jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault(); } StringEscapeHandling? stringEscapeHandling = null; if (_stringEscapeHandling.HasValue && jsonWriter.StringEscapeHandling != _stringEscapeHandling) { stringEscapeHandling = jsonWriter.StringEscapeHandling; jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); } CultureInfo cultureInfo = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { cultureInfo = jsonWriter.Culture; jsonWriter.Culture = _culture; } string dateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { dateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } TraceJsonWriter traceJsonWriter = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null); new JsonSerializerInternalWriter(this).Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); } if (formatting.HasValue) { jsonWriter.Formatting = formatting.GetValueOrDefault(); } if (dateFormatHandling.HasValue) { jsonWriter.DateFormatHandling = dateFormatHandling.GetValueOrDefault(); } if (dateTimeZoneHandling.HasValue) { jsonWriter.DateTimeZoneHandling = dateTimeZoneHandling.GetValueOrDefault(); } if (floatFormatHandling.HasValue) { jsonWriter.FloatFormatHandling = floatFormatHandling.GetValueOrDefault(); } if (stringEscapeHandling.HasValue) { jsonWriter.StringEscapeHandling = stringEscapeHandling.GetValueOrDefault(); } if (_dateFormatStringSet) { jsonWriter.DateFormatString = dateFormatString; } if (cultureInfo != null) { jsonWriter.Culture = cultureInfo; } } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) { _referenceResolver = new DefaultReferenceResolver(); } return _referenceResolver; } internal JsonConverter? GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } internal static JsonConverter? GetMatchingConverter(IList<JsonConverter>? converters, Type objectType) { if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter jsonConverter = converters[i]; if (jsonConverter.CanConvert(objectType)) { return jsonConverter; } } } return null; } internal void OnError(Newtonsoft.Json.Serialization.ErrorEventArgs e) { this.Error?.Invoke(this, e); } } public class JsonSerializerSettings { internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error; internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore; internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include; internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include; internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto; internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None; internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default; internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None; internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default; internal static readonly StreamingContext DefaultContext; internal const Formatting DefaultFormatting = Formatting.None; internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat; internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime; internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double; internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String; internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default; internal const TypeNameAssemblyFormatHandling DefaultTypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple; internal static readonly CultureInfo DefaultCulture; internal const bool DefaultCheckAdditionalContent = false; internal const string DefaultDateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; internal const int DefaultMaxDepth = 64; internal Formatting? _formatting; internal DateFormatHandling? _dateFormatHandling; internal DateTimeZoneHandling? _dateTimeZoneHandling; internal DateParseHandling? _dateParseHandling; internal FloatFormatHandling? _floatFormatHandling; internal FloatParseHandling? _floatParseHandling; internal StringEscapeHandling? _stringEscapeHandling; internal CultureInfo? _culture; internal bool? _checkAdditionalContent; internal int? _maxDepth; internal bool _maxDepthSet; internal string? _dateFormatString; internal bool _dateFormatStringSet; internal TypeNameAssemblyFormatHandling? _typeNameAssemblyFormatHandling; internal DefaultValueHandling? _defaultValueHandling; internal PreserveReferencesHandling? _preserveReferencesHandling; internal NullValueHandling? _nullValueHandling; internal ObjectCreationHandling? _objectCreationHandling; internal MissingMemberHandling? _missingMemberHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal StreamingContext? _context; internal ConstructorHandling? _constructorHandling; internal TypeNameHandling? _typeNameHandling; internal MetadataPropertyHandling? _metadataPropertyHandling; public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public IList<JsonConverter> Converters { get; set; } public PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling.GetValueOrDef
plugins\Shared.dll
Decompiled a week agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; 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.Configuration; using HarmonyLib; using JetBrains.Annotations; using Jotunn; using Jotunn.Utils; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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 Shared.Interfaces { public interface PluginInfo { string Name { get; } string Version { get; } string Guid { get; } } } namespace Zolantris.Shared { [AttributeUsage(AttributeTargets.Method)] public class MeasureTimeAttribute : Attribute { } public static class TimerUtility { public static void ExecuteWithTiming(Action action, [CallerMemberName] string methodName = "") { } public static void MeasureTimeWithAttribute(object instance, string methodName) { object instance2 = instance; MethodInfo method = instance2.GetType().GetMethod(methodName); if ((object)method != null && method.GetCustomAttribute<MeasureTimeAttribute>() != null) { ExecuteWithTiming(delegate { method.Invoke(instance2, null); }, methodName); } else { method?.Invoke(instance2, null); } } } public class BatchedLogger : MonoBehaviour { private static BatchedLogger? _instance; private static readonly Queue<string> _logQueue = new Queue<string>(); private float _timer; public static bool IsLoggingEnabled { get; set; } = true; [UsedImplicitly] public static float BatchIntervalFrequencyInSeconds { get; set; } = 3f; public static BatchedLogger Instance { get { //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_0021: Expected O, but got Unknown if (_instance == null) { GameObject val = new GameObject("Logger"); _instance = val.AddComponent<BatchedLogger>(); Object.DontDestroyOnLoad((Object)val); } return _instance; } } public void Log(string message) { _logQueue.Enqueue(message); } private void FlushLogs() { while (_logQueue.Count > 0) { Logger.LogInfo((object)_logQueue.Dequeue()); } } } public static class HarmonyHelper { private const bool IsDebug = false; public static void TryPatchAll(Harmony harmonyInstance, Type type) { try { harmonyInstance.PatchAll(type); } catch (Exception arg) { Logger.LogError((object)$"[Harmony] Failed to patch: {type.Name}\n{arg}"); } } public static void TryPatchAll(Harmony harmonyInstance, params Type[] patchTypes) { foreach (Type type in patchTypes) { TryPatchAll(harmonyInstance, type); } } } } namespace Zolantris.Shared.Debug { public class DebugSafeTimer { private bool _isRunning; private float _elapsedTime; private List<DebugSafeTimer>? _listRef; public float ElapsedMilliseconds => _elapsedTime * 1000f; public static DebugSafeTimer StartNew() { DebugSafeTimer debugSafeTimer = new DebugSafeTimer(); debugSafeTimer.Start(); return debugSafeTimer; } public static DebugSafeTimer StartNew(List<DebugSafeTimer> list) { DebugSafeTimer debugSafeTimer = new DebugSafeTimer(); debugSafeTimer.Start(); list.Add(debugSafeTimer); debugSafeTimer._listRef = list; return debugSafeTimer; } public static void UpdateTimersFromList(List<DebugSafeTimer> list) { if (list.Count == 0) { return; } DebugSafeTimer[] array = list.ToArray(); foreach (DebugSafeTimer debugSafeTimer in array) { if (debugSafeTimer != null) { debugSafeTimer.Update(); } else if (debugSafeTimer == null) { list.Remove(debugSafeTimer); } } } [UsedImplicitly] public void Start() { if (_listRef != null && !_listRef.Contains(this)) { _listRef.Add(this); } _isRunning = true; } [UsedImplicitly] public void Stop() { _isRunning = false; } [UsedImplicitly] public void Reset() { if (_listRef != null && _listRef.Contains(this)) { _listRef.Remove(this); } _elapsedTime = 0f; Stop(); } [UsedImplicitly] public void Restart() { _elapsedTime = 0f; Start(); } [UsedImplicitly] public void Clear() { Reset(); if (_listRef == null) { Logger.LogWarning((object)"Called delete but listRef did not exist"); } else { _listRef?.Remove(this); } } private void OnUpdateAutoExpire() { if (ElapsedMilliseconds > 20000f) { Clear(); } } [UsedImplicitly] private void Update() { if (_isRunning) { _elapsedTime += Time.deltaTime; } OnUpdateAutoExpire(); } } } namespace Zolantris.Shared.ModIntegrations { public interface IModIntegrationApi { void RunIntegration(); } public static class ConditionalImporter { public static bool ImportConditionally(string modGuid, string targetClass) { Type type = Type.GetType("Namespace.ParentClassName"); if (type != null) { Logger.LogDebug((object)("Conditional " + modGuid + " found. " + targetClass + " will now run")); (Activator.CreateInstance(type) as IModIntegrationApi)?.RunIntegration(); return true; } Logger.LogDebug((object)("Conditional " + modGuid + " not found. Exiting")); return false; } } } namespace Zolantris.Shared.BepInExAutoDoc { public class BepInExConfigAutoDoc { public bool runOnRelease; public bool runOnDebug = true; private static readonly Regex ConfigMatchRegExp = new Regex("\\[(.*?)\\]"); private static string? GetOutputFolderPath(PluginInfo plugin, string autoDocName) { string directoryName = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location); string directoryName2 = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Logger.LogDebug((object)("BepInExConfigAutoDoc: GetOutputFolderPath() " + directoryName)); Logger.LogDebug((object)("BepInExConfigAutoDoc: GetOutputFolderPath() executingAssemblyLocation " + directoryName2)); if (directoryName2 == null) { return null; } return Path.Combine(directoryName2, autoDocName + "_AutoDoc.md"); } private static string StripString(string x) { return ConfigMatchRegExp.Match(x).Groups[1].Value; } private static void AutoWriteBepInExConfigDoc(PluginInfo plugin, ConfigFile Config, string documentName) { StringBuilder stringBuilder = new StringBuilder(); string text = ""; foreach (ConfigDefinition key in Config.Keys) { if (key.Section != text) { text = key.Section; stringBuilder.Append(Environment.NewLine + "## " + key.Section + Environment.NewLine); } stringBuilder.Append(("\n### " + key.Key + " [" + StripString(Config[key].Description.Description) + "]").Replace("[]", "") + Environment.NewLine + "- Description: " + Config[key].Description.Description.Replace("[Synced with Server]", "").Replace("[Not Synced with Server]", "") + $"{Environment.NewLine}- Default Value: {Config[key].DefaultValue}{Environment.NewLine}"); } string outputFolderPath = GetOutputFolderPath(plugin, documentName); if (outputFolderPath != null) { File.WriteAllText(outputFolderPath, stringBuilder.ToString()); } } public void Generate(BaseUnityPlugin plugin, ConfigFile configFile, string documentName) { PluginInfo pluginInfoFromType = BepInExUtils.GetPluginInfoFromType(((object)plugin).GetType()); Generate(pluginInfoFromType, configFile, documentName); } public void Generate(FileInfo pluginPath, ConfigFile configFile, string documentName) { PluginInfo pluginInfoFromPath = BepInExUtils.GetPluginInfoFromPath(pluginPath); Generate(pluginInfoFromPath, configFile, documentName); } public void Generate(PluginInfo pluginInfo, ConfigFile configFile, string documentName) { AutoWriteBepInExConfigDoc(pluginInfo, configFile, documentName); } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { internal IgnoresAccessChecksToAttribute(string assemblyName) { } } }
plugins\ValheimRAFT.dll
Decompiled a week agousing System; using System.Collections.Generic; 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.Configuration; using DynamicLocations.API; using DynamicLocations.Controllers; using JetBrains.Annotations; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.Rendering; using ValheimVehicles; using ValheimVehicles.Compat; using ValheimVehicles.Components; using ValheimVehicles.ConsoleCommands; using ValheimVehicles.Controllers; using ValheimVehicles.Injections; using ValheimVehicles.ModSupport; using ValheimVehicles.Prefabs; using ValheimVehicles.Providers; using ValheimVehicles.SharedScripts; using ZdoWatcher; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("ValheimRAFT")] [assembly: AssemblyDescription("Valheim Mod for building on the sea, requires Jotunn to be installed.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Virtualize LLC")] [assembly: AssemblyProduct("ValheimRAFT")] [assembly: AssemblyCopyright("Copyright © 2023-2024, GNU-v3 licensed")] [assembly: Guid("6015B165-2627-40A7-8CA1-3E6B6CD7CB49")] [assembly: AssemblyFileVersion("3.3.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("3.3.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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 ValheimRAFT { public class DockComponent : MonoBehaviour { private enum DockState { None, EnteringDock, Docked, LeavingDock } private DockState m_dockState; private float m_dockingStrength = 1f; private GameObject m_dockedObject; private Rigidbody m_dockedRigidbody; private ZNetView m_nview; public Transform m_dockLocation; public Transform m_dockExit; public void Awake() { m_nview = ((Component)this).GetComponent<ZNetView>(); } public void FixedUpdate() { if (Object.op_Implicit((Object)(object)m_dockedRigidbody)) { if (m_dockState == DockState.EnteringDock) { PushToward(m_dockLocation); } else if (m_dockState == DockState.LeavingDock) { PushToward(m_dockExit); } } } private void PushToward(Transform target) { //IL_0006: 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_0020: 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_0034: Unknown result type (might be due to invalid IL or missing references) Vector3 val = ((Component)target).transform.position - ((Component)m_dockedRigidbody).transform.position; m_dockedRigidbody.AddForce(((Vector3)(ref val)).normalized * m_dockingStrength, (ForceMode)2); } public void OnTriggerEnter(Collider other) { if (Object.op_Implicit((Object)(object)m_dockedObject) && CanDock(other)) { Dock(other); } } private void Dock(Collider other) { ZNetView componentInParent = ((Component)other).GetComponentInParent<ZNetView>(); if (Object.op_Implicit((Object)(object)componentInParent) && componentInParent.IsOwner()) { Rigidbody component = ((Component)componentInParent).GetComponent<Rigidbody>(); if (Object.op_Implicit((Object)(object)component)) { int orCreatePersistentID = ZdoWatchController.Instance.GetOrCreatePersistentID(componentInParent.m_zdo); m_dockedObject = ((Component)componentInParent).gameObject; m_dockedRigidbody = component; m_nview.m_zdo.Set("MBDock_dockedObject", orCreatePersistentID); m_dockState = DockState.EnteringDock; } } } private bool CanDock(Collider other) { if (((Object)other).name.StartsWith("Karve")) { return true; } if (((Object)other).name.StartsWith("VikingShip")) { return true; } return false; } } public class MoveableBaseRootComponent : MonoBehaviour { public void Awake() { LoggerProvider.LogError("V1 vehicles are removed. You should never see this message unless another mod is force rendering ValheimRAFT. Deprecation started at v2.0.0 of ValheimRAFT and v3 does not support v1 rafts anymore.\n This class is retained to not break older mods. It may be removed in future versions.", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\ValheimRAFT\\ValheimRAFT\\MoveableBaseRootComponent.cs", 16); } public void CleanUp() { } private void Sync() { } public void FixedUpdate() { } public void LateUpdate() { } public void Client_UpdateAllPieces() { } public void ServerSyncAllPieces() { } public void UpdatePieces(List<ZDO> list) { } internal float GetColliderBottom() { return 0f; } public static void AddInactivePiece(int id, ZNetView netView) { } public void UpdateMass(ZNetView netView, bool isRemoving = false) { } public void RemovePiece(ZNetView netView) { } private float ComputeContainerWeight(Container container, bool isRemoving = false) { return 0f; } private float ComputePieceWeight(Piece piece, bool isRemoving) { return 0f; } public void DestroyPiece(WearNTear wnt) { } public void DestroyBoat() { } public static void AddDynamicParent(ZNetView source, GameObject target) { } public float GetTotalSailArea() { return 0f; } [Obsolete("GetSailingForce is deprecated, please use VehicleMovementController.GetSailingForce instead.")] public float GetSailingForce() { return 0f; } public static void AddDynamicParent(ZNetView source, GameObject target, Vector3 offset) { } public static void InitZDO(ZDO zdo) { } public static void RemoveZDO(ZDO zdo) { } private static int GetParentID(ZDO zdo) { return 0; } public static void InitPiece(ZNetView netview) { } public void ActivatePiece(ZNetView netview) { } public void AddTemporaryPiece(Piece piece) { } public void AddNewPiece(Piece piece) { } public void AddNewPiece(ZNetView netView) { } public void AddPiece(ZNetView netView) { } private void UpdatePieceCount() { } public void EncapsulateBounds(ZNetView netview) { } internal int GetPieceCount() { return 0; } } public class MoveableBaseShipComponent : MonoBehaviour { [Flags] public enum MBFlags { None = 0, IsAnchored = 1, HideMesh = 2 } public VehicleDebugHelpers VehicleDebugHelpersInstance; public MoveableBaseRootComponent m_baseRoot; public bool isCreative; internal Rigidbody m_rigidbody; internal Ship m_ship; internal ShipStats m_shipStats = new ShipStats(); internal ZNetView m_nview; internal GameObject m_baseRootObject; internal ZSyncTransform m_zsync; public float m_targetHeight; public float m_balanceForce = 0.03f; public float m_liftForce = 20f; public MBFlags m_flags; public bool IsAnchored => m_flags.HasFlag(MBFlags.IsAnchored); public MoveableBaseRootComponent GetMbRoot() { return m_baseRoot; } public void Awake() { } public void UpdateVisual() { } public void OnDestroy() { } public ShipStats GetShipStats() { return m_shipStats; } private void FirstTimeCreation() { } public void Ascend() { } public void Descent() { } public void UpdateStats(bool flight) { } public void SetAnchor(bool state) { } public void RPC_SetAnchor(long sender, bool state) { } internal void SetVisual(bool state) { } public void RPC_SetVisual(long sender, bool state) { } } internal abstract class PluginDependencies { public const string JotunnModGuid = "com.jotunn.jotunn"; } [BepInPlugin("zolantris.ValheimRAFT", "ValheimRAFT", "3.3.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency("zolantris.DynamicLocations", "1.2.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] public class ValheimRaftPlugin : BaseUnityPlugin { public const string Author = "zolantris"; public const string Version = "3.3.0"; public const string ModName = "ValheimRAFT"; public const string ModNameBeta = "ValheimRAFTBETA"; public const string ModGuid = "zolantris.ValheimRAFT"; public const string ModDescription = "Valheim Mod for building on the sea, requires Jotunn to be installed."; public const string CopyRight = "Copyright © 2023-2024, GNU-v3 licensed"; public static string HarmonyGuid => "zolantris.ValheimRAFT"; public static ValheimRaftPlugin Instance { get; private set; } private ConfigDescription CreateConfigDescription(string description, bool isAdmin = false, bool isAdvanced = false, AcceptableValueBase? acceptableValues = null) { //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) //IL_0024: Expected O, but got Unknown //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown return new ConfigDescription(description, acceptableValues, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = isAdmin, IsAdvanced = isAdvanced } }); } [UsedImplicitly] public static string GetVersion() { return "3.3.0"; } public void Awake() { Instance = this; ProviderInitializers.InitProviders(((BaseUnityPlugin)this).Logger, ((Component)this).gameObject); ValheimRAFT_API.RegisterHost((object)Instance); ValheimVehiclesPlugin.CreateConfigFromRAFTConfig(((BaseUnityPlugin)this).Config); PatchController.Apply(HarmonyGuid); AddPhysicsSettings(); RegisterVehicleConsoleCommands(); PrefabManager.OnVanillaPrefabsAvailable += delegate { if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsDedicated()) { LoadCustomTextures(); } AddCustomItemsAndPieces(); }; ZdoWatcherDelegate.RegisterToZdoManager(); AddModSupport(); RenderPipelineAsset defaultRenderPipeline = GraphicsSettings.defaultRenderPipeline; if ((Object)(object)defaultRenderPipeline != (Object)null) { ((BaseUnityPlugin)this).Logger.LogDebug((object)$"Valheim GameEngine is using: <{defaultRenderPipeline}> graphics pipeline "); } ((Component)this).gameObject.AddComponent<ValheimVehiclesPlugin>(); } private void OnDestroy() { PatchController.UnpatchSelf(); } public void AddModSupport() { AddModSupportDynamicLocations(); } public void AddModSupportDynamicLocations() { //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_0015: Expected O, but got Unknown LoginAPIController.AddLoginApiIntegration((DynamicLoginIntegration)new DynamicLocationsLoginIntegration(DynamicLoginIntegration.CreateConfig((BaseUnityPlugin)(object)this, "ValheimVehicles_WaterVehicleShip"))); } public void RegisterVehicleConsoleCommands() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown CommandManager.Instance.AddConsoleCommand((ConsoleCommand)new VehicleCommands()); } private void Start() { GenerateAutoDocs(); } private void GenerateAutoDocs() { } private void AddPhysicsSettings() { int num = LayerMask.NameToLayer("vehicle"); for (int i = 0; i < 32; i++) { Physics.IgnoreLayerCollision(29, i, Physics.GetIgnoreLayerCollision(num, i)); } Physics.IgnoreLayerCollision(29, LayerMask.NameToLayer("vehicle"), true); Physics.IgnoreLayerCollision(29, LayerMask.NameToLayer("piece"), false); Physics.IgnoreLayerCollision(29, LayerMask.NameToLayer("character"), true); Physics.IgnoreLayerCollision(29, LayerMask.NameToLayer("smoke"), true); Physics.IgnoreLayerCollision(29, LayerMask.NameToLayer("character_ghost"), true); Physics.IgnoreLayerCollision(29, LayerMask.NameToLayer("weapon"), true); Physics.IgnoreLayerCollision(29, LayerMask.NameToLayer("blocker"), true); Physics.IgnoreLayerCollision(29, LayerMask.NameToLayer("pathblocker"), true); Physics.IgnoreLayerCollision(29, LayerMask.NameToLayer("viewblock"), true); Physics.IgnoreLayerCollision(29, LayerMask.NameToLayer("character_net"), true); Physics.IgnoreLayerCollision(29, LayerMask.NameToLayer("character_noenv"), true); Physics.IgnoreLayerCollision(29, LayerMask.NameToLayer("Default_small"), false); Physics.IgnoreLayerCollision(29, LayerMask.NameToLayer("Default"), false); } private void LoadCustomTextures() { foreach (CustomTexture texture in CustomTextureGroup.Load("Sails").Textures) { texture.Texture.wrapMode = (TextureWrapMode)1; if (Object.op_Implicit((Object)(object)texture.Normal)) { texture.Normal.wrapMode = (TextureWrapMode)1; } } foreach (CustomTexture texture2 in CustomTextureGroup.Load("Patterns").Textures) { texture2.Texture.filterMode = (FilterMode)0; texture2.Texture.wrapMode = (TextureWrapMode)0; if (Object.op_Implicit((Object)(object)texture2.Normal)) { texture2.Normal.wrapMode = (TextureWrapMode)0; } } foreach (CustomTexture texture3 in CustomTextureGroup.Load("Logos").Textures) { texture3.Texture.wrapMode = (TextureWrapMode)1; if (Object.op_Implicit((Object)(object)texture3.Normal)) { texture3.Normal.wrapMode = (TextureWrapMode)1; } } } private void AddCustomItemsAndPieces() { PrefabRegistryController.InitAfterVanillaItemsAndPrefabsAreAvailable(); } } } namespace Properties { [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] internal sealed class SentryDSN : Attribute { public string Dsn { get; } public SentryDSN(string sentryDsn) { Dsn = sentryDsn; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { internal IgnoresAccessChecksToAttribute(string assemblyName) { } } }
plugins\ValheimVehicles.dll
Decompiled a week 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.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; 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 Advize_PlantEasily; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using ComfyGizmo; using Components; using DynamicLocations.API; using DynamicLocations.Constants; using DynamicLocations.Controllers; using DynamicLocations.Structs; using HarmonyLib; using JetBrains.Annotations; using Jotunn; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Extensions; using Jotunn.GUI; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using PlanBuild.Blueprints.Components; using PlanBuild.Plans; using Registry; using Splatform; using TMPro; using Unity.Collections; using Unity.Jobs; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.Experimental.Rendering; using UnityEngine.Rendering; using UnityEngine.Serialization; using UnityEngine.U2D; using UnityEngine.UI; using Valheim.UI; using ValheimVehicles.Attributes; using ValheimVehicles.Compat; using ValheimVehicles.Components; using ValheimVehicles.Config; using ValheimVehicles.ConsoleCommands; using ValheimVehicles.Constants; using ValheimVehicles.Controllers; using ValheimVehicles.Enums; using ValheimVehicles.GUI; using ValheimVehicles.Helpers; using ValheimVehicles.Injections; using ValheimVehicles.Interfaces; using ValheimVehicles.Patches; using ValheimVehicles.Prefabs; using ValheimVehicles.Prefabs.Registry; using ValheimVehicles.Prefabs.ValheimVehicles.Prefabs.Registry; using ValheimVehicles.Propulsion.Rudder; using ValheimVehicles.Propulsion.Sail; using ValheimVehicles.SharedScripts; using ValheimVehicles.SharedScripts.Validation; using ValheimVehicles.Storage.Serialization; using ValheimVehicles.Structs; using ValheimVehicles.UI; using ZdoWatcher; using Zolantris.Shared; using Zolantris.Shared.Debug; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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 Registry { public class ShipKeelPrefab : IRegisterPrefab { public static readonly ShipKeelPrefab Instance = new ShipKeelPrefab(); public void Register(PrefabManager prefabManager, PieceManager pieceManager) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected O, but got Unknown //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_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Expected O, but got Unknown //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Expected O, but got Unknown GameObject val = prefabManager.CreateClonedPrefab("ValheimVehicles_ShipKeel", LoadValheimVehicleAssets.ShipKeelAsset); PrefabRegistryHelpers.HoistSnapPointsToPrefab(val, val.transform); PrefabRegistryHelpers.AddNetViewWithPersistence(val); PrefabRegistryHelpers.SetWearNTear(val); PrefabRegistryHelpers.AddPieceForPrefab("ValheimVehicles_ShipKeel", val); PrefabRegistryHelpers.PieceData valueSafe = GeneralExtensions.GetValueSafe<string, PrefabRegistryHelpers.PieceData>(PrefabRegistryHelpers.PieceDataDictionary, "ValheimVehicles_ShipKeel"); PieceConfig val2 = new PieceConfig(); val2.PieceTable = PrefabRegistryController.GetPieceTableName(); val2.Description = valueSafe.Description; val2.Icon = LoadValheimVehicleAssets.VehicleSprites.GetSprite("keel"); val2.Category = PrefabRegistryController.SetCategoryName("Structure"); val2.Enabled = true; val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Amount = 10, Item = "Wood", Recover = true } }; pieceManager.AddPiece(new CustomPiece(val, false, val2)); } } public class VehiclePiecesPrefab : IRegisterPrefab { public static readonly VehiclePiecesPrefab Instance = new VehiclePiecesPrefab(); public static GameObject VehiclePiecesContainer = null; public void RegisterPiecesContainer(PrefabManager prefabManager) { VehiclePiecesContainer = prefabManager.CreateClonedPrefab("ValheimVehicles_piecesContainer", LoadValheimVehicleAssets.VehiclePiecesAsset); } public void Register(PrefabManager prefabManager, PieceManager pieceManager) { RegisterPiecesContainer(prefabManager); } } } namespace Components { public class CustomToggleSwitch : MonoBehaviour, Interactable, Hoverable { public enum ToggleSwitchAction { CommandsHud, CreativeMode, ColliderEditMode } public ToggleSwitchAction mToggleSwitchType = ToggleSwitchAction.CreativeMode; private ZNetView netView; public void Awake() { netView = ((Component)this).GetComponent<ZNetView>(); } public void Start() { SyncSwitchMode(); } public void OnEnable() { netView.Register("RPC_UpdateSwitch", (Action<long>)RPC_UpdateSwitch); } public void OnDisable() { netView.Unregister("RPC_UpdateSwitch"); } public void RPC_UpdateSwitch(long sender) { SyncSwitchMode(); } public void UpdateSwitch() { netView.m_zdo.Set(VehicleZdoVars.ToggleSwitchAction, mToggleSwitchType.ToString()); netView.InvokeRPC(ZRoutedRpc.Everybody, "RPC_UpdateSwitch", Array.Empty<object>()); } public ToggleSwitchAction GetActivationActionFromString(string activationActionString) { if (!Enum.TryParse<ToggleSwitchAction>(activationActionString, out var result)) { return ToggleSwitchAction.CommandsHud; } return result; } public void SyncSwitchMode() { if (Object.op_Implicit((Object)(object)netView) && netView.GetZDO() != null && ((Behaviour)this).isActiveAndEnabled) { string @string = netView.GetZDO().GetString(VehicleZdoVars.ToggleSwitchAction, "CreativeMode"); mToggleSwitchType = GetActivationActionFromString(@string); } } private void HandleToggleCreativeMode() { VehicleCommands.ToggleCreativeMode(); } private void HandleToggleCommandsHud() { VehicleCommands.ToggleVehicleCommandsHud(); } public void OnPressHandler(CustomToggleSwitch toggleSwitch, Humanoid humanoid) { switch (mToggleSwitchType) { case ToggleSwitchAction.CommandsHud: HandleToggleCommandsHud(); break; case ToggleSwitchAction.CreativeMode: HandleToggleCreativeMode(); break; case ToggleSwitchAction.ColliderEditMode: VehicleCommands.ToggleColliderEditMode(); break; default: throw new ArgumentOutOfRangeException(); } } public ToggleSwitchAction GetNextAction() { return mToggleSwitchType switch { ToggleSwitchAction.CommandsHud => ToggleSwitchAction.CreativeMode, ToggleSwitchAction.CreativeMode => ToggleSwitchAction.ColliderEditMode, ToggleSwitchAction.ColliderEditMode => ToggleSwitchAction.CommandsHud, _ => throw new ArgumentOutOfRangeException(), }; } public void SwapHandlerToNextAction() { mToggleSwitchType = GetNextAction(); } public void OnAltPressHandler() { SwapHandlerToNextAction(); UpdateSwitch(); } public bool Interact(Humanoid character, bool hold, bool alt) { if (hold) { return false; } if (!alt) { OnPressHandler(this, character); } else { OnAltPressHandler(); } return true; } public string GetLocalizedActionText(ToggleSwitchAction action) { return action switch { ToggleSwitchAction.CommandsHud => ModTranslations.ToggleSwitch_CommandsHudText, ToggleSwitchAction.CreativeMode => ModTranslations.CreativeMode, ToggleSwitchAction.ColliderEditMode => ModTranslations.ToggleSwitch_MaskColliderEditMode, _ => throw new ArgumentOutOfRangeException("action", action, null), }; } public bool UseItem(Humanoid user, ItemData item) { return false; } public string GetHoverName() { return ModTranslations.ToggleSwitch_SwitchName; } public string GetHoverText() { return ModTranslations.ToggleSwitch_CurrentActionString + " " + GetLocalizedActionText(mToggleSwitchType) + "\n" + ModTranslations.ToggleSwitch_NextActionString + " " + GetLocalizedActionText(GetNextAction()); } } public class LeverComponent { } } namespace ValheimVehicles { public class ValheimVehiclesPlugin : MonoBehaviour { public const string Author = "zolantris"; public const string Version = "1.0.0"; internal const string ModName = "ValheimVehicles"; public const string Guid = "zolantris.ValheimVehicles"; public static bool HasRunSetup; private static bool HasCreatedConfig; private RetryGuard _languageRetry; private MapPinSync _mapPinSync; public static ValheimVehiclesPlugin Instance { get; private set; } private void Awake() { Instance = this; _languageRetry = new RetryGuard((MonoBehaviour)(object)Instance); } private IEnumerator Start() { DebugSafeTimer timer = DebugSafeTimer.StartNew(); while (timer.ElapsedMilliseconds < 10000f && !ModTranslations.CanRunLocalization()) { yield return null; } Localization.OnLanguageChange = (Action)Delegate.Combine(Localization.OnLanguageChange, new Action(OnLanguageChanged)); yield return null; OnLanguageChanged(); } private void OnEnable() { Setup(); } private void OnDisable() { HasRunSetup = false; if ((Object)(object)_mapPinSync != (Object)null) { Object.Destroy((Object)(object)_mapPinSync); } if (Localization.instance != null) { Localization.OnLanguageChange = (Action)Delegate.Remove(Localization.OnLanguageChange, new Action(OnLanguageChanged)); } } public void Setup() { if (!HasRunSetup) { SetupComponents(); HasRunSetup = true; } } private void SetupComponents() { _mapPinSync = ((Component)this).gameObject.AddComponent<MapPinSync>(); } private void OnLanguageChanged() { ModTranslations.UpdateTranslations(); if (!ModTranslations.IsHealthy()) { _languageRetry.Retry(ModTranslations.UpdateTranslations, 1f); } else { _languageRetry.Reset(); } } [UsedImplicitly] public static void CreateConfigFromRAFTConfig(ConfigFile config) { if (!HasCreatedConfig) { BepInExBaseConfig<PatchConfig>.BindConfig(config); BepInExBaseConfig<RamConfig>.BindConfig(config); BepInExBaseConfig<PrefabConfig>.BindConfig(config); BepInExBaseConfig<VehicleDebugConfig>.BindConfig(config); BepInExBaseConfig<PropulsionConfig>.BindConfig(config); BepInExBaseConfig<ModSupportConfig>.BindConfig(config); BepInExBaseConfig<CustomMeshConfig>.BindConfig(config); BepInExBaseConfig<WaterConfig>.BindConfig(config); BepInExBaseConfig<PhysicsConfig>.BindConfig(config); BepInExBaseConfig<MinimapConfig>.BindConfig(config); BepInExBaseConfig<HudConfig>.BindConfig(config); BepInExBaseConfig<CameraConfig>.BindConfig(config); BepInExBaseConfig<RenderingConfig>.BindConfig(config); BepInExBaseConfig<VehicleGlobalConfig>.BindConfig(config); HasCreatedConfig = true; } } } } namespace ValheimVehicles.UI { public class EditRampComponent { private BoardingRampComponent m_ramp; private GameObject m_editPanel; private InputField m_segmentsInput; private int m_segmentCount; public void ShowPanel(BoardingRampComponent boardingRamp) { m_ramp = boardingRamp; if (!Object.op_Implicit((Object)(object)m_editPanel)) { InitPanel(); } m_segmentCount = boardingRamp.m_segments; m_segmentsInput.SetTextWithoutNotify(boardingRamp.m_segments.ToString()); GUIManager.BlockInput(true); m_editPanel.SetActive(true); } private void InitPanel() { //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Expected O, but got Unknown //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Expected O, but got Unknown Transform transform = GUIManager.CustomGUIFront.transform; m_editPanel = Object.Instantiate<GameObject>(PrefabRegistryController.vehicleAssetBundle.LoadAsset<GameObject>("edit_ramp_panel"), transform, false); PanelUtil.ApplyPanelStyle(m_editPanel); m_segmentsInput = ((Component)m_editPanel.transform.Find("SegmentsInput")).GetComponent<InputField>(); Button component = ((Component)m_editPanel.transform.Find("SaveButton")).GetComponent<Button>(); Button component2 = ((Component)m_editPanel.transform.Find("CancelButton")).GetComponent<Button>(); ((UnityEvent)component.onClick).AddListener(new UnityAction(SaveEditPanel)); ((UnityEvent)component2.onClick).AddListener(new UnityAction(CancelEditPanel)); ((UnityEvent<string>)(object)m_segmentsInput.onValueChanged).AddListener((UnityAction<string>)delegate(string val) { int.TryParse(val, out m_segmentCount); m_segmentCount = Mathf.Clamp(m_segmentCount, 2, 32); }); } private void ClosePanel() { GUIManager.BlockInput(false); m_editPanel.SetActive(false); } private void CancelEditPanel() { ClosePanel(); } private void SaveEditPanel() { if ((Object)(object)m_ramp != (Object)null) { m_ramp.SetSegmentCount(m_segmentCount); } ClosePanel(); } } public class EditSailComponentPanel { private GameObject m_editPanel; private GameObject m_editSailPanel; private GameObject m_editPatternPanel; private GameObject m_editLogoPanel; private SailComponent m_editSail; private Toggle[] m_editLockedSailSides; private Toggle[] m_editLockedSailCorners; private Toggle m_sailShrinkingToggle; private GameObject m_locksTri; private GameObject m_locksQuad; private Toggle m_disableClothToggle; public void ShowPanel(SailComponent sailComponent) { m_editSail = sailComponent; m_editSail.StartEdit(); bool flag = m_editSail.m_sailCorners.Count == 3; if (!Object.op_Implicit((Object)(object)m_editPanel)) { InitPanel(); } GameObject val = (flag ? m_locksTri : m_locksQuad); m_editLockedSailCorners = (Toggle[])(object)new Toggle[flag ? 3 : 4]; m_editLockedSailSides = (Toggle[])(object)new Toggle[flag ? 3 : 4]; m_locksTri.SetActive(flag); m_locksQuad.SetActive(!flag); m_editLockedSailCorners[0] = ((Component)val.transform.Find("CornerA")).GetComponent<Toggle>(); m_editLockedSailCorners[1] = ((Component)val.transform.Find("CornerB")).GetComponent<Toggle>(); m_editLockedSailCorners[2] = ((Component)val.transform.Find("CornerC")).GetComponent<Toggle>(); if (!flag) { m_editLockedSailCorners[3] = ((Component)val.transform.Find("CornerD")).GetComponent<Toggle>(); } m_editLockedSailSides[0] = ((Component)val.transform.Find("SideA")).GetComponent<Toggle>(); m_editLockedSailSides[1] = ((Component)val.transform.Find("SideB")).GetComponent<Toggle>(); m_editLockedSailSides[2] = ((Component)val.transform.Find("SideC")).GetComponent<Toggle>(); if (!flag) { m_editLockedSailSides[3] = ((Component)val.transform.Find("SideD")).GetComponent<Toggle>(); } for (int i = 0; i < m_editLockedSailCorners.Length; i++) { m_editLockedSailCorners[i].SetIsOnWithoutNotify(m_editSail.m_lockedSailCorners.HasFlag((SailComponent.SailLockedSide)(1 << i))); m_editLockedSailSides[i].SetIsOnWithoutNotify(m_editSail.m_lockedSailSides.HasFlag((SailComponent.SailLockedSide)(1 << i))); } m_sailShrinkingToggle.SetIsOnWithoutNotify(m_editSail.m_sailFlags.HasFlag(SailComponent.SailFlags.AllowSailShrinking)); m_disableClothToggle.SetIsOnWithoutNotify(m_editSail.m_sailFlags.HasFlag(SailComponent.SailFlags.DisableCloth)); GUIManager.BlockInput(true); m_editPanel.SetActive(true); } private void InitPanel() { //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Expected O, but got Unknown //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Expected O, but got Unknown //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Expected O, but got Unknown //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Expected O, but got Unknown //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Expected O, but got Unknown //IL_0328: Unknown result type (might be due to invalid IL or missing references) //IL_0332: Expected O, but got Unknown //IL_033f: Unknown result type (might be due to invalid IL or missing references) //IL_0349: Expected O, but got Unknown //IL_0355: Unknown result type (might be due to invalid IL or missing references) //IL_035f: Expected O, but got Unknown Transform transform = GUIManager.CustomGUIFront.transform; m_editPanel = Object.Instantiate<GameObject>(LoadValheimRaftAssets.editPanel, transform, false); PanelUtil.ApplyPanelStyle(m_editPanel); GameObject editTexturePanel = LoadValheimRaftAssets.editTexturePanel; PanelUtil.ApplyPanelStyle(editTexturePanel); GUIManager.Instance.ApplyDropdownStyle(((Component)editTexturePanel.transform.Find("TextureName")).GetComponent<Dropdown>(), 15); m_editSailPanel = Object.Instantiate<GameObject>(editTexturePanel, transform, false); m_editPatternPanel = Object.Instantiate<GameObject>(editTexturePanel, transform, false); m_editLogoPanel = Object.Instantiate<GameObject>(editTexturePanel, transform, false); m_editSailPanel.SetActive(false); m_editPatternPanel.SetActive(false); m_editLogoPanel.SetActive(false); ((UnityEvent)((Component)m_editSailPanel.transform.Find("Button")).GetComponent<Button>().onClick).AddListener((UnityAction)delegate { m_editSailPanel.SetActive(false); m_editPanel.SetActive(true); }); ((UnityEvent)((Component)m_editPatternPanel.transform.Find("Button")).GetComponent<Button>().onClick).AddListener((UnityAction)delegate { m_editPatternPanel.SetActive(false); m_editPanel.SetActive(true); }); ((UnityEvent)((Component)m_editLogoPanel.transform.Find("Button")).GetComponent<Button>().onClick).AddListener((UnityAction)delegate { m_editLogoPanel.SetActive(false); m_editPanel.SetActive(true); }); GameObject gameObject = ((Component)m_editPanel.transform.Find("SaveButton")).gameObject; ((UnityEvent)((Component)m_editPanel.transform.Find("CancelButton")).gameObject.GetComponent<Button>().onClick).AddListener(new UnityAction(CancelEditPanel)); ((UnityEvent)gameObject.GetComponent<Button>().onClick).AddListener(new UnityAction(SaveEditPanel)); m_sailShrinkingToggle = ((Component)m_editPanel.transform.Find("SailShrinkingToggle")).GetComponent<Toggle>(); ((UnityEvent<bool>)(object)m_sailShrinkingToggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool b) { m_editSail.SetSailMastSetting(SailComponent.SailFlags.AllowSailShrinking, b); }); m_disableClothToggle = ((Component)m_editPanel.transform.Find("SailClothToggle")).GetComponent<Toggle>(); ((UnityEvent<bool>)(object)m_disableClothToggle.onValueChanged).AddListener((UnityAction<bool>)delegate(bool b) { m_editSail.SetSailMastSetting(SailComponent.SailFlags.DisableCloth, b); }); m_locksTri = ((Component)m_editPanel.transform.Find("LocksTri")).gameObject; m_locksQuad = ((Component)m_editPanel.transform.Find("LocksQuad")).gameObject; Toggle[] componentsInChildren = m_locksTri.GetComponentsInChildren<Toggle>(); for (int i = 0; i < componentsInChildren.Length; i++) { ((UnityEvent<bool>)(object)componentsInChildren[i].onValueChanged).AddListener((UnityAction<bool>)delegate { UpdateSails(); }); } componentsInChildren = m_locksQuad.GetComponentsInChildren<Toggle>(); for (int i = 0; i < componentsInChildren.Length; i++) { ((UnityEvent<bool>)(object)componentsInChildren[i].onValueChanged).AddListener((UnityAction<bool>)delegate { UpdateSails(); }); } Button component = ((Component)m_editPanel.transform.Find("EditSailButton")).GetComponent<Button>(); Button component2 = ((Component)m_editPanel.transform.Find("EditPatternButton")).GetComponent<Button>(); Button component3 = ((Component)m_editPanel.transform.Find("EditLogoButton")).GetComponent<Button>(); ((UnityEvent)component.onClick).AddListener((UnityAction)delegate { m_editSailPanel.SetActive(true); m_editPatternPanel.SetActive(false); m_editLogoPanel.SetActive(false); m_editPanel.SetActive(false); LoadTexturePanel(m_editSailPanel, m_editSail.GetSailMaterial(), "_Main", CustomTextureGroup.Get("Sails")); }); ((UnityEvent)component2.onClick).AddListener((UnityAction)delegate { m_editSailPanel.SetActive(false); m_editPatternPanel.SetActive(true); m_editLogoPanel.SetActive(false); m_editPanel.SetActive(false); LoadTexturePanel(m_editPatternPanel, m_editSail.GetSailMaterial(), "_Pattern", CustomTextureGroup.Get("Patterns")); }); ((UnityEvent)component3.onClick).AddListener((UnityAction)delegate { m_editSailPanel.SetActive(false); m_editPatternPanel.SetActive(false); m_editLogoPanel.SetActive(true); m_editPanel.SetActive(false); LoadTexturePanel(m_editLogoPanel, m_editSail.GetSailMaterial(), "_Logo", CustomTextureGroup.Get("Logos")); }); } private void LoadTexturePanel(GameObject editPanel, Material mat, string parameterName, CustomTextureGroup group) { //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Expected O, but got Unknown //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Expected O, but got Unknown //IL_02af: Unknown result type (might be due to invalid IL or missing references) //IL_02cf: Unknown result type (might be due to invalid IL or missing references) //IL_02d4: Unknown result type (might be due to invalid IL or missing references) //IL_0311: Unknown result type (might be due to invalid IL or missing references) //IL_0316: Unknown result type (might be due to invalid IL or missing references) Material mat2 = mat; string parameterName2 = parameterName; CustomTextureGroup group2 = group; Button component = ((Component)editPanel.transform.Find("TextureColor")).GetComponent<Button>(); Dropdown component2 = ((Component)editPanel.transform.Find("TextureName")).GetComponent<Dropdown>(); InputField component3 = ((Component)editPanel.transform.Find("OffsetX")).GetComponent<InputField>(); InputField component4 = ((Component)editPanel.transform.Find("OffsetY")).GetComponent<InputField>(); InputField component5 = ((Component)editPanel.transform.Find("TilingX")).GetComponent<InputField>(); InputField component6 = ((Component)editPanel.transform.Find("TilingY")).GetComponent<InputField>(); InputField component7 = ((Component)editPanel.transform.Find("Rotation")).GetComponent<InputField>(); ((UnityEventBase)component.onClick).RemoveAllListeners(); ((UnityEventBase)component2.onValueChanged).RemoveAllListeners(); ((UnityEventBase)component3.onValueChanged).RemoveAllListeners(); ((UnityEventBase)component4.onValueChanged).RemoveAllListeners(); ((UnityEventBase)component5.onValueChanged).RemoveAllListeners(); ((UnityEventBase)component6.onValueChanged).RemoveAllListeners(); ((UnityEventBase)component7.onValueChanged).RemoveAllListeners(); List<OptionData> list = new List<OptionData>(); for (int i = 0; i < group2.Textures.Count; i++) { list.Add(new OptionData(((Object)group2.Textures[i].Texture).name)); } component2.options = list; ((UnityEvent<int>)(object)component2.onValueChanged).AddListener((UnityAction<int>)delegate(int index) { mat2.SetTexture(parameterName2 + "Tex", group2.Textures[index].Texture); if (Object.op_Implicit((Object)(object)group2.Textures[index].Normal)) { mat2.SetTexture(parameterName2 + "Normal", group2.Textures[index].Normal); } }); GUIManager.Instance.ApplyDropdownStyle(component2, 15); ((UnityEvent)component.onClick).AddListener((UnityAction)delegate { //IL_000f: 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_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown //IL_0070: Expected O, but got Unknown GUIManager.Instance.CreateColorPicker(new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), mat2.GetColor(parameterName2 + "Color"), "Color", (ColorEvent)delegate(Color color) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) mat2.SetColor(parameterName2 + "Color", color); }, (ColorEvent)delegate(Color color) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) mat2.SetColor(parameterName2 + "Color", color); }, true); }); ((UnityEvent<string>)(object)component3.onValueChanged).AddListener((UnityAction<string>)delegate(string str) { //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_0044: Unknown result type (might be due to invalid IL or missing references) if (float.TryParse(str, out var result5)) { Vector2 textureOffset3 = mat2.GetTextureOffset(parameterName2 + "Tex"); textureOffset3.x = result5; mat2.SetTextureOffset(parameterName2 + "Tex", textureOffset3); } }); ((UnityEvent<string>)(object)component4.onValueChanged).AddListener((UnityAction<string>)delegate(string str) { //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_0044: Unknown result type (might be due to invalid IL or missing references) if (float.TryParse(str, out var result4)) { Vector2 textureOffset2 = mat2.GetTextureOffset(parameterName2 + "Tex"); textureOffset2.y = result4; mat2.SetTextureOffset(parameterName2 + "Tex", textureOffset2); } }); ((UnityEvent<string>)(object)component5.onValueChanged).AddListener((UnityAction<string>)delegate(string str) { //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_0044: Unknown result type (might be due to invalid IL or missing references) if (float.TryParse(str, out var result3)) { Vector2 textureScale3 = mat2.GetTextureScale(parameterName2 + "Tex"); textureScale3.x = result3; mat2.SetTextureScale(parameterName2 + "Tex", textureScale3); } }); ((UnityEvent<string>)(object)component6.onValueChanged).AddListener((UnityAction<string>)delegate(string str) { //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_0044: Unknown result type (might be due to invalid IL or missing references) if (float.TryParse(str, out var result2)) { Vector2 textureScale2 = mat2.GetTextureScale(parameterName2 + "Tex"); textureScale2.y = result2; mat2.SetTextureScale(parameterName2 + "Tex", textureScale2); } }); string text = parameterName2 + "Rotation"; if (mat2.HasProperty(text)) { ((Component)component7).gameObject.SetActive(true); ((UnityEvent<string>)(object)component7.onValueChanged).AddListener((UnityAction<string>)delegate(string str) { if (float.TryParse(str, out var result)) { mat2.SetFloat(parameterName2 + "Rotation", result); } }); } else { ((Component)component7).gameObject.SetActive(false); } Texture texture = mat2.GetTexture(parameterName2 + "Tex"); CustomTexture textureByHash = group2.GetTextureByHash(StringExtensionMethods.GetStableHashCode(((Object)texture).name)); if (textureByHash != null) { component2.SetValueWithoutNotify(textureByHash.Index); } UpdateColorButton(component, mat2.GetColor(parameterName2 + "Color")); Vector2 textureOffset = mat2.GetTextureOffset(parameterName2 + "Tex"); component3.SetTextWithoutNotify(textureOffset.x.ToString()); component4.SetTextWithoutNotify(textureOffset.y.ToString()); Vector2 textureScale = mat2.GetTextureScale(parameterName2 + "Tex"); component5.SetTextWithoutNotify(textureScale.x.ToString()); component6.SetTextWithoutNotify(textureScale.y.ToString()); if (((Component)component7).gameObject.activeSelf) { component7.SetTextWithoutNotify(mat2.GetFloat(parameterName2 + "Rotation").ToString()); } } private void UpdateColorButton(Button button, Color color) { //IL_000f: 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_001f: 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_003b: 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_0055: Unknown result type (might be due to invalid IL or missing references) color.a = 1f; ColorBlock colors = default(ColorBlock); ((ColorBlock)(ref colors)).normalColor = color; ((ColorBlock)(ref colors)).highlightedColor = color; ((ColorBlock)(ref colors)).disabledColor = color; ((ColorBlock)(ref colors)).fadeDuration = 0.1f; ((ColorBlock)(ref colors)).pressedColor = color; ((ColorBlock)(ref colors)).selectedColor = color; ((ColorBlock)(ref colors)).colorMultiplier = 1f; ((Selectable)button).colors = colors; } private void UpdateSails() { if (Object.op_Implicit((Object)(object)m_editSail)) { m_editSail.m_lockedSailCorners = SailComponent.SailLockedSide.None; for (int i = 0; i < m_editLockedSailCorners.Length; i++) { m_editSail.m_lockedSailCorners |= (SailComponent.SailLockedSide)(m_editLockedSailCorners[i].isOn ? (1 << i) : 0); } m_editSail.m_lockedSailSides = SailComponent.SailLockedSide.None; for (int j = 0; j < m_editLockedSailSides.Length; j++) { m_editSail.m_lockedSailSides |= (SailComponent.SailLockedSide)(m_editLockedSailSides[j].isOn ? (1 << j) : 0); } m_editSail.UpdateCoefficients(); } } private void CloseEditPanel() { if (Object.op_Implicit((Object)(object)m_editPanel)) { m_editPanel.SetActive(false); } if (Object.op_Implicit((Object)(object)m_editSail)) { m_editSail.EndEdit(); } m_editSail = null; GUIManager.BlockInput(false); } private void CancelEditPanel() { if (Object.op_Implicit((Object)(object)m_editSail)) { m_editSail.LoadZDO(); } CloseEditPanel(); } private void SaveEditPanel() { if (Object.op_Implicit((Object)(object)m_editSail)) { m_editSail.LoadFromMaterial(); m_editSail.SaveZdo(); m_editSail.LoadZDO(); } CloseEditPanel(); } } public class PanelUtil { public static void ApplyPanelStyle(GameObject editPanel) { //IL_00de: Unknown result type (might be due to invalid IL or missing references) Array.ForEach(editPanel.GetComponentsInChildren<Button>(true), delegate(Button b) { if (((Object)b).name.EndsWith("Button")) { GUIManager.Instance.ApplyButtonStyle(b, 16); } }); Array.ForEach(editPanel.GetComponentsInChildren<InputField>(true), delegate(InputField b) { GUIManager.Instance.ApplyInputFieldStyle(b, 16); }); Array.ForEach(editPanel.GetComponentsInChildren<Text>(true), delegate(Text b) { b.text = Localization.instance.Localize(b.text); if (((Object)b).name.EndsWith("Label")) { GUIManager.Instance.ApplyTextStyle(b, 16); } }); Array.ForEach(editPanel.GetComponentsInChildren<Toggle>(true), delegate(Toggle b) { Logger.LogInfo((object)("PANEL_UTIL CHILD " + ((Object)b).name)); if (((Object)b).name.EndsWith("Toggle")) { GUIManager.Instance.ApplyToogleStyle(b); } }); Image component = editPanel.GetComponent<Image>(); component.sprite = GUIManager.Instance.GetSprite("woodpanel_trophys"); component.type = (Type)1; ((Graphic)component).material = Cache.GetPrefab<Material>("litpanel"); ((Graphic)component).color = Color.white; } } } namespace ValheimVehicles.GUI { public static class DropdownHelpers { public static void SetupOptionsAndSelectFirst(TMP_Dropdown dropdown, List<OptionData> options) { if ((Object)(object)dropdown == (Object)null || options == null || options.Count == 0) { LoggerProvider.LogWarning("[DropdownHelpers] Dropdown or options list is null/empty. Cannot setup options.", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\ValheimVehicles\\ValheimVehicles.UI\\DropdownHelpers.cs", 15); return; } dropdown.ClearOptions(); dropdown.AddOptions(options); dropdown.RefreshShownValue(); dropdown.value = 0; dropdown.captionText.text = options[0].text; } } public class DropdownRefreshOnHover : MonoBehaviour, IPointerEnterHandler, IEventSystemHandler { private TMP_Dropdown dropdown; public Action<TMP_Dropdown>? OnPointerEnterAction; private void Awake() { dropdown = ((Component)this).GetComponent<TMP_Dropdown>(); } public void OnPointerEnter(PointerEventData eventData) { OnPointerEnterAction?.Invoke(dropdown); } } public static class TMPDropdownFactory { public static Color BackgroundElementColor = new Color(0.2f, 0.2f, 0.2f, 1f); public static TMP_Dropdown CreateTMPDropDown(Transform parent, Vector2 anchoredPosition, Vector2 size, string captionText = "", string itemPrototypeText = "Option") { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown //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_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_00a1: 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_00b3: 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_00dc: 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_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) //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_01b0: 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_020d: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Expected O, but got Unknown //IL_023e: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_02e5: Unknown result type (might be due to invalid IL or missing references) //IL_02ec: Expected O, but got Unknown //IL_0314: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Unknown result type (might be due to invalid IL or missing references) //IL_0340: Unknown result type (might be due to invalid IL or missing references) //IL_034c: Unknown result type (might be due to invalid IL or missing references) //IL_0358: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: Unknown result type (might be due to invalid IL or missing references) //IL_03b1: Expected O, but got Unknown //IL_03da: 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_0406: Unknown result type (might be due to invalid IL or missing references) //IL_0412: 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_045a: Unknown result type (might be due to invalid IL or missing references) //IL_0464: Expected O, but got Unknown //IL_049f: Unknown result type (might be due to invalid IL or missing references) //IL_04a6: Expected O, but got Unknown //IL_04f2: Unknown result type (might be due to invalid IL or missing references) //IL_0538: Unknown result type (might be due to invalid IL or missing references) //IL_053d: Unknown result type (might be due to invalid IL or missing references) //IL_0550: 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) //IL_0562: Unknown result type (might be due to invalid IL or missing references) //IL_0577: Unknown result type (might be due to invalid IL or missing references) //IL_058b: Unknown result type (might be due to invalid IL or missing references) //IL_05d9: Unknown result type (might be due to invalid IL or missing references) //IL_0622: Unknown result type (might be due to invalid IL or missing references) //IL_062e: Unknown result type (might be due to invalid IL or missing references) //IL_063a: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("VehicleGUI_TMP_Dropdown", new Type[4] { typeof(RectTransform), typeof(CanvasRenderer), typeof(Image), typeof(TMP_Dropdown) }); val.transform.SetParent(parent, false); RectTransform component = val.GetComponent<RectTransform>(); component.sizeDelta = size; component.anchoredPosition = anchoredPosition; GameObject val2 = new GameObject("Label", new Type[2] { typeof(RectTransform), typeof(TextMeshProUGUI) }); val2.transform.SetParent(val.transform, false); RectTransform component2 = val2.GetComponent<RectTransform>(); component2.anchorMin = Vector2.zero; component2.anchorMax = Vector2.one; component2.offsetMin = new Vector2(10f, 6f); component2.offsetMax = new Vector2(-25f, -7f); TextMeshProUGUI component3 = val2.GetComponent<TextMeshProUGUI>(); ((TMP_Text)component3).font = TMP_Settings.defaultFontAsset; ((TMP_Text)component3).text = captionText ?? ""; ((TMP_Text)component3).alignment = (TextAlignmentOptions)4097; ((TMP_Text)component3).fontSize = 24f; ((Graphic)component3).color = GUIManager.Instance.ValheimOrange; GameObject val3 = new GameObject("Arrow", new Type[3] { typeof(RectTransform), typeof(CanvasRenderer), typeof(Image) }); val3.transform.SetParent(val.transform, false); RectTransform component4 = val3.GetComponent<RectTransform>(); component4.anchorMin = new Vector2(1f, 0.5f); component4.anchorMax = new Vector2(1f, 0.5f); component4.sizeDelta = new Vector2(20f, 20f); component4.anchoredPosition = new Vector2(-15f, 0f); GameObject val4 = new GameObject("Template", new Type[4] { typeof(RectTransform), typeof(CanvasRenderer), typeof(Image), typeof(ScrollRect) }); val4.transform.SetParent(val.transform, false); val4.SetActive(false); RectTransform component5 = val4.GetComponent<RectTransform>(); component5.pivot = new Vector2(0.5f, 1f); component5.anchorMin = new Vector2(0f, 0f); component5.anchorMax = new Vector2(1f, 0f); component5.sizeDelta = new Vector2(0f, 150f); Canvas obj = val4.AddComponent<Canvas>(); obj.overrideSorting = true; obj.sortingOrder = 300; ScrollRect component6 = val4.GetComponent<ScrollRect>(); GameObject val5 = new GameObject("Viewport", new Type[4] { typeof(RectTransform), typeof(CanvasRenderer), typeof(Image), typeof(Mask) }); val5.transform.SetParent(val4.transform, false); RectTransform component7 = val5.GetComponent<RectTransform>(); component7.pivot = new Vector2(0f, 1f); component7.anchorMin = new Vector2(0f, 0f); component7.anchorMax = new Vector2(1f, 1f); component7.offsetMin = Vector2.zero; component7.offsetMax = Vector2.zero; val5.GetComponent<Mask>().showMaskGraphic = false; component6.viewport = component7; GameObject val6 = new GameObject("Content", new Type[3] { typeof(RectTransform), typeof(VerticalLayoutGroup), typeof(ContentSizeFitter) }); val6.transform.SetParent(val5.transform, false); RectTransform component8 = val6.GetComponent<RectTransform>(); component8.pivot = new Vector2(0.5f, 1f); component8.anchorMin = new Vector2(0f, 0f); component8.anchorMax = new Vector2(1f, 1f); component8.offsetMin = Vector2.zero; component8.offsetMax = Vector2.zero; VerticalLayoutGroup component9 = val6.GetComponent<VerticalLayoutGroup>(); ((HorizontalOrVerticalLayoutGroup)component9).childForceExpandHeight = false; ((HorizontalOrVerticalLayoutGroup)component9).childControlHeight = true; ((HorizontalOrVerticalLayoutGroup)component9).childForceExpandWidth = true; ((HorizontalOrVerticalLayoutGroup)component9).childControlWidth = true; ((HorizontalOrVerticalLayoutGroup)component9).spacing = 5f; ((LayoutGroup)component9).padding = new RectOffset(5, 5, 5, 5); val6.GetComponent<ContentSizeFitter>().verticalFit = (FitMode)2; component6.content = component8; GameObject val7 = new GameObject("Item", new Type[2] { typeof(RectTransform), typeof(Toggle) }); LayoutElement obj2 = val7.AddComponent<LayoutElement>(); obj2.preferredHeight = 30f; obj2.minHeight = 30f; obj2.flexibleHeight = 0f; val7.transform.SetParent(val6.transform, false); val7.GetComponent<RectTransform>().sizeDelta = new Vector2(0f, 30f); Image val9 = (Image)(object)(((Selectable)val7.GetComponent<Toggle>()).targetGraphic = (Graphic)(object)val7.AddComponent<Image>()); GameObject val10 = new GameObject("Item Label", new Type[2] { typeof(RectTransform), typeof(TextMeshProUGUI) }); val10.transform.SetParent(val7.transform, false); RectTransform component10 = val10.GetComponent<RectTransform>(); component10.anchorMin = Vector2.zero; component10.anchorMax = Vector2.one; component10.offsetMin = new Vector2(10f, 0f); component10.offsetMax = new Vector2(-10f, 0f); TextMeshProUGUI component11 = val10.GetComponent<TextMeshProUGUI>(); ((TMP_Text)component11).font = TMP_Settings.defaultFontAsset; ((TMP_Text)component11).text = itemPrototypeText ?? "Option"; ((TMP_Text)component11).alignment = (TextAlignmentOptions)4097; ((TMP_Text)component11).fontSize = 22f; ((Graphic)component11).color = GUIManager.Instance.ValheimOrange; TMP_Dropdown component12 = val.GetComponent<TMP_Dropdown>(); component12.captionText = (TMP_Text)(object)component3; component12.template = component5; component12.itemText = (TMP_Text)(object)component11; ((Selectable)component12).targetGraphic = (Graphic)(object)val.GetComponent<Image>(); component6.content = component8; Image component13 = val.GetComponent<Image>(); Image component14 = val4.GetComponent<Image>(); ((Graphic)component13).color = BackgroundElementColor; ((Graphic)component14).color = BackgroundElementColor; ((Graphic)val9).color = BackgroundElementColor; return component12; } } } namespace ValheimVehicles.Structs { public struct GameCacheValue<TCachedResult, TParams> { internal TCachedResult? CachedValue; public string Name { get; set; } internal float IntervalInSeconds { get; set; } public bool IsCached { get; set; } private float _timer { get; set; } private Func<TParams, TCachedResult?> GetValueUncached { get; set; } public GameCacheValue(string name, float intervalInSeconds, Func<TParams, TCachedResult?> callback) { Name = name; IntervalInSeconds = intervalInSeconds; IsCached = false; _timer = 0f; CachedValue = default(TCachedResult); GetValueUncached = callback; } public TCachedResult? GetValue(TParams @params) { if (!IsCached) { return GetValueUncachedAndCache(@params); } return CachedValue; } public TCachedResult? GetValue(TParams @params, bool flushCache) { if (flushCache) { return GetValueUncachedAndCache(@params); } return GetValue(@params); } private TCachedResult? GetValueUncachedAndCache(TParams @params) { TCachedResult val = GetValueUncached(@params); SetCached(val); return val; } private void ResetCache() { IsCached = false; } public void SyncCache(float deltaSeconds) { _timer += deltaSeconds; if (_timer >= IntervalInSeconds) { ResetCache(); } } private void SetCached(TCachedResult? value) { CachedValue = value; IsCached = true; } } public struct ShipFloatation { public Vector3 ShipBack; public Vector3 ShipForward; public Vector3 ShipLeft; public Vector3 ShipRight; public bool IsAboveBuoyantLevel; public float BuoyancySpeedMultiplier; public bool IsInvalid; public float CurrentDepth; public float WaterLevelLeft; public float WaterLevelRight; public float WaterLevelForward; public float WaterLevelBack; public float LowestWaterHeight; public float GroundLevelLeft; public float GroundLevelRight; public float GroundLevelForward; public float GroundLevelBack; public float GroundLevelCenter; public float AverageWaterHeight; public float AverageGroundLevel; public float MaxWaterHeight; public float MaxGroundLevel; } public struct ActivationPieceData { private List<Rigidbody> frozenRigidbodies; public List<Rigidbody> rigidbodies; public ZNetView netView; public GameObject gameObject; public int vehicleId; public Vector3 localPosition; public ActivationPieceData(ZNetView netView, int vehicleId, Vector3 localPosition) { //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) this.netView = netView; this.vehicleId = vehicleId; this.localPosition = localPosition; rigidbodies = new List<Rigidbody>(); frozenRigidbodies = new List<Rigidbody>(); ((Component)netView).GetComponentsInChildren<Rigidbody>(true, rigidbodies); WearNTear component = ((Component)netView).GetComponent<WearNTear>(); if (Object.op_Implicit((Object)(object)component)) { ((Behaviour)component).enabled = false; } gameObject = ((Component)netView).gameObject; } public void UnFreezeRigidbodies() { if (rigidbodies.Count <= 0) { return; } foreach (Rigidbody frozenRigidbody in frozenRigidbodies) { if (!((Object)(object)frozenRigidbody == (Object)null)) { frozenRigidbody.isKinematic = false; } } frozenRigidbodies.Clear(); } public void FreezeRigidbodies() { if (rigidbodies.Count <= 0) { return; } foreach (Rigidbody rigidbody in rigidbodies) { if (!((Object)(object)rigidbody == (Object)null) && !rigidbody.isKinematic) { if (!frozenRigidbodies.Contains(rigidbody)) { frozenRigidbodies.Add(rigidbody); } rigidbody.isKinematic = true; } } } } public struct GenericInputAction { public string title; public bool IsAdminOnly; public Action OnButtonPress; public InputType inputType; public Action<TMP_Dropdown>? OnCreateDropdown; public UnityAction<int>? OnDropdownChanged; public Action<TMP_Dropdown>? OnPointerEnterAction; public GenericInputAction() { title = ""; IsAdminOnly = false; OnButtonPress = delegate { }; inputType = InputType.Button; OnCreateDropdown = null; OnDropdownChanged = null; OnPointerEnterAction = null; } } public enum InputType { Button, Input, Dropdown } public struct InputAction { public string title; public string description; public Action saveAction; public Action resetAction; } public static class VehicleZdoVars { public const string ZdoKeyBaseVehicleInitState = "ValheimVehicles_BaseVehicle_Initialized"; public const string VehicleFloatationHeight = "ValheimVehicles_VehicleFloatationHeight"; public const string VehicleFloatationCustomModeEnabled = "ValheimVehicles_VehicleFloatationCustomModeEnabled"; public static string ToggleSwitchAction = "ValheimVehicles_ToggleSwitchAction"; public static string CustomMeshId = "ValheimVehicles_CustomMesh"; public static string CustomMeshScale = "ValheimVehicles_CustomMeshSize"; public static string CustomMeshPrimitiveType = "ValheimVehicles_CustomMeshPrimitiveType"; public static string IsLandVehicle = "ValheimVehicles_IsLandVehicle"; public static readonly int MBCultivatableParentIdHash = StringExtensionMethods.GetStableHashCode("MBCultivatableParentId"); public static readonly KeyValuePair<int, int> MBCultivatableParentHash = ZDO.GetHashZDOID("MBCultivatableParent"); public static readonly int TempPieceParentId = StringExtensionMethods.GetStableHashCode("VehicleTempPieceParentId"); public static readonly int DEPRECATED_VehicleFlags = StringExtensionMethods.GetStableHashCode("VehicleFlags"); public static readonly string VehicleAnchorState = "VehicleAnchorState"; public static readonly int VehicleTargetHeight = StringExtensionMethods.GetStableHashCode("VehicleTargetHeight"); public static readonly int VehicleOceanSway = StringExtensionMethods.GetStableHashCode("VehicleOceanSway"); public static readonly int VehicleTreadWidth = StringExtensionMethods.GetStableHashCode("VehicleTreadWidth"); public static readonly KeyValuePair<int, int> MBParentHash = ZDO.GetHashZDOID("MBParent"); public static readonly int MBParentIdHash = StringExtensionMethods.GetStableHashCode("MBParentId"); public static readonly int MBPositionHash = StringExtensionMethods.GetStableHashCode("MBPosition"); public static readonly int MBRotationHash = StringExtensionMethods.GetStableHashCode("MBRotation"); public static readonly int MBRotationVecHash = StringExtensionMethods.GetStableHashCode("MBRotationVec"); public static readonly int MBPieceCount = StringExtensionMethods.GetStableHashCode("MBPieceCount"); public const string VehicleParentIdHash = "VehicleParentIdHash"; public const string VehicleParentId = "VehicleParentId"; } } namespace ValheimVehicles.Storage.Serialization { [Serializable] public struct SerializableVector3 { public float x; public float y; public float z; public SerializableVector3(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } public SerializableVector3(Vector3 v) { //IL_0001: 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_0019: Unknown result type (might be due to invalid IL or missing references) x = v.x; y = v.y; z = v.z; } public readonly Vector3 ToVector3() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) return new Vector3(x, y, z); } } [Serializable] public struct SerializableColor { public float r; public float g; public float b; public float a; public SerializableColor(float r, float g, float b, float a) { this.r = r; this.g = g; this.b = b; this.a = a; } public SerializableColor(Color color) { //IL_0001: 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_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) r = color.r; g = color.g; b = color.b; a = color.a; } public readonly Color ToColor() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) return new Color(r, g, b, a); } } [Serializable] public struct SerializableQuaternion { public float x; public float y; public float z; public float w; public SerializableQuaternion(float x, float y, float z, float w) { this.x = x; this.y = y; this.z = z; this.w = w; } public SerializableQuaternion(Quaternion q) { //IL_0001: 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_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) x = q.x; y = q.y; z = q.z; w = q.w; } public readonly Quaternion ToQuaternion() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) return new Quaternion(x, y, z, w); } } [Serializable] public struct SerializableVector2 { public float x; public float y; public SerializableVector2(float x, float y) { this.x = x; this.y = y; } public SerializableVector2(Vector2 v) { //IL_0001: 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) x = v.x; y = v.y; } public readonly Vector2 ToVector2() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) return new Vector2(x, y); } } [Serializable] public class StoredSailData { public List<SerializableVector3> SailCorners = new List<SerializableVector3>(); public int LockedSides; public int LockedCorners; public int MainHash; public SerializableVector2 MainScale; public SerializableVector2 MainOffset; public SerializableColor MainColor; public int PatternHash; public SerializableVector2 PatternScale; public SerializableVector2 PatternOffset; public SerializableColor PatternColor; public float PatternRotation; public int LogoHash; public SerializableVector2 LogoScale; public SerializableVector2 LogoOffset; public SerializableColor LogoColor; public float LogoRotation; public int SailFlags; } public static class StoredSailDataExtensions { public static StoredSailData LoadFromZDO(ZDO zdo, SailComponent sail) { //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_005b: 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_007c: 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_00b1: 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_00d2: 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_00dc: 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_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0158: 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_0174: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_0197: 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_0232: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_023e: Unknown result type (might be due to invalid IL or missing references) StoredSailData storedSailData = new StoredSailData { SailCorners = new List<SerializableVector3>(), LockedSides = zdo.GetInt(sail.m_lockedSailSidesHash, 0), LockedCorners = zdo.GetInt(sail.m_lockedSailCornersHash, 0), MainHash = zdo.GetInt(sail.m_mainHashRefHash, 0), MainScale = new SerializableVector2(Vector2.op_Implicit(zdo.GetVec3(sail.m_mainScaleHash, Vector3.zero))), MainOffset = new SerializableVector2(Vector2.op_Implicit(zdo.GetVec3(sail.m_mainOffsetHash, Vector3.zero))), MainColor = new SerializableColor(sail.GetColorFromByteStream(zdo.GetByteArray(sail.m_mainColorHash, (byte[])null))), PatternScale = new SerializableVector2(Vector2.op_Implicit(zdo.GetVec3(sail.m_patternScaleHash, Vector3.zero))), PatternOffset = new SerializableVector2(Vector2.op_Implicit(zdo.GetVec3(sail.m_patternOffsetHash, Vector3.zero))), PatternColor = new SerializableColor(sail.GetColorFromByteStream(zdo.GetByteArray(sail.m_patternColorHash, (byte[])null))), PatternHash = zdo.GetInt(sail.m_patternZDOHash, 0), PatternRotation = zdo.GetFloat(sail.m_patternRotationHash, 0f), LogoHash = zdo.GetInt(sail.m_logoZdoHash, 0), LogoScale = new SerializableVector2(Vector2.op_Implicit(zdo.GetVec3(sail.m_logoScaleHash, Vector3.zero))), LogoOffset = new SerializableVector2(Vector2.op_Implicit(zdo.GetVec3(sail.m_logoOffsetHash, Vector3.zero))), LogoColor = new SerializableColor(sail.GetColorFromByteStream(zdo.GetByteArray(sail.m_logoColorHash, (byte[])null))), LogoRotation = zdo.GetFloat(sail.m_logoRotationHash, 0f), SailFlags = zdo.GetInt(sail.m_sailFlagsHash, 0) }; int @int = zdo.GetInt(sail.m_sailCornersCountHash, 0); for (int i = 0; i < @int && i < 4; i++) { Vector3 vec = zdo.GetVec3(i switch { 0 => sail.m_sailCorner1Hash, 1 => sail.m_sailCorner2Hash, 2 => sail.m_sailCorner3Hash, 3 => sail.m_sailCorner4Hash, _ => 0, }, Vector3.zero); storedSailData.SailCorners.Add(new SerializableVector3(vec)); } return storedSailData; } public static void ApplyToZDO(this StoredSailData data, ZDO zdo, SailComponent sail) { //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_00f7: 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_0114: 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_0135: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: 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_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_01d9: 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_01f6: 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_0079: Unknown result type (might be due to invalid IL or missing references) zdo.Set(sail.m_sailCornersCountHash, data.SailCorners.Count, false); for (int i = 0; i < data.SailCorners.Count && i < 4; i++) { Vector3 val = data.SailCorners[i].ToVector3(); zdo.Set(i switch { 0 => sail.m_sailCorner1Hash, 1 => sail.m_sailCorner2Hash, 2 => sail.m_sailCorner3Hash, 3 => sail.m_sailCorner4Hash, _ => 0, }, val); } zdo.Set(sail.m_lockedSailSidesHash, data.LockedSides, false); zdo.Set(sail.m_lockedSailCornersHash, data.LockedCorners, false); zdo.Set(sail.m_mainHashRefHash, data.MainHash, false); zdo.Set(sail.m_mainScaleHash, Vector2.op_Implicit(data.MainScale.ToVector2())); zdo.Set(sail.m_mainOffsetHash, Vector2.op_Implicit(data.MainOffset.ToVector2())); zdo.Set(sail.m_mainColorHash, sail.ConvertColorToByteStream(data.MainColor.ToColor())); zdo.Set(sail.m_patternScaleHash, Vector2.op_Implicit(data.PatternScale.ToVector2())); zdo.Set(sail.m_patternOffsetHash, Vector2.op_Implicit(data.PatternOffset.ToVector2())); zdo.Set(sail.m_patternColorHash, sail.ConvertColorToByteStream(data.PatternColor.ToColor())); zdo.Set(sail.m_patternZDOHash, data.PatternHash, false); zdo.Set(sail.m_patternRotationHash, data.PatternRotation); zdo.Set(sail.m_logoZdoHash, data.LogoHash, false); zdo.Set(sail.m_logoScaleHash, Vector2.op_Implicit(data.LogoScale.ToVector2())); zdo.Set(sail.m_logoOffsetHash, Vector2.op_Implicit(data.LogoOffset.ToVector2())); zdo.Set(sail.m_logoColorHash, sail.ConvertColorToByteStream(data.LogoColor.ToColor())); zdo.Set(sail.m_logoRotationHash, data.LogoRotation); zdo.Set(sail.m_sailFlagsHash, data.SailFlags, false); zdo.Set(sail.HasInitialized, true); } } } namespace ValheimVehicles.Providers { public static class ProviderInitializers { public static void InitProviders(ManualLogSource Logger, GameObject gameObject) { new WearNTearIntegrationProvider().Init(); LoggerProvider.Setup(Logger); } } public class WearNTearIntegrationProvider : IInitProvider { private class WearNTearAdapter : IWearNTearStub { private readonly WearNTear _wearNTear; public Action m_onDestroyed { get; set; } public GameObject? m_new { get; set; } public GameObject? m_worn { get; set; } public GameObject? m_broken { get; set; } public GameObject? m_wet { get; set; } public WearNTearAdapter(WearNTear component) { _wearNTear = component; m_onDestroyed = component.m_onDestroyed; m_new = component.m_new; m_worn = component.m_worn; m_broken = component.m_broken; m_wet = component.m_wet; } } private static IWearNTearStub? ResolveWearNTear(GameObject? obj) { if ((Object)(object)obj == (Object)null) { return null; } WearNTear component = obj.GetComponent<WearNTear>(); if (!((Object)(object)component == (Object)null)) { return new WearNTearAdapter(component); } return null; } public void Init() { WearNTearProviderBase.GetWearNTearComponent = ResolveWearNTear; } } } namespace ValheimVehicles.Propulsion.Sail { public static class SailAreaForce { public static readonly float Tier1 = 5f; public static readonly float Tier2 = 10f; public static readonly float Tier3 = 20f; public static readonly float Tier4 = 40f; public static readonly float CustomTier1AreaForceMultiplier = 0.5f; public static readonly bool HasPropulsionConfigOverride = false; } } namespace ValheimVehicles.Propulsion.Rudder { public class SteeringWheelComponent : MonoBehaviour, Hoverable, Interactable, IDoodadController { private VehicleMovementController _controls; public IVehicleShip ShipInstance; public Transform? wheelTransform; private Vector3 wheelLocalOffset; public List<Transform> m_spokes = new List<Transform>(); public Vector3 m_leftHandPosition = new Vector3(-0.5f, 0f, 0f); public Vector3 m_rightHandPosition = new Vector3(0.5f, 0f, 0f); public float m_holdWheelTime = 0.7f; public float m_wheelRotationFactor = 4f; public float m_handIKSpeed = 0.2f; private float m_movingLeftAlpha; private float m_movingRightAlpha; private Transform? m_currentLeftHand; private Transform? m_currentRightHand; private Transform? m_targetLeftHand; private Transform? m_targetRightHand; private const float maxUseRange = 10f; public Transform steeringWheelHoverTransform; public HoverFadeText steeringWheelHoverText; public string _cachedLocalizedWheelHoverText = ""; public const string AnchorUseMessage = "[<color=red><b>$valheim_vehicles_wheel_use_anchored</b></color>]"; private long? _currentOwner; private string? _currentPlayerName; private AnchorState lastAnchorState; public VehicleMovementController? Controls => _controls; public string m_hoverText { get; set; } public Transform AttachPoint { get; set; } public static string GetAnchorHotkeyString() { return ZInput.instance.GetBoundKeyString("Run", false); } public static string GetAnchorMessage(bool isAnchored, string anchorKeyString) { string text = (isAnchored ? "[<color=red><b>$valheim_vehicles_wheel_use_anchored</b></color>]" : ""); string text2 = (isAnchored ? "$valheim_vehicles_wheel_use_anchor_disable_detail" : "$valheim_vehicles_wheel_use_anchor_enable_detail"); return text + "\n[<color=yellow><b>" + anchorKeyString + "</b></color>] <color=white>" + text2 + "</color>"; } public static string GetHoverTextFromShip(float sailArea, float totalMass, float shipMass, float shipPropulsion, bool isAnchored, string anchorKeyString) { string text = ""; if (PropulsionConfig.ShowShipStats.Value) { float value = PropulsionConfig.SailingMassPercentageFactor.Value; text += $"\nsailArea: {sailArea}"; text += $"\ntotalMass: {totalMass}"; text += $"\nshipMass(no-containers): {shipMass}"; text += $"\ntotalMassToPush: {value}% * {totalMass} = {totalMass * value / 100f}"; text += $"\nshipPropulsion: {shipPropulsion}"; text = "<color=white>" + text + "</color>"; } string anchorMessage = GetAnchorMessage(isAnchored, anchorKeyString); return Localization.instance.Localize("[<color=yellow><b>$KEY_Use</b></color>]<color=white><b>$valheim_vehicles_wheel_use</b></color>\n" + anchorMessage + "\n" + text); } private string GetOwnerHoverText() { IVehicleShip vehicleShip = ShipInstance?.PiecesController?.VehicleInstance; object obj; if (vehicleShip == null) { obj = null; } else { ZNetView? netView = vehicleShip.NetView; obj = ((netView != null) ? netView.GetZDO() : null); } if (obj == null) { return ""; } long ownerId = vehicleShip.NetView.GetZDO().GetOwner(); if (ownerId != _currentOwner || _currentPlayerName == null) { Player val = ((IEnumerable<Player>)vehicleShip?.OnboardController.m_localPlayers).FirstOrDefault((Func<Player, bool>)delegate(Player player) { long owner = ((Character)player).GetOwner(); return ownerId == owner; }); _currentOwner = ((val != null) ? new long?(((Character)val).GetOwner()) : null); _currentPlayerName = ((val != null) ? val.GetPlayerName() : null) ?? "Server"; } return "\n[<color=green><b>Physics Owner: " + _currentPlayerName + "</b></color>]"; } private string GetBeachedHoverText() { return "\n[<color=red><b>$valheim_vehicles_gui_vehicle_is_beached</b></color>]"; } public string GetHoverText() { VehiclePiecesController vehiclePiecesController = ShipInstance?.PiecesController; if ((Object)(object)vehiclePiecesController == (Object)null) { return Localization.instance.Localize("<color=white><b>$valheim_vehicles_wheel_use_error</b></color>"); } bool valueOrDefault = (vehiclePiecesController?.VehicleInstance?.MovementController?.isAnchored).GetValueOrDefault(); string anchorHotkeyString = GetAnchorHotkeyString(); string text = GetHoverTextFromShip(vehiclePiecesController?.cachedTotalSailArea ?? 0f, vehiclePiecesController?.TotalMass ?? 0f, vehiclePiecesController?.ShipMass ?? 0f, vehiclePiecesController?.GetSailingForce() ?? 0f, valueOrDefault, anchorHotkeyString); if ((vehiclePiecesController?.OnboardController?.m_localPlayers?.Any()).Value) { text += GetOwnerHoverText(); } if ((vehiclePiecesController?.MovementController?.isBeached).Value) { text += GetBeachedHoverText(); } return Localization.instance.Localize(text); } private void Awake() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_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) AttachPoint = ((Component)this).transform.Find("attachpoint"); wheelTransform = ((Component)this).transform.Find("controls/wheel"); wheelLocalOffset = wheelTransform.position - ((Component)this).transform.position; PrefabRegistryHelpers.IgnoreCameraCollisions(((Component)this).gameObject); steeringWheelHoverTransform = ((Component)this).transform.Find("wheel_state_hover_message"); steeringWheelHoverText = ((Component)steeringWheelHoverTransform).gameObject.AddComponent<HoverFadeText>(); } public string GetHoverName() { return ModTranslations.WheelControls_Name; } public void SetLastUsedWheel() { if ((Object)(object)ShipInstance.MovementController != (Object)null) { ShipInstance.MovementController.lastUsedWheelComponent = this; } } public bool Interact(Humanoid user, bool hold, bool alt) { if (!((Behaviour)this).isActiveAndEnabled) { return false; } bool flag = InUseDistance((Component)(object)user); bool flag2 = (Object)(object)ShipInstance.Instance == (Object)null; if (hold || flag2 || !flag) { return false; } SetLastUsedWheel(); Player val = (Player)(object)((user is Player) ? user : null); IVehicleShip shipInstance = ShipInstance; object obj; if (shipInstance == null) { obj = null; } else { VehiclePiecesController? piecesController = shipInstance.PiecesController; obj = ((piecesController != null) ? ((Component)piecesController).GetComponentsInChildren<Player>() : null); } if (obj == null) { obj = null; } Player[] array = (Player[])obj; if ((Object)(object)val != (Object)null) { ShipInstance?.MovementController?.UpdatePlayerOnShip(val); } if ((array != null && array.Length == 0) || array == null) { array = ShipInstance?.Instance?.OnboardController?.m_localPlayers.ToArray() ?? null; } if (array != null) { Player[] array2 = array; foreach (Player val2 in array2) { Logger.LogDebug((object)$"Interact PlayerId {val2.GetPlayerID()}, currentPlayerId: {val.GetPlayerID()}"); if (val2.GetPlayerID() == val.GetPlayerID()) { ShipInstance?.Instance?.MovementController?.SendRequestControl(val2.GetPlayerID()); return true; } } } if ((Object)(object)val == (Object)null || ((Character)val).IsEncumbered()) { return false; } if (VehicleShipCompat.InitFromUnknown(((Character)val).GetStandingOnShip()) == null) { Logger.LogDebug((object)"Player is not on Ship"); return false; } if (!Object.op_Implicit((Object)(object)ShipInstance?.Instance?.MovementController)) { return false; } ShipInstance.Instance.MovementController?.SendRequestControl(val.GetPlayerID()); return true; } public bool UseItem(Humanoid user, ItemData item) { return false; } public void OnUseStop(Player player) { ShipInstance.Instance?.MovementController?.SendReleaseControl(player); } public void ApplyControlls(Vector3 moveDir, Vector3 lookDir, bool run, bool autoRun, bool block) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)ShipInstance.Instance == (Object)null) && !((Object)(object)ShipInstance.Instance.MovementController == (Object)null)) { ShipInstance?.Instance.MovementController.ApplyControls(moveDir); } } public Component? GetControlledComponent() { return (Component?)(object)ShipInstance.Instance; } public Vector3 GetPosition() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return ((Component)this).transform.position; } public bool IsValid() { return Object.op_Implicit((Object)(object)this); } public void FixedUpdate() { steeringWheelHoverText.FixedUpdate_UpdateText(); } public void InitializeControls(ZNetView netView, IVehicleShip? vehicleShip) { if (vehicleShip == null) { Logger.LogError((object)"Initialized called with null vehicleShip"); return; } ShipInstance = vehicleShip; if (!Object.op_Implicit((Object)(object)_controls)) { _controls = vehicleShip.Instance.MovementController; } if ((Object)(object)_controls != (Object)null) { _controls.InitializeWheelWithShip(this); ShipInstance = vehicleShip; ((Behaviour)_controls).enabled = true; } } public void UpdateSteeringHoverMessage(AnchorState anchorState, string message) { if (anchorState != lastAnchorState) { lastAnchorState = anchorState; steeringWheelHoverText.ResetHoverTimer(); steeringWheelHoverText.currentText = message; } } public void UpdateSpokes() { m_spokes.Clear(); m_spokes.AddRange(from k in ((Component)wheelTransform).GetComponentsInChildren<Transform>() where ((Object)((Component)k).gameObject).name.StartsWith("grabpoint") select k); } private Vector3 GetWheelHandOffset(float height) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) return new Vector3(0f, (height > wheelLocalOffset.y) ? (-0.25f) : 0.25f, 0f); } public void UpdateIK(Animator animator) { //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_002c: 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_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_0062: 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_009f: 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_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: 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_0126: 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_00f2: 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_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_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_0263: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0279: 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_013d: 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: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0156: 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_027e: 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_02ba: 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_0298: 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_02d1: Unknown result type (might be due to invalid IL or missing references) //IL_02e2: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)wheelTransform)) { return; } if (!Object.op_Implicit((Object)(object)m_currentLeftHand)) { Vector3 position = ((Component)this).transform.TransformPoint(m_leftHandPosition); m_currentLeftHand = GetNearestSpoke(position); } if (!Object.op_Implicit((Object)(object)m_currentRightHand)) { Vector3 position2 = ((Component)Player.m_localPlayer).transform.TransformPoint(m_leftHandPosition); m_currentRightHand = GetNearestSpoke(position2); } if (!Object.op_Implicit((Object)(object)m_targetLeftHand) && !Object.op_Implicit((Object)(object)m_targetRightHand)) { Vector3 val = ((Component)this).transform.InverseTransformPoint(m_currentLeftHand.position); Vector3 val2 = ((Component)this).transform.InverseTransformPoint(m_currentRightHand.position); Vector3 val3 = wheelLocalOffset.y * Vector3.up; if (val.x > 0f) { m_targetLeftHand = GetNearestSpoke(((Component)this).transform.TransformPoint(m_leftHandPosition + GetWheelHandOffset(val.y) + val3)); m_movingLeftAlpha = Time.time; } else if (val2.x < 0f) { m_targetRightHand = GetNearestSpoke(((Component)this).transform.TransformPoint(m_rightHandPosition + GetWheelHandOffset(val2.y) + val3)); m_movingRightAlpha = Time.time; } } float num = Mathf.Clamp01((Time.time - m_movingLeftAlpha) / m_handIKSpeed); float num2 = Mathf.Clamp01((Time.time - m_movingRightAlpha) / m_handIKSpeed); float num3 = Mathf.Sin(num * (float)Math.PI) * (1f - m_holdWheelTime) + m_holdWheelTime; float num4 = Mathf.Sin(num2 * (float)Math.PI) * (1f - m_holdWheelTime) + m_holdWheelTime; if (Object.op_Implicit((Object)(object)m_targetLeftHand) && num > 0.99f) { m_currentLeftHand = m_targetLeftHand; m_targetLeftHand = null; } if (Object.op_Implicit((Object)(object)m_targetRightHand) && num2 > 0.99f) { m_currentRightHand = m_targetRightHand; m_targetRightHand = null; } Vector3 val4 = (Object.op_Implicit((Object)(object)m_targetLeftHand) ? Vector3.Lerp(((Component)m_currentLeftHand).transform.position, ((Component)m_targetLeftHand).transform.position, num) : ((Component)m_currentLeftHand).transform.position); Vector3 val5 = (Object.op_Implicit((Object)(object)m_targetRightHand) ? Vector3.Lerp(((Component)m_currentRightHand).transform.position, ((Component)m_targetRightHand).transform.position, num2) : ((Component)m_currentRightHand).transform.position); animator.SetIKPositionWeight((AvatarIKGoal)2, num3); animator.SetIKPosition((AvatarIKGoal)2, val4); animator.SetIKPositionWeight((AvatarIKGoal)3, num4); animator.SetIKPosition((AvatarIKGoal)3, val5); } public Transform GetNearestSpoke(Vector3 position) { //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) Transform val = null; float num = 0f; foreach (Transform spoke in m_spokes) { Vector3 val2 = ((Component)spoke).transform.position - position; float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude; if (!((Object)(object)val != (Object)null) || sqrMagnitude < num) { val = spoke; num = sqrMagnitude; } } return val; } private bool InUseDistance(Component human) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)AttachPoint == (Object)null) { return false; } return Vector3.Distance(human.transform.position, AttachPoint.position) < 10f; } } } namespace ValheimVehicles.Prefabs { public interface ILoadAssets { void Init(AssetBundle assetBundle); } public interface IRegisterPrefab { void Register(PrefabManager prefabManager, PieceManager pieceManager); } public static class PrefabNames { public enum PrefabSizeVariant { TwoByTwo, TwoByThree, FourByFour, FourByEight } public enum DirectionVariant { Left, Right } public static class MastLevels { public const string ONE = "level_1"; public const string TWO = "level_2"; public const string THREE = "level_3"; } private const string ValheimVehiclesPrefix = "ValheimVehicles"; public const string LandVehicle = "ValheimVehicles_VehicleLand"; public const string AirVehicle = "ValheimVehicles_VehicleAir"; public const string WheelSet = "ValheimVehicles_WheelSet"; public const string MBRopeAnchor = "MBRopeAnchor"; public const string CustomWaterFloatation = "ValheimVehicles_CustomWaterFloatation"; public const string CustomWaterMask = "ValheimVehicles_CustomWaterMask"; public const string CustomWaterMaskCreator = "ValheimVehicles_CustomWaterMaskCreator"; public const string CustomVehicleMaxCollisionHeightCreator = "ValheimVehicles_CustomVehicleMaxCollisionHeightCreator"; public const string PlayerSpawnControllerObj = "ValheimVehicles_PlayerSpawnControllerObj"; public const string ShipAnchorWood = "ValheimVehicles_ShipAnchor_wood"; public const string MBRopeLadder = "MBRopeLadder"; public const string MBRaft = "MBRaft"; public const string Nautilus = "ValheimVehicles_VehiclePresets_Nautilus"; public static int m_raftHash = StringExtensionMethods.GetStableHashCode("MBRaft"); public const string Tier1RaftMastName = "MBRaftMast"; public const string Tier2RaftMastName = "MBKarveMast"; public const string Tier3RaftMastName = "MBVikingShipMast"; public const string Tier4RaftMastName = "ValheimVehicles_DrakkalMast"; public const string Tier1CustomSailName = "MBSail"; public const string BoardingRamp = "MBBoardingRamp"; public const string BoardingRampWide = "MBBoardingRamp_Wide"; public const string WaterVehicleFloatCollider = "VehicleShip_FloatCollider"; public const string WaterVehicleBlockingCollider = "VehicleShip_BlockingCollider"; public const string WaterVehicleOnboardCollider = "VehicleShip_OnboardTriggerCollider"; public const string DEPRECATED_ValheimRaftMenuName = "Raft"; private const string PiecesContainer = "piecesContainer"; public const string MovingPiecesContainer = "movingPiecesContainer"; public const string GhostContainer = "ghostContainer"; public const string VehicleContainer = "vehicleContainer"; public const string VehiclePiecesContainer = "ValheimVehicles_piecesContainer"; public const string VehicleMovingPiecesContainer = "ValheimVehicles_movingPiecesContainer"; public const string WaterVehicleShip = "ValheimVehicles_WaterVehicleShip"; public const string HullProw = "ValheimVehicles_Ship_Hull_Prow"; public const string HullRibCorner = "ValheimVehicles_Ship_Hull_Rib_Corner"; public const string HullRibCornerFloor = "ValheimVehicles_Ship_Hull_Rib_Corner_Floor"; public const string HullRib = "ValheimVehicles_Ship_Hull_Rib"; public const string HullSlab = "ValheimVehicles_Hull_Slab"; public const string HullWall = "ValheimVehicles_Hull_Wall"; public const string HullCornerFloor = "ValheimVehicles_Hull_Corner_Floor"; public const string KeelColliderPrefix = "keel_collider"; public const string ShipHullPrefabName = "Ship_Hull"; public const string WindowWallPorthole2x2Prefab = "ValheimVehicles_ShipWindow_Wall_Porthole_2x2"; public const string WindowWallPorthole4x4Prefab = "ValheimVehicles_ShipWindow_Wall_Porthole_4x4"; public const string WindowWallPorthole8x4Prefab = "ValheimVehicles_ShipWindow_Wall_Porthole_8x4"; public const string WindowFloorPorthole4x4Prefab = "ValheimVehicles_ShipWindow_Floor_Porthole_4x4"; public const string WindowWallSquareIronPrefabName = "ValheimVehicles_ShipWindow_Wall_Square_iron_2x2"; public const string WindowWallSquareWoodPrefabName = "ValheimVehicles_ShipWindow_Wall_Square_wood_2x2"; public const string WindowPortholeStandalonePrefab = "ValheimVehicles_ShipWindow_Porthole_standalone"; public const string ShipHullCenterWoodPrefabName = "ValheimVehicles_Ship_Hull_Wood"; public const string ShipHullCenterIronPrefabName = "ValheimVehicles_Ship_Hull_Iron"; public const string ShipRudderBasic = "ValheimVehicles_ShipRudderBasic"; public const string ShipRudderAdvancedWood = "ValheimVehicles_ShipRudderAdvanced_Wood"; public const string ShipRudderAdvancedIron = "ValheimVehicles_ShipRudderAdvanced_Iron"; public const string ShipRudderAdvancedDoubleWood = "ValheimVehicles_ShipRudderAdvanced_Tail_Wood"; public const string ShipRudderAdvancedDoubleIron = "ValheimVehicles_ShipRudderAdvanced_Tail_Iron"; public const string ShipSteeringWheel = "ValheimVehicles_ShipSteeringWheel"; public const string ShipKeel = "ValheimVehicles_ShipKeel"; public const string WaterVehiclePreviewHull = "ValheimVehicles_WaterVehiclePreviewHull"; public const string VehicleSail = "ValheimVehicles_VehicleSail"; public const string VehicleShipTransform = "ValheimVehicles_VehicleShipTransform"; public const string VehicleShipEffects = "ValheimVehicles_VehicleShipEffects"; public const string VehicleSailMast = "ValheimVehicles_VehicleSailMast"; public const string VehicleSailCloth = "ValheimVehicles_SailCloth"; public const string ToggleSwitch = "ValheimVehicles_ToggleSwitch"; public const string VehicleShipMovementOrientation = "VehicleShip_MovementOrientation"; public const string VehicleHudAnchorIndicator = "ValheimVehicles_HudAnchorIndicator"; public const string VehicleHammer = "ValheimVehicles_vehicle_hammer"; public const string RamBladePrefix = "ValheimVehicles_ram_blade"; public const string RamStakePrefix = "ValheimVehicles_ram_stake"; public const string ConvexHull = "ValheimVehicles_ConvexHull"; public static string GetPrefabSizeName(PrefabSizeVariant variant) { return variant switch { PrefabSizeVariant.TwoByTwo => "2x2", PrefabSizeVariant.TwoByThree => "2x3", PrefabSizeVariant.FourByFour => "4x4", _ => throw new ArgumentOutOfRangeException("variant", variant, null), }; } public static string GetDirectionName(DirectionVariant directionVariant) { return directionVariant switch { DirectionVariant.Left => "left", DirectionVariant.Right => "right", _ => throw new ArgumentOutOfRangeException("directionVariant", directionVariant, null), }; } public static int GetPrefabSizeArea(PrefabSizeVariant variant) { return variant switch { PrefabSizeVariant.TwoByTwo => 4, PrefabSizeVariant.TwoByThree => 6, PrefabSizeVariant.FourByFour => 16, PrefabSizeVariant.FourByEight => 32, _ => throw new ArgumentOutOfRangeException("variant", variant, null), }; } private static string GetMaterialVariantName(string materialVariant) { if (!(materialVariant == "iron")) { return "Wood"; } return "Iron"; } private static string GetPrefabSizeVariantName(PrefabSizeVariant prefabSizeVariant) { if (prefabSizeVariant != PrefabSizeVariant.FourByFour) { return "2x2"; } return "4x4"; } public static string GetHullProwVariants(string materialVariant, PrefabSizeVariant prefabSizeVariant) { string prefabSizeVariantName = GetPrefabSizeVariantName(prefabSizeVariant); string materialVariantName = GetMaterialVariantName(materialVariant); return "ValheimVehicles_Ship_Hull_Prow_" + materialVariantName + "_" + prefabSizeVariantName; } public static string GetHullRibName(string materialVariant) { string materialVariantName = GetMaterialVariantName(materialVariant); return "ValheimVehicles_Ship_Hull_Rib_" + materialVariantName; } public static string GetHullRibCornerName(string materialVariant) { string materialVariantName = GetMaterialVariantName(materialVariant); return "ValheimVehicles_Ship_Hull_Rib_Corner_" + materialVariantName; } public static string GetHullRibCornerFloorName(string materialVariant, DirectionVariant directionVariant) { string directionName = GetDirectionName(directionVariant); string materialVariantName = GetMaterialVariantName(materialVariant); return "ValheimVehicles_Ship_Hull_Rib_Corner_Floor_" + directionName + "_" + materialVariantName; } public static string GetHullSlabName(string materialVariant, PrefabSizeVariant prefabSizeVariant) { string prefabSizeVariantName = GetPrefabSizeVariantName(prefabSizeVariant); string materialVariantName = GetMaterialVariantName(materialVariant); return "ValheimVehicles_Hull_Slab_" + materialVariantName + "_" + prefabSizeVariantName; } public static string GetHullWallName(string materialVariant, PrefabSizeVariant prefabSizeVariant) { string prefabSizeVariantName = GetPrefabSizeVariantName(prefabSizeVariant); string materialVariantName = GetMaterialVariantName(materialVariant); return "ValheimVehicles_Hull_Wall_" + materialVariantName + "_" + prefabSizeVariantName; } public static string GetShipHullCenterName(string hullMaterial) { if (hullMaterial == "iron") { return "ValheimVehicles_Ship_Hull_Iron"; } if (hullMaterial == "wood") { return "ValheimVehicles_Ship_Hull_Wood"; } Logger.LogError((object)"No hull of this name, this is an error registering a hull"); return ""; } public static string GetRamBladeName(string val) { return "ValheimVehicles_ram_blade_" + val.ToLower() + "_tier3"; } public static string GetRamStakeName(string tier, int size) { string text = ((size == 1) ? "1x2" : "2x4"); return "ValheimVehicles_ram_stake_" + tier + "_" + text; } public static void ValidateMastTypeName(string mastLevel) { if (mastLevel != "level_1" && mastLevel != "level_2" && mastLevel != "level_3") { throw new ArgumentException("Invalid mast tier name: " + mastLevel, "mastLevel"); } } public static string GetMastByLevelFromAssetBundle(string mastLevel) { ValidateMastTypeName(mastLevel); return "mast_" + mastLevel; } public static string GetMastByLevelName(string mastLevel) { ValidateMastTypeName(mastLevel); return "ValheimVehicles_" + GetMastByLevelFromAssetBundle(mastLevel); } public static bool IsVehicleCollider(string objName) { if (!objName.StartsWith("VehicleShip_BlockingCollider") && !objName.StartsWith("VehicleShip_FloatCollider")) { return objName.StartsWith("VehicleShip_OnboardTriggerCollider"); } return true; } public static bool IsHull(string goName) { if (!goName.StartsWith("ValheimVehicles_Ship_Hull_Wood") && !goName.StartsWith("ValheimVehicles_Ship_Hull_Iron") && !goName.StartsWith("ValheimVehicles_Ship_Hull_Rib") && !goName.StartsWith("ValheimVehicles_Ship_Hull_Rib_Corner") && !goName.StartsWith("ValheimVehicles_Hull_Wall") && !goName.StartsWith("ValheimVehicles_Hull_Slab") && !goName.StartsWith("ValheimVehicles_Ship_Hull_Prow") && !goName.StartsWith("ValheimVehicles_Ship_Hull_Rib_Corner_Floor") && !goName.StartsWith("ValheimVehicles_ShipWindow_Porthole_standalone") && !goName.StartsWith("ValheimVehicles_ShipWindow_Wall_Porthole_2x2") && !goName.StartsWith("ValheimVehicles_ShipWindow_Wall_Porthole_4x4") && !goName.StartsWith("ValheimVehicles_ShipWindow_Wall_Square_iron_2x2")) { return goName.StartsWith("ValheimVehicles_ShipWindow_Wall_Square_wood_2x2"); } return true; } public static bool IsHull(GameObject go) { return IsHull(((Object)go).name); } public static bool IsVehicle(string goName) { if (!goName.StartsWith("ValheimVehicles_VehicleLand")) { return goName.StartsWith("ValheimVehicles_WaterVehicleShip"); } return true; } } public static class PrefabRegistryController { public static PrefabManager prefabManager; public static PieceManager pieceManager; private static SynchronizationManager synchronizationManager; private static List<Piece> raftPrefabPieces = new List<Piece>(); private static bool prefabsEnabled = true; public static AssetBundle vehicleAssetBundle; private static bool HasRunInitSuccessfully = false; private static string ValheimDefaultPieceTableName = "Hammer"; private static PieceTable? _cachedValheimHammerPieceTable = null; public static float wearNTearBaseHealth = 250f; public static string GetPieceTableName() { if (VehicleHammerTableRegistry.VehicleHammerTable == null) { return ValheimDefaultPieceTableName; } return "ValheimVehicles_HammerTable"; } public static PieceTable GetPieceTable() { if (VehicleHammerTableRegistry.VehicleHammerTable != null) { return VehicleHammerTableRegistry.VehicleHammerTable.PieceTable; } if ((Object)(object)_cachedValheimHammerPieceTable != (Object)null) { return _cachedValheimHammerPieceTable; } _cachedValheimHammerPieceTable = PieceManager.Instance.GetPieceTable(ValheimDefaultPieceTableName); return _cachedValheimHammerPieceTable; } public static string SetCategoryName(string val) { if (VehicleHammerTableRegistry.VehicleHammerTable != null) { return val; } return "Raft"; } public static void DebugDestroyAllRaftObjects() { GameObject[] array = Resources.FindObjectsOfTypeAll<GameObject>(); foreach (GameObject val in array) { if (((Object)val).name.Contains("ValheimVehicles_WaterVehicleShip(Clone)") || (PrefabNames.IsHull(val) && ((Object)val).name.Contains("(Clone)"))) { WearNTear component = val.GetComponent<WearNTear>(); if (Object.op_Implicit((Object)(object)component)) { component.Destroy((HitData)null, false); } else { Object.Destroy((Object)(object)val); } } } } private static void SetupComponents() { Vector3Logger.LoggerAPI = Logger.LogDebug; ConvexHullAPI.DebugMaterial = LoadValheimVehicleAssets.DoubleSidedTransparentMat; } private static void UpdatePrefabs(bool isPrefabEnabled) { foreach (Piece raftPrefabPiece in raftPrefabPieces) { CustomPiece piece = pieceManager.GetPiece(((Object)raftPrefabPiece).name); if (piece == null) { Logger.LogWarning((object)("ValheimRaft attempted to run UpdatePrefab on " + ((Object)raftPrefabPiece).name + " but jotunn pieceManager did not find that piece name")); continue; } Logger.LogDebug((object)$"Setting m_enabled: to {isPrefabEnabled}, for name {((Object)raftPrefabPiece).name}"); piece.Piece.m_enabled = isPrefabEnabled; } prefabsEnabled = isPrefabEnabled; } public static void UpdatePrefabStatus() { if (PrefabConfig.AdminsCanOnlyBuildRaft.Value || !prefabsEnabled) { Logger.LogDebug((object)$"ValheimRAFT: UpdatePrefabStatusCalled with AdminsCanOnlyBuildRaft set as {PrefabConfig.AdminsCanOnlyBuildRaft.Value}, updating prefabs and player access"); UpdatePrefabs(SynchronizationManager.Instance.PlayerIsAdmin); } } public static void UpdatePrefabStatus(object obj, ConfigurationSynchronizationEventArgs e) { UpdateRaftSailDescriptions(); UpdatePrefabStatus(); } private static void UpdateRaftSailDescriptions() { pieceManager.GetPiece("MBRaftMast").Piece.m_description = SailPrefabs.GetTieredSailAreaText(1); pieceManager.GetPiece("MBKarveMast").Piece.m_description = SailPrefabs.GetTieredSailAreaText(2); pieceManager.GetPiece("MBVikingShipMast").Piece.m_description = SailPrefabs.GetTieredSailAreaText(3); pieceManager.GetPiece("ValheimVehicles_DrakkalMast").Piece.m_description = SailPrefabs.GetTieredSailAreaText(4); } public static void InitAfterVanillaItemsAndPrefabsAreAvailable() { if (HasRunInitSuccessfully) { LoggerProvider.LogInfo("skipping PrefabRegistryController.Init as it has already been done.", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\ValheimVehicles\\ValheimVehicles.Prefabs\\PrefabRegistryController.cs", 186); return; } try { vehicleAssetBundle = AssetUtils.LoadAssetBundleFromResources("valheim-vehicles", Assembly.GetCallingAssembly()); prefabManager = PrefabManager.Instance; pieceManager = PieceManager.Instance; LoadValheimAssets.Instance.Init(prefabManager); LoadValheimRaftAssets.Instance.Init(vehicleAssetBundle); LoadValheimVehicleAssets.Instance.Init(vehicleAssetBundle); new VehicleHammerTableRegistry().Register(); PrefabRegistryHelpers.Init(); RegisterAllItemPrefabs(); RegisterAllPiecePrefabs(); SetupComponents(); } catch (Exception arg) { LoggerProvider.LogError($"Error occurred during InitAfterVanillaItemsAndPrefabsAvaila
plugins\ZdoWatcher.dll
Decompiled a week 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.Configuration; using HarmonyLib; using Jotunn; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using UnityEngine; using ZdoWatcher.Patches; using ZdoWatcher.ZdoWatcher.Config; using Zolantris.Shared.Debug; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("ZdoWatcher")] [assembly: AssemblyDescription("Valheim Mod made to share Zdo Changes and side effect through one shareable interface")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Virtualize LLC")] [assembly: AssemblyProduct("ZdoWatcher")] [assembly: AssemblyCopyright("Copyright © 2023-2024, GNU-v3 licensed")] [assembly: Guid("6015B165-2627-40A7-8CA1-3E6B6CD7CB49")] [assembly: AssemblyFileVersion("1.1.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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] [Microsoft.CodeAnalysis.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 ZdoWatcher { public static class ZdoVarController { private static readonly Dictionary<string, string> ZdoVariables = new Dictionary<string, string>(); public static readonly int PersistentUidHash = StringExtensionMethods.GetStableHashCode("PersistentID"); public static string NameToVar(BaseUnityPlugin unityPlugin, string key) { return ((Object)unityPlugin).name + "_" + key; } public static void RegisterPublicVar(BaseUnityPlugin unityPlugin, string key, int value) { string key2 = NameToVar(unityPlugin, key); ZdoVariables.Add(key2, value.ToString()); } public static void RegisterPublicVar(BaseUnityPlugin unityPlugin, string key, string value) { NameToVar(unityPlugin, key); ZdoVariables.Add(key, value); } public static void ListPublicVar(bool shouldLog = true) { if (!shouldLog) { return; } foreach (KeyValuePair<string, string> zdoVariable in ZdoVariables) { Logger.LogInfo((object)("Key: " + zdoVariable.Key + ", Value: " + zdoVariable.Value)); } } } public class ZdoWatchController : MonoBehaviour { public static Action<ZDO>? OnDeserialize; public static Action<ZDO>? OnLoad; public static Action<ZDO>? OnReset; public static ZdoWatchController Instance; private readonly Dictionary<int, ZDO> _zdoGuidLookup = new Dictionary<int, ZDO>(); private readonly List<DebugSafeTimer> _timers = new List<DebugSafeTimer>(); private CustomRPC RPC_RequestPersistentIdInstance; public Dictionary<int, ZDO?> PendingPersistentIdQueries = new Dictionary<int, ZDO>(); public void Awake() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown RPC_RequestPersistentIdInstance = NetworkManager.Instance.AddRPC("RPC_RequestSync", new CoroutineHandler(RequestPersistentIdRPCServerReceive), (CoroutineHandler)null); } public Dictionary<int, ZDO> GetAllZdoGuids() { return _zdoGuidLookup.ToDictionary<KeyValuePair<int, ZDO>, int, ZDO>((KeyValuePair<int, ZDO> kvp) => kvp.Key, (KeyValuePair<int, ZDO> kvp) => kvp.Value); } public void Update() { DebugSafeTimer.UpdateTimersFromList(_timers); } public void SyncToPeer(ZDOPeer? zdoPeer) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) if (!ZNet.instance.IsServer() || zdoPeer == null) { return; } foreach (ZDO value in _zdoGuidLookup.Values) { if (zdoPeer != null) { zdoPeer.ForceSendZDO(value.m_uid); } } } private IEnumerator RequestPersistentIdRPCServerReceive(long sender, ZPackage package) { int num = package.ReadInt(); ZDOPeer peer = ZDOMan.instance.GetPeer(sender); Logger.LogMessage((object)$"Sending first id across to peer {num}"); ZDO zdo = GetZdo(num); if (zdo != null && peer != null) { peer.ForceSendZDO(zdo.m_uid); } else { Logger.LogMessage((object)"RequestPersistentIdRPCServerReceive called but zdoid not found, attempting to sync all ids to peer"); SyncToPeer(peer); } yield return null; } public ZPackage GetAllServerZdoIds() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) ZPackage val = new ZPackage(); Logger.LogMessage((object)$"Writing {_zdoGuidLookup.Values.Count} zdos to a ZPackage"); foreach (ZDO value in _zdoGuidLookup.Values) { val.Write(value.m_uid); } return val; } public bool RequestZdoFromServer(int persistentId) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown if (ZNet.instance.IsServer()) { return false; } ZPackage val = new ZPackage(); val.Write(persistentId); long serverPeerID = ZRoutedRpc.instance.GetServerPeerID(); RPC_RequestPersistentIdInstance.SendPackage(serverPeerID, val); return true; } public IEnumerator GetZdoFromServerAsync(int persistentId, Action<ZDO?> onComplete) { if (ZNet.instance.IsServer()) { ZDO zdo = GetZdo(persistentId); Logger.LogWarning((object)$"Called GetZdoFromServer for {persistentId} on the server. This should not happen"); onComplete(zdo); yield break; } ZDO zdo2 = GetZdo(persistentId); if (zdo2 != null) { onComplete(zdo2); } else if (PendingPersistentIdQueries.ContainsKey(persistentId)) { Logger.LogWarning((object)$"RequestPersistentID called for ongoing operation on id: {persistentId}, requests cannot be called during a specific timelimit"); onComplete(null); } else { RequestZdoFromServer(persistentId); yield return WaitForZdo(persistentId, onComplete); Logger.LogDebug((object)"GetZdoFromServerAsync finished"); } } private IEnumerator WaitForZdo(int persistentId, Action<ZDO?> onComplete, int timeoutInMs = 2000) { DebugSafeTimer timer = DebugSafeTimer.StartNew(_timers); ZDO targetZdo = null; while (timer.ElapsedMilliseconds < (float)timeoutInMs && targetZdo == null) { if (_zdoGuidLookup.TryGetValue(persistentId, out ZDO value)) { targetZdo = value; break; } yield return (object)new WaitForFixedUpdate(); } if (timer.ElapsedMilliseconds >= (float)timeoutInMs) { Logger.LogWarning((object)"Timeout for WaitForZdo reached, exiting the WaitForZdo call with a failure."); } else { Logger.LogDebug((object)$"Completed timer in: {timer.ElapsedMilliseconds} milliseconds"); } if (PendingPersistentIdQueries.ContainsKey(persistentId)) { PendingPersistentIdQueries.Remove(persistentId); } onComplete(targetZdo); } public void Reset() { _zdoGuidLookup.Clear(); } public static bool GetPersistentID(ZDO zdo, out int id) { id = zdo.GetInt(ZdoVarController.PersistentUidHash, 0); return id != 0; } public static int ZdoIdToId(ZDOID zdoid) { return (int)((ZDOID)(ref zdoid)).UserID + (int)((ZDOID)(ref zdoid)).ID; } public int GetOrCreatePersistentID(ZDO? zdo) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown //IL_002a: Unknown result type (might be due to invalid IL or missing references) if (zdo == null) { Logger.LogWarning((object)"GetOrCreatePersistentID called with a null ZDO, this will be disabled in the future."); } if (zdo == null) { zdo = new ZDO(); } int @int = zdo.GetInt(ZdoVarController.PersistentUidHash, 0); if (@int != 0) { return @int; } for (@int = ZdoIdToId(zdo.m_uid); _zdoGuidLookup.ContainsKey(@int); @int++) { } zdo.Set(ZdoVarController.PersistentUidHash, @int, false); _zdoGuidLookup[@int] = zdo; return @int; } public void HandleRegisterPersistentId(ZDO zdo) { if (GetPersistentID(zdo, out var id)) { _zdoGuidLookup[id] = zdo; } } private void HandleDeregisterPersistentId(ZDO zdo) { if (GetPersistentID(zdo, out var id)) { _zdoGuidLookup.Remove(id); } } public void Deserialize(ZDO zdo) { HandleRegisterPersistentId(zdo); if (OnDeserialize == null) { return; } try { OnDeserialize(zdo); } catch { Logger.LogError((object)"OnDeserialize had an error"); } } public void Load(ZDO zdo) { HandleRegisterPersistentId(zdo); if (OnLoad == null) { return; } try { OnLoad(zdo); } catch { Logger.LogError((object)"OnLoad had an error"); } } public void Reset(ZDO zdo) { HandleDeregisterPersistentId(zdo); if (OnReset == null) { return; } try { OnReset(zdo); } catch { Logger.LogError((object)"OnReset had an error"); } } public ZDO? GetZdo(int id) { if (!_zdoGuidLookup.TryGetValue(id, out ZDO value)) { return null; } return value; } public GameObject? GetGameObject(int id) { ZNetView instance = GetInstance(id); if (!Object.op_Implicit((Object)(object)instance)) { return null; } if (instance == null) { return null; } return ((Component)instance).gameObject; } public ZNetView? GetInstance(int id) { ZDO zdo = GetZdo(id); if (zdo == null) { return null; } return ZNetScene.instance.FindInstance(zdo); } } [BepInPlugin("zolantris.ZdoWatcher", "ZdoWatcher", "1.1.0")] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] public class ZdoWatcherPlugin : BaseUnityPlugin { public const string Author = "zolantris"; public const string Version = "1.1.0"; public const string ModName = "ZdoWatcher"; public const string ModGuid = "zolantris.ZdoWatcher"; private static Harmony _harmony; public const string ModDescription = "Valheim Mod made to share Zdo Changes and side effect through one shareable interface"; public const string CopyRight = "Copyright © 2023-2024, GNU-v3 licensed"; public static string HarmonyGuid => "zolantris.ZdoWatcher"; private void Awake() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown ZdoWatcherConfig.BindConfig(((BaseUnityPlugin)this).Config); _harmony = new Harmony(HarmonyGuid); _harmony.PatchAll(typeof(ZdoPatch)); _harmony.PatchAll(typeof(ZNetScene_Patch)); _harmony.PatchAll(typeof(ZDOMan_Patch)); if (ZdoWatcherConfig.GuardAgainstInvalidZNetSceneSpam != null && ZdoWatcherConfig.GuardAgainstInvalidZNetSceneSpam.Value) { _harmony.PatchAll(typeof(InvalidZNetScenePatch)); } ZdoWatchController.Instance = ((Component)this).gameObject.AddComponent<ZdoWatchController>(); } } } namespace ZdoWatcher.Patches { public class ZDOMan_Patch { [HarmonyPatch(typeof(ZDOMan), "AddPeer")] [HarmonyPostfix] private static void OnAddPeer(ZDOMan __instance) { int num = __instance.m_peers.Count - 1; if (num >= 1) { ZDOPeer zdoPeer = __instance.m_peers[num]; ZdoWatchController.Instance.SyncToPeer(zdoPeer); } } } [HarmonyPatch] public class ZdoPatch { [HarmonyPatch(typeof(ZDO), "Deserialize")] [HarmonyPostfix] private static void ZDO_Deserialize(ZDO __instance, ZPackage pkg) { ZdoWatchController.Instance.Deserialize(__instance); } [HarmonyPatch(typeof(ZDO), "Load")] [HarmonyPostfix] private static void ZDO_Load(ZDO __instance, ZPackage pkg, int version) { ZdoWatchController.Instance.Load(__instance); } [HarmonyPatch(typeof(ZDO), "Reset")] [HarmonyPrefix] private static void ZDO_Reset(ZDO __instance) { ZdoWatchController.Instance.Reset(__instance); } } public class ZNetScene_Patch { [HarmonyPatch(typeof(ZNetScene), "Shutdown")] [HarmonyPostfix] private static void ZNetScene_Shutdown() { ZdoWatchController.Instance.Reset(); } } } namespace ZdoWatcher.ZdoWatcher.Config { public class ConfigHelpers { public static ConfigDescription CreateConfigDescription(string description, bool isAdmin = false, bool isAdvanced = false) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown return new ConfigDescription(description, (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = isAdmin, IsAdvanced = isAdvanced } }); } } public static class ZdoWatcherConfig { public static ConfigFile? Config { get; private set; } public static ConfigEntry<bool>? GuardAgainstInvalidZNetSceneSpam { get; private set; } public static void BindConfig(ConfigFile config) { Config = config; GuardAgainstInvalidZNetSceneSpam = config.Bind<bool>("Patches", "GuardAgainstInvalidZNetScene", true, ConfigHelpers.CreateConfigDescription("Allows you to customize what piece the raft initializes with. Admins only as this can be overpowered.", isAdmin: true, isAdvanced: true)); } } public class InvalidZNetScenePatch { [HarmonyPatch(typeof(ZNetScene), "RemoveObjects")] [HarmonyPrefix] private static bool RemoveObjects(ZNetScene __instance, List<ZDO> currentNearObjects, List<ZDO> currentDistantObjects) { byte b = (byte)((uint)Time.frameCount & 0xFFu); foreach (ZDO currentNearObject in currentNearObjects) { currentNearObject.TempRemoveEarmark = b; } foreach (ZDO currentDistantObject in currentDistantObjects) { currentDistantObject.TempRemoveEarmark = b; } __instance.m_tempRemoved.Clear(); foreach (ZNetView value in __instance.m_instances.Values) { if (Object.op_Implicit((Object)(object)value) && value.GetZDO().TempRemoveEarmark != b) { __instance.m_tempRemoved.Add(value); } } for (int i = 0; i < __instance.m_tempRemoved.Count; i++) { ZNetView val = __instance.m_tempRemoved[i]; if (Object.op_Implicit((Object)(object)val)) { ZDO zDO = val.GetZDO(); val.ResetZDO(); Object.Destroy((Object)(object)((Component)val).gameObject); if (!zDO.Persistent && zDO.IsOwner()) { ZDOMan.instance.DestroyZDO(zDO); } __instance.m_instances.Remove(zDO); } } return false; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { internal IgnoresAccessChecksToAttribute(string assemblyName) { } } }