using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using MonsterDB; using MonsterDB.Solution.Methods; using ServerSync; using TMPro; using UnityEngine; using UnityEngine.Networking; using UnityEngine.Rendering; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.BufferedDeserialization; using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; [assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")] [assembly: ComVisible(false)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCopyright("Copyright © 2026")] [assembly: AssemblyProduct("MonsterDB")] [assembly: AssemblyCompany("RustyMods")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = "")] [assembly: AssemblyDescription("")] [assembly: AssemblyTitle("MonsterDB")] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(8)] [assembly: AssemblyFileVersion("0.3.5")] [assembly: AssemblyConfiguration("")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.3.5.0")] [module: <308d27bf-7cfd-479f-b18b-64b6090a19b3>RefSafetyRules(11)] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class <64cf9182-2f81-4902-ae94-34c63181c9f0>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <64cf9182-2f81-4902-ae94-34c63181c9f0>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <64cf9182-2f81-4902-ae94-34c63181c9f0>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [Embedded] internal sealed class <5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContextAttribute : Attribute { public readonly byte Flag; public <5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class <308d27bf-7cfd-479f-b18b-64b6090a19b3>RefSafetyRulesAttribute : Attribute { public readonly int Version; public <308d27bf-7cfd-479f-b18b-64b6090a19b3>RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class UV { private static readonly Color DefaultBackgroundColor = new Color(0.15f, 0.15f, 0.15f, 1f); private static readonly Color DefaultLineColor = new Color(0.4f, 0.8f, 1f, 1f); public static void ExportMaps(Terminal context, string prefabId, string bkgHex = "", string lineHex = "") { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006a: 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_006c: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) GameObject prefab = PrefabManager.GetPrefab(prefabId); if (prefab == null) { context.LogWarning("Failed to find prefab: " + prefabId); return; } Color bgColor = (Color)(string.IsNullOrEmpty(bkgHex) ? default(Color) : bkgHex.FromHexOrRGBA(DefaultBackgroundColor)); Color lineColor = (Color)(string.IsNullOrEmpty(lineHex) ? default(Color) : lineHex.FromHexOrRGBA(DefaultLineColor)); MeshRenderer[] componentsInChildren = prefab.GetComponentsInChildren(); foreach (MeshRenderer val in componentsInChildren) { MeshFilter component = ((Component)val).GetComponent(); if (!((Object)(object)component == (Object)null) && !((Object)(object)component.sharedMesh == (Object)null)) { int width = 256; int height = 256; if ((Object)(object)((Renderer)val).material != (Object)null && (Object)(object)((Renderer)val).material.mainTexture != (Object)null) { width = ((Renderer)val).material.mainTexture.width; height = ((Renderer)val).material.mainTexture.height; } DrawAndExportUVMap(context, prefab, component.sharedMesh, width, height, lineColor, bgColor); } } SkinnedMeshRenderer[] componentsInChildren2 = prefab.GetComponentsInChildren(); foreach (SkinnedMeshRenderer val2 in componentsInChildren2) { if (!((Object)(object)val2.sharedMesh == (Object)null)) { int width2 = 256; int height2 = 256; if ((Object)(object)((Renderer)val2).material != (Object)null && (Object)(object)((Renderer)val2).material.mainTexture != (Object)null) { width2 = ((Renderer)val2).material.mainTexture.width; height2 = ((Renderer)val2).material.mainTexture.height; } DrawAndExportUVMap(context, prefab, val2.sharedMesh, width2, height2, lineColor, bgColor); } } } [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public static Texture2D DrawAndExportUVMap(Terminal context, GameObject prefab, Mesh mesh, int width, int height, Color lineColor = default(Color), Color bgColor = default(Color), [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] string outputPath = null) { //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009b: 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_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Expected O, but got Unknown //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: 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_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0121: 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_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0133: 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_0141: 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_0145: Unknown result type (might be due to invalid IL or missing references) if (!mesh.isReadable) { context.LogError("Mesh '" + ((Object)mesh).name + "' is not readable."); return null; } Vector2[] uv = mesh.uv; int[] triangles = mesh.triangles; if (uv == null || uv.Length == 0) { context.LogError("Mesh '" + ((Object)mesh).name + "' has no UV coordinates."); return null; } if (lineColor == default(Color)) { lineColor = DefaultLineColor; } if (bgColor == default(Color)) { bgColor = DefaultBackgroundColor; } Texture2D val = new Texture2D(width, height); Color[] array = (Color[])(object)new Color[width * height]; for (int i = 0; i < array.Length; i++) { array[i] = bgColor; } val.SetPixels(array); for (int j = 0; j < triangles.Length; j += 3) { Vector2 val2 = uv[triangles[j]]; Vector2 val3 = uv[triangles[j + 1]]; Vector2 val4 = uv[triangles[j + 2]]; DrawLine(val, val2, val3, lineColor, width, height); DrawLine(val, val3, val4, lineColor, width, height); DrawLine(val, val4, val2, lineColor, width, height); } val.Apply(); if (outputPath == null) { outputPath = Path.Combine(FileManager.ExportFolder, ((Object)prefab).name + "_" + ((Object)mesh).name + "_uv.png"); } File.WriteAllBytes(outputPath, ImageConversion.EncodeToPNG(val)); context.LogInfo("UV map saved to: " + outputPath); return val; } private static void DrawLine(Texture2D tex, Vector2 uvA, Vector2 uvB, Color color, int width, int height) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) int num = Mathf.RoundToInt(uvA.x * (float)(width - 1)); int num2 = Mathf.RoundToInt(uvA.y * (float)(height - 1)); int num3 = Mathf.RoundToInt(uvB.x * (float)(width - 1)); int num4 = Mathf.RoundToInt(uvB.y * (float)(height - 1)); int num5 = Mathf.Abs(num3 - num); int num6 = ((num < num3) ? 1 : (-1)); int num7 = Mathf.Abs(num4 - num2); int num8 = ((num2 < num4) ? 1 : (-1)); int num9 = ((num5 > num7) ? num5 : (-num7)) / 2; while (true) { if (num >= 0 && num < width && num2 >= 0 && num2 < height) { tex.SetPixel(num, num2, color); } if (num == num3 && num2 == num4) { break; } int num10 = num9; if (num10 > -num5) { num9 -= num7; num += num6; } if (num10 < num7) { num9 += num5; num2 += num8; } } } } namespace MonsterDB { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [PublicAPI] public static class AssetBundleManager { private static readonly Dictionary CachedBundles = new Dictionary(); [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public static T LoadAsset<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>(string assetBundle, string prefab) where T : Object { AssetBundle assetBundle2 = GetAssetBundle(assetBundle); return (assetBundle2 == null) ? default(T) : assetBundle2.LoadAsset(prefab); } public static AssetBundle GetAssetBundle(string fileName) { if (CachedBundles.TryGetValue(fileName, out var value)) { return value; } AssetBundle val = AssetBundle.GetAllLoadedAssetBundles().FirstOrDefault((Func)([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (AssetBundle b) => ((Object)b).name == fileName)); if (val != null) { CachedBundles[fileName] = val; return val; } Assembly executingAssembly = Assembly.GetExecutingAssembly(); string name = executingAssembly.GetManifestResourceNames().Single([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (string str) => str.EndsWith(fileName)); using Stream stream = executingAssembly.GetManifestResourceStream(name); AssetBundle val2 = AssetBundle.LoadFromStream(stream); CachedBundles[fileName] = val2; return val2; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class AnimalTameable : MonoBehaviour { [HarmonyPatch(typeof(BaseAI), "IdleMovement")] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] private static class AnimalAI_IdleMovement_Patch { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] private static bool Prefix(BaseAI __instance, float dt) { AnimalTameable animalTameable = default(AnimalTameable); if (!((Component)__instance).TryGetComponent(ref animalTameable)) { return true; } AnimalAI val = (AnimalAI)(object)((__instance is AnimalAI) ? __instance : null); if (val == null) { return true; } Tameable tameable = default(Tameable); if (!((Component)__instance).TryGetComponent(ref tameable)) { return true; } return !animalTameable.UpdateConsumeItem(__instance.m_character, val, tameable, dt); } } [HarmonyPatch(typeof(Tameable), "TamingUpdate")] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] private static class Tameable_TamingUpdate_Patch { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] private static void Postfix(Tameable __instance) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) if (ShouldPatchTameable(__instance) && !__instance.IsHungry()) { __instance.DecreaseRemainingTime(3f); if ((double)__instance.GetRemainingTime() <= 0.0) { __instance.Tame(); } else { __instance.m_sootheEffect.Create(((Component)__instance).transform.position, ((Component)__instance).transform.rotation, (Transform)null, 1f, -1); } } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] [HarmonyPatch(typeof(Tameable), "Tame")] private static class Tameable_Tame_Patch { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] private static void Postfix(Tameable __instance) { //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) //IL_004c: Unknown result type (might be due to invalid IL or missing references) if (ShouldPatchTameable(__instance)) { __instance.m_character.SetTamed(true); __instance.m_tamedEffect.Create(((Component)__instance).transform.position, ((Component)__instance).transform.rotation, (Transform)null, 1f, -1); Player closestPlayer = Player.GetClosestPlayer(((Component)__instance).transform.position, 30f); if (Object.op_Implicit((Object)(object)closestPlayer)) { ((Character)closestPlayer).Message((MessageType)2, __instance.m_character.m_name + " $hud_tamedone", 0, (Sprite)null); } } } } public List m_consumeItems = new List(); public float m_consumeRange = 2f; public float m_consumeSearchRange = 5f; public float m_consumeSearchInterval = 10f; public EffectList m_consumeItemEffects = new EffectList(); public float m_consumeSearchTimer; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public ItemDrop m_consumeTarget; private static readonly int Consume = Animator.StringToHash("consume"); private static bool ShouldPatchTameable(Tameable __instance) { return __instance.m_nview.IsValid() && __instance.m_nview.IsOwner() && !__instance.IsTamed() && Object.op_Implicit((Object)(object)__instance.m_character) && !Object.op_Implicit((Object)(object)__instance.m_monsterAI); } public bool UpdateConsumeItem(Character character, AnimalAI animalAI, Tameable tameable, float dt) { //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) if (m_consumeItems.Count == 0) { return false; } m_consumeSearchTimer += dt; if (m_consumeSearchTimer > m_consumeSearchInterval) { m_consumeSearchTimer = 0f; if (!tameable.IsHungry()) { return false; } ItemDrop consumeTarget = FindClosestConsumableItem(animalAI, m_consumeSearchRange); m_consumeTarget = consumeTarget; } if (!Object.op_Implicit((Object)(object)m_consumeTarget)) { return false; } if (((BaseAI)animalAI).MoveTo(dt, ((Component)m_consumeTarget).transform.position, m_consumeRange, false)) { ((BaseAI)animalAI).LookAt(((Component)m_consumeTarget).transform.position); if (((BaseAI)animalAI).IsLookingAt(((Component)m_consumeTarget).transform.position, 20f, false) && m_consumeTarget.RemoveOne()) { tameable.OnConsumedItem(m_consumeTarget); m_consumeItemEffects.Create(((Component)character).transform.position, Quaternion.identity, (Transform)null, 1f, -1); character.m_animator.SetTrigger(Consume); m_consumeTarget = null; } } return true; } [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public ItemDrop FindClosestConsumableItem(AnimalAI animalAI, float maxRange) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: 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) if (MonsterAI.m_itemMask == 0) { MonsterAI.m_itemMask = LayerMask.GetMask(new string[1] { "item" }); } Collider[] array = (Collider[])(object)new Collider[20]; int num = Physics.OverlapSphereNonAlloc(((Component)animalAI).transform.position, maxRange, array, MonsterAI.m_itemMask); ItemDrop val = null; float num2 = 999999f; for (int i = 0; i < num; i++) { Collider val2 = array[i]; if ((Object)(object)val2 == (Object)null || !Object.op_Implicit((Object)(object)val2.attachedRigidbody)) { continue; } ItemDrop component = ((Component)val2.attachedRigidbody).GetComponent(); if (!((Object)(object)component == (Object)null) && ((Component)component).GetComponent().IsValid() && CanConsume(component.m_itemData)) { float num3 = Vector3.Distance(((Component)component).transform.position, ((Component)animalAI).transform.position); if ((Object)(object)val == (Object)null || num3 < num2) { val = component; num2 = num3; } } } return ((Object)(object)val != (Object)null && ((BaseAI)animalAI).HavePath(((Component)val).transform.position)) ? val : null; } public bool CanConsume(ItemData item) { if (m_consumeItems.Count == 0) { return false; } foreach (ItemDrop consumeItem in m_consumeItems) { if (consumeItem.m_itemData.m_shared.m_name == item.m_shared.m_name) { return true; } } return false; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class GrowUpText { private static ConfigEntry addGrowUpText; public static void Setup() { addGrowUpText = ConfigManager.config("Grow Up", "Add Progress Text", Toggle.Off, "If on, will add progress text on character hover"); } public static bool AddGrowUpText() { return addGrowUpText.Value == Toggle.On; } public static string GetGrowthPercentageText(this Growup __instance) { if ((Object)(object)__instance.m_baseAI == (Object)null) { return "$hud_growup_maturing 0%"; } double totalSeconds = __instance.m_baseAI.GetTimeSinceSpawned().TotalSeconds; double num = totalSeconds / (double)__instance.m_growTime * 100.0; return $"$hud_growup_maturing {num:0}%"; } } public static class ProcreateText { [HarmonyPatch(typeof(Tameable), "GetStatusString")] private static class Tameable_GetStatusString { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] private static void Postfix(Tameable __instance, ref string __result) { Procreation val = default(Procreation); if (AddProgressText() && __instance.IsTamed() && ((Component)__instance).TryGetComponent(ref val)) { if (val.IsPregnant()) { __result += ", $hud_procreate_pregnant"; return; } int lovePoints = val.GetLovePoints(); float num = (float)lovePoints / (float)val.m_requiredLovePoints * 100f; __result += $", $hud_procreate_bonding {num}%"; } } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] private static ConfigEntry addProcreateProgressText; public static void Setup() { addProcreateProgressText = ConfigManager.config("Procreation", "Add Progress Text", Toggle.Off, "If on, will add procreation progress info to hover text"); } private static bool AddProgressText() { return addProcreateProgressText.Value == Toggle.On; } } [HarmonyPatch(typeof(Character), "GetHoverText")] public static class Character_GetHoverText_Patch { private static bool _valharvestInstalled => Chainloader.PluginInfos.ContainsKey("com.frenvius.Valharvest"); [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] private static bool Prefix(Character __instance, ref string __result) { if (_valharvestInstalled) { return true; } if (!__instance.m_nview.IsValid()) { return true; } StringBuilder stringBuilder = new StringBuilder(); Tameable val = default(Tameable); Growup _instance2 = default(Growup); if (((Component)__instance).TryGetComponent(ref val)) { stringBuilder.Append(val.GetName()); if (val.IsTamed()) { stringBuilder.AppendFormat(" ( {0}, {1}", "$hud_tame", val.GetStatusString()); Growup _instance = default(Growup); if (((Component)__instance).TryGetComponent(ref _instance) && GrowUpText.AddGrowUpText()) { stringBuilder.Append(", " + _instance.GetGrowthPercentageText()); } stringBuilder.Append(" )"); stringBuilder.Append("\n[$KEY_Use] $hud_pet"); bool flag = ZInput.IsNonClassicFunctionality() && ZInput.IsGamepadActive(); stringBuilder.AppendFormat("\n[{0} + $KEY_Use] $hud_rename", flag ? "$KEY_AltKeys" : "$KEY_AltPlace"); Saddle saddle = default(Saddle); if (((Component)__instance).TryGetComponent(ref saddle) && (!saddle.HasSaddleItem() || saddle.HaveSaddle())) { saddle.GetHoverText(stringBuilder, flag); } } else { int tameness = val.GetTameness(); stringBuilder.AppendFormat(" ( {0}, {1} )", (tameness <= 0) ? "$hud_wild" : $"$hud_tameness {tameness}%", val.GetStatusString()); } } else if (((Component)__instance).TryGetComponent(ref _instance2) && GrowUpText.AddGrowUpText() && __instance.IsTamed()) { stringBuilder.Append(__instance.m_name + " ( " + _instance2.GetGrowthPercentageText() + " )"); } __result = Localization.instance.Localize(stringBuilder.ToString()); return false; } } [HarmonyPatch(typeof(Growup), "GrowUpdate")] public static class GrowUp_ConditioanlGrow_Patch { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] private static bool Prefix(Growup __instance) { if (!__instance.m_nview.IsValid() || !__instance.m_nview.IsOwner()) { return true; } Character val = default(Character); if (!((Component)__instance).TryGetComponent(ref val) || val.IsTamed()) { return true; } __instance.m_nview.GetZDO().Set(ZDOVars.s_spawnTime, ZNet.instance.GetTime().Ticks); return false; } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class Human : Humanoid { [CompilerGenerated] private sealed class d__20 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] private object <>2__current; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public string reloadAnimation; public float reloadTime; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public Human <>4__this; object IEnumerator.Current { [DebuggerHidden] [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__20(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>4__this.m_reloading = true; ((Character)<>4__this).m_zanim.SetBool(reloadAnimation, true); <>2__current = (object)new WaitForSeconds(reloadTime); <>1__state = 1; return true; case 1: <>1__state = -1; ((Character)<>4__this).m_zanim.SetTrigger(reloadAnimation + "_done"); ((Character)<>4__this).m_zanim.SetBool(reloadAnimation, false); <>2__current = <>4__this.m_weaponLoadedDelay; <>1__state = 2; return true; case 2: <>1__state = -1; <>4__this.m_weaponLoaded = true; <>4__this.m_reloadCoroutine = null; <>4__this.m_reloading = false; return false; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } public int m_modelIndex; public Vector3 m_skinColor; public Vector3 m_hairColor; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public int[] m_models; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public string[] m_skinColors; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public string[] m_hairColors; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public string[] m_beards; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public string[] m_hairs; public bool m_reloading; public bool m_weaponLoaded; private readonly WaitForSeconds m_weaponLoadedDelay = new WaitForSeconds(1f); [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] private Coroutine m_reloadCoroutine; public override void Start() { //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) ((Humanoid)this).Start(); BaseAI baseAI = ((Character)this).m_baseAI; MonsterAI val = (MonsterAI)(object)((baseAI is MonsterAI) ? baseAI : null); if (val != null) { val.m_onConsumedItem = (Action)Delegate.Combine(val.m_onConsumedItem, new Action(OnConsumeItem)); } if (((Character)this).m_nview.IsValid() && !((Character)this).m_nview.GetZDO().GetBool(ZDOVars.s_addedDefaultItems, false)) { if (m_models != null && m_models.Length != 0) { m_modelIndex = m_models[Random.Range(0, m_models.Length)]; } if (m_beards != null && m_beards.Length != 0) { base.m_beardItem = m_beards[Random.Range(0, m_beards.Length)]; } if (m_hairs != null && m_hairs.Length != 0) { base.m_hairItem = m_hairs[Random.Range(0, m_hairs.Length)]; } if (m_skinColors != null && m_skinColors.Length != 0) { string input = m_skinColors[Random.Range(0, m_skinColors.Length)]; m_skinColor = Utils.ColorToVec3(input.FromHexOrRGBA(Color.white)); } if (m_hairColors != null && m_hairColors.Length != 0) { string input2 = m_hairColors[Random.Range(0, m_hairColors.Length)]; m_hairColor = Utils.ColorToVec3(input2.FromHexOrRGBA(Color.black)); } ((Character)this).m_nview.GetZDO().Set(ZDOVars.s_addedDefaultItems, true); ((Humanoid)this).SetupVisEquipment(base.m_visEquipment, false); } } private void OnConsumeItem(ItemDrop item) { string trigger = (item.m_itemData.m_shared.m_isDrink ? "emote_drink" : "eat"); ((Character)this).m_animator.SetTrigger(trigger); } public override void SetupVisEquipment(VisEquipment visEq, bool isRagdoll) { //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) if (!isRagdoll) { visEq.SetLeftItem((base.m_leftItem != null) ? ((Object)base.m_leftItem.m_dropPrefab).name : "", (base.m_leftItem != null) ? base.m_leftItem.m_variant : 0); visEq.SetRightItem((base.m_rightItem != null) ? ((Object)base.m_rightItem.m_dropPrefab).name : ""); } visEq.SetChestItem((base.m_chestItem != null) ? ((Object)base.m_chestItem.m_dropPrefab).name : ""); visEq.SetLegItem((base.m_legItem != null) ? ((Object)base.m_legItem.m_dropPrefab).name : ""); visEq.SetHelmetItem((base.m_helmetItem != null) ? ((Object)base.m_helmetItem.m_dropPrefab).name : ""); visEq.SetShoulderItem((base.m_shoulderItem != null) ? ((Object)base.m_shoulderItem.m_dropPrefab).name : "", (base.m_shoulderItem != null) ? base.m_shoulderItem.m_variant : 0); visEq.SetUtilityItem((base.m_utilityItem != null) ? ((Object)base.m_utilityItem.m_dropPrefab).name : ""); visEq.SetTrinketItem((base.m_trinketItem != null) ? ((Object)base.m_trinketItem.m_dropPrefab).name : ""); visEq.SetBeardItem(base.m_beardItem); visEq.SetHairItem(base.m_hairItem); visEq.SetSkinColor(m_skinColor); visEq.SetHairColor(m_hairColor); visEq.SetModel(m_modelIndex); } public override float GetMaxEitr() { return 9999f; } public void LateUpdate() { if (base.m_currentAttack != null && base.m_currentAttack.m_loopingAttack) { int num = Mathf.CeilToInt(base.m_lastCombatTimer / base.m_currentAttack.m_burstInterval); if (num > 10) { base.m_currentAttack.Stop(); base.m_previousAttack = base.m_currentAttack; base.m_currentAttack = null; } } } public override void ResetLoadedWeapon() { m_weaponLoaded = false; StartWeaponReload(); } public override bool IsWeaponLoaded() { if (!m_weaponLoaded) { StartWeaponReload(); } return m_weaponLoaded; } public void StartWeaponReload() { if (m_reloading || m_weaponLoaded) { return; } ItemData currentWeapon = ((Humanoid)this).GetCurrentWeapon(); if (currentWeapon != null && currentWeapon.m_shared.m_attack.m_requiresReload) { if (m_reloadCoroutine != null) { ((MonoBehaviour)this).StopCoroutine(m_reloadCoroutine); m_reloadCoroutine = null; } m_reloadCoroutine = ((MonoBehaviour)this).StartCoroutine(ReloadRoutine(currentWeapon.m_shared.m_attack.m_reloadAnimation, currentWeapon.m_shared.m_attack.m_reloadTime)); } } [IteratorStateMachine(typeof(d__20))] private IEnumerator ReloadRoutine(string reloadAnimation, float reloadTime) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__20(0) { <>4__this = this, reloadAnimation = reloadAnimation, reloadTime = reloadTime }; } } public static class Humanoid_Patches { [HarmonyPatch(typeof(Humanoid), "EquipItem")] private static class Humanoid_EquipItem_Patch { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] private static void Prefix(Humanoid __instance, ItemData item) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Invalid comparison between Unknown and I4 if (!((Character)__instance).IsPlayer() && (int)item.m_shared.m_itemType == 10 && !((Object)(object)item.m_dropPrefab == (Object)null)) { string prefabName = Utils.GetPrefabName(item.m_dropPrefab); if (Utils.CustomStartsWith(prefabName, "Beard")) { __instance.SetBeard(prefabName); } else if (Utils.CustomStartsWith(prefabName, "Hair")) { __instance.SetHair(prefabName); } } } } } [HarmonyPatch(typeof(Hud), "UpdateMount")] public static class Hud_UpdateMount { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] private static bool Prefix(Hud __instance, Player player, float dt) { Saddle saddle = player.GetDoodadController() as Saddle; if ((Object)(object)saddle == (Object)null) { return true; } Character character = saddle.GetCharacter(); __instance.m_mountPanel.SetActive(true); __instance.m_mountIcon.overrideSprite = saddle.m_mountIcon; __instance.m_mountHealthBarSlow.SetValue(character.GetHealthPercentage()); __instance.m_mountHealthBarFast.SetValue(character.GetHealthPercentage()); ((TMP_Text)__instance.m_mountHealthText).text = StringExtensionMethods.ToFastString(Mathf.CeilToInt(character.GetHealth())); float stamina = saddle.GetStamina(); float maxStamina = saddle.GetMaxStamina(); __instance.m_mountStaminaBar.SetValue(stamina / maxStamina); ((TMP_Text)__instance.m_mountStaminaText).text = StringExtensionMethods.ToFastString(Mathf.CeilToInt(stamina)); ((TMP_Text)__instance.m_mountNameText).text = character.GetHoverName() + " ( " + Localization.instance.Localize(saddle.GetTameable().GetStatusString()) + " )"; return false; } } [HarmonyPatch(typeof(Player), "IsRiding")] public static class Player_IsRiding { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] private static void Postfix(Player __instance, ref bool __result) { __result |= __instance.m_doodadController != null && __instance.m_doodadController.IsValid() && __instance.m_doodadController is Saddle; } } [HarmonyPatch(typeof(Player), "SetControls")] public static class Player_SetControls_SaddlePatch { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] private static bool Prefix(Player __instance, Vector3 movedir, bool attack, bool secondaryAttack, bool block, bool jump, bool run, bool autoRun) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (!(__instance.m_doodadController is Saddle saddle) || !saddle.IsValid()) { return true; } saddle.ApplyCustomControls(movedir, ((Character)__instance).m_lookDir, run, autoRun, block, attack, secondaryAttack, jump); return false; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class Saddle : MonoBehaviour, Interactable, Hoverable, IDoodadController { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] [HarmonyPatch(typeof(Tameable), "UseItem")] public static class Tameable_UseItem { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] private static bool Prefix(Tameable __instance, Humanoid user, ItemData item, ref bool __result) { Saddle saddle = default(Saddle); if (!((Component)__instance).TryGetComponent(ref saddle)) { return true; } __result = saddle.UseItem(user, item); return false; } } [HarmonyPatch(typeof(BaseAI), "UpdateAI")] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] public static class BaseAI_UpdateAI { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] private static bool Prefix(BaseAI __instance, float dt, ref bool __result) { Saddle saddle = default(Saddle); if (!((Component)__instance).TryGetComponent(ref saddle)) { return true; } if (!__instance.m_nview.IsValid() || !__instance.m_nview.IsOwner()) { return true; } if (!__instance.m_character.IsTamed()) { return true; } if (saddle.UpdateRiding(dt)) { __instance.UpdateTakeoffLanding(dt); if ((double)__instance.m_jumpInterval > 0.0) { __instance.m_jumpTimer += dt; } if ((double)__instance.m_randomMoveUpdateTimer > 0.0) { __instance.m_randomMoveUpdateTimer -= dt; } __instance.UpdateRegeneration(dt); __instance.m_timeSinceHurt += dt; __result = false; return false; } return true; } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] [HarmonyPatch(typeof(Tameable), "Interact")] public static class Tameable_Interact { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] private static bool Prefix(Tameable __instance, Humanoid user, bool hold, bool alt, ref bool __result) { Saddle saddle = default(Saddle); if (!((Component)__instance).TryGetComponent(ref saddle)) { return true; } if (saddle.HasSaddleItem() && !saddle.HaveSaddle()) { return true; } if (alt || hold) { return true; } if (ZInput.GetKey((KeyCode)308, true) || ZInput.GetKeyDown((KeyCode)308, true) || ZInput.GetButton("JoyLTrigger")) { __result = saddle.Interact(user, repeat: false, alt: false); return false; } if (ZInput.GetKey((KeyCode)306, true) || ZInput.GetKeyDown((KeyCode)306, true) || ZInput.GetButton("JoyButtonB")) { __result = saddle.Interact(user, repeat: false, alt: true); return false; } return true; } } public string m_hoverText = ""; public float m_maxUseRange = 10f; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public Transform m_attachPoint; public Vector3 m_attachOffset; public GameObject m_attachParent; public Vector3 m_detachOffset = new Vector3(0f, 0.5f, 0f); public string m_attachAnimation = "attach_chair"; public float m_maxStamina = 100f; public float m_runStaminaDrain = 10f; public float m_swimStaminaDrain = 10f; public float m_staminaRegen = 10f; public float m_staminaRegenHungry = 10f; public EffectList m_drownEffects = new EffectList(); [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public Sprite m_mountIcon; public Vector3 m_controlDir; public Speed m_speed; public float m_rideSkill; public float m_staminaRegenTimer; public float m_drownDamageTimer; public float m_raiseSkillTimer; public Character m_character = null; public ZNetView m_nview = null; public Tameable m_tambable = null; public BaseAI m_baseAI = null; public bool m_haveValidUser; public const string rideKey = "JoyLTrigger"; private const string removeKey = "JoyButtonB"; public void Awake() { m_character = ((Component)this).GetComponent(); m_nview = ((Component)this).GetComponent(); m_tambable = ((Component)this).GetComponent(); m_baseAI = ((Component)this).GetComponent(); m_nview.Register("RequestControl", (Action)RPC_RequestControl); m_nview.Register("ReleaseControl", (Action)RPC_ReleaseControl); m_nview.Register("RequestRespons", (Action)RPC_RequestRespons); m_nview.Register("RemoveSaddle", (Action)RPC_RemoveSaddle); m_nview.Register("Controls", (Action)RPC_Controls); m_nview.Register("AddSaddle", (Action)RPC_AddSaddle); } public void Start() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("attach"); val.transform.SetParent(((Object)(object)m_attachParent != (Object)null) ? m_attachParent.transform : ((Component)this).transform); val.transform.localPosition = m_attachOffset; val.transform.rotation = Quaternion.identity; m_attachPoint = val.transform; } public void Restart() { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)m_attachPoint != (Object)null) { m_attachPoint.SetParent(((Object)(object)m_attachParent != (Object)null) ? m_attachParent.transform : ((Component)this).transform); m_attachPoint.localPosition = m_attachOffset; m_attachPoint.rotation = Quaternion.identity; } } public bool IsValid() { return Object.op_Implicit((Object)(object)this) && (Object)(object)m_attachPoint != (Object)null; } public bool UseItem(Humanoid user, ItemData item) { if (!m_nview.IsValid() || (Object)(object)m_tambable.m_saddleItem == (Object)null || !m_tambable.IsTamed() || item.m_shared.m_name != m_tambable.m_saddleItem.m_itemData.m_shared.m_name) { return false; } if (HaveSaddle()) { ((Character)user).Message((MessageType)2, m_tambable.GetHoverName() + " $hud_saddle_already", 0, (Sprite)null); } else { m_nview.InvokeRPC("AddSaddle", Array.Empty()); user.GetInventory().RemoveOneItem(item); ((Character)user).Message((MessageType)2, m_tambable.GetHoverName() + " $hud_saddle_ready", 0, (Sprite)null); } return true; } public void FixedUpdate() { if (!m_nview.IsValid()) { return; } CalculateHaveValidUser(); if (m_character.IsTamed()) { if (IsLocalUser()) { UpdateRidingSkill(Time.fixedDeltaTime); } if (m_nview.IsOwner()) { float fixedDeltaTime = Time.fixedDeltaTime; UpdateStamina(fixedDeltaTime); UpdateDrown(fixedDeltaTime); } } } public void LateUpdate() { if (HaveValidUser()) { UpdateAttachRotation(); } } public void UpdateDrown(float dt) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Expected O, but got Unknown //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_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) if (m_character.IsSwimming() && !m_character.IsOnGround() && !HaveStamina()) { m_drownDamageTimer += dt; if (!((double)m_drownDamageTimer <= 1.0)) { m_drownDamageTimer = 0f; float damage = Mathf.Ceil(m_character.GetMaxHealth() / 20f); m_character.Damage(new HitData { m_damage = { m_damage = damage }, m_point = m_character.GetCenterPoint(), m_dir = Vector3.down, m_pushForce = 10f, m_hitType = (HitType)4 }); EffectList drownEffects = m_drownEffects; Vector3 position = ((Component)this).transform.position; position.y = m_character.GetLiquidLevel(); drownEffects.Create(position, ((Component)this).transform.rotation, (Transform)null, 1f, -1); } } } public bool UpdateRiding(float dt) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Invalid comparison between Unknown and I4 //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Invalid comparison between Unknown and I4 //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Invalid comparison between Unknown and I4 //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Invalid comparison between Unknown and I4 //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Invalid comparison between Unknown and I4 //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Invalid comparison between Unknown and I4 if (!m_character.IsTamed() || !HaveValidUser() || (int)m_speed == 0 || (double)((Vector3)(ref m_controlDir)).magnitude == 0.0) { return false; } bool flag = HaveStamina(); if (m_character.IsFlying() && !flag && m_character.CanToggleFly()) { m_character.Land(); } if ((int)m_speed == 1 || (int)m_speed == 2) { if ((int)m_speed == 2 && !flag) { m_speed = (Speed)1; } m_baseAI.MoveTowards(m_controlDir, (int)m_speed == 2); float num = Mathf.Lerp(1f, 0.5f, GetRiderSkill()); if (m_character.IsSwimming() || m_character.IsFlying()) { UseStamina(m_swimStaminaDrain * num * dt); } else if ((int)m_speed == 2) { UseStamina(m_runStaminaDrain * num * dt); } } else if ((int)m_speed == 3) { m_baseAI.StopMoving(); m_character.SetRun(false); m_baseAI.LookTowards(m_controlDir); } m_baseAI.ResetRandomMovement(); return true; } public bool HasSaddleItem() { return (Object)(object)m_tambable.m_saddleItem != (Object)null; } public bool HaveSaddle() { return m_nview.IsValid() && m_nview.GetZDO().GetBool(ZDOVars.s_haveSaddleHash, false); } public void RPC_AddSaddle(long sender) { if (m_nview.IsOwner() && !HaveSaddle()) { m_nview.GetZDO().Set(ZDOVars.s_haveSaddleHash, true); m_nview.InvokeRPC(ZNetView.Everybody, "SetSaddle", new object[1] { true }); } } public bool DropSaddle(Vector3 userPoint) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) if (!HaveSaddle()) { return false; } m_nview.GetZDO().Set(ZDOVars.s_haveSaddleHash, false); m_nview.InvokeRPC(ZNetView.Everybody, "SetSaddle", new object[1] { false }); SpawnSaddle(userPoint - ((Component)this).transform.position); return true; } public void SpawnSaddle(Vector3 flyDirection) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) Rigidbody component = Object.Instantiate(((Component)m_tambable.m_saddleItem).gameObject, ((Component)this).transform.TransformPoint(m_tambable.m_dropSaddleOffset), Quaternion.identity).GetComponent(); if (Object.op_Implicit((Object)(object)component)) { Vector3 val = Vector3.up; if ((double)((Vector3)(ref flyDirection)).magnitude > 0.10000000149011612) { flyDirection.y = 0f; ((Vector3)(ref flyDirection)).Normalize(); val += flyDirection; } component.AddForce(val * m_tambable.m_dropItemVel, (ForceMode)2); } } public string GetHoverText() { if (!m_nview.IsValid()) { return ""; } StringBuilder stringBuilder = new StringBuilder(); GetHoverText(stringBuilder, ZInput.IsNonClassicFunctionality() && ZInput.IsGamepadActive()); return Localization.instance.Localize(stringBuilder.ToString()); } public void GetHoverText(StringBuilder sb, bool gamepad) { sb.AppendFormat("\n[{0} + $KEY_Use] $hud_ride", gamepad ? ZInput.instance.GetBoundKeyString("JoyLTrigger", false) : "$button_lalt"); if (HasSaddleItem()) { sb.AppendFormat("\n[{0} + $KEY_Use] $hud_saddle_remove", gamepad ? ZInput.instance.GetBoundKeyString("JoyButtonB", false) : "$button_lctrl"); } } public string GetHoverName() { return Localization.instance.Localize(m_hoverText); } public bool Interact(Humanoid character, bool repeat, bool alt) { //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) if (repeat || !m_nview.IsValid() || !InUseDistance(character) || !m_character.IsTamed()) { return false; } Player val = (Player)(object)((character is Player) ? character : null); if ((Object)(object)val == (Object)null) { return false; } if (alt && HasSaddleItem()) { m_nview.InvokeRPC("RemoveSaddle", new object[1] { ((Component)character).transform.position }); return true; } ZNetView nview = m_nview; object[] array = new object[1]; ZDOID zDOID = ((Character)val).GetZDOID(); array[0] = ((ZDOID)(ref zDOID)).UserID; nview.InvokeRPC("RequestControl", array); return false; } public Character GetCharacter() { return m_character; } public Tameable GetTameable() { return m_tambable; } public void ApplyCustomControls(Vector3 moveDir, Vector3 lookDir, bool run, bool autoRun, bool block, bool attack, bool attackSecondary, bool jump) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Player.m_localPlayer == (Object)null) { return; } if (jump) { if (m_character.GetBaseAI().m_randomFly || m_character.CanToggleFly()) { if (m_character.IsFlying()) { m_character.Land(); } else { m_character.TakeOff(); } } else { m_character.Jump(false); } } ApplyControlls(moveDir, lookDir, run, autoRun, block); BaseAI baseAI = m_character.GetBaseAI(); MonsterAI val = (MonsterAI)(object)((baseAI is MonsterAI) ? baseAI : null); if (val == null) { return; } Character character = m_character; Humanoid val2 = (Humanoid)(object)((character is Humanoid) ? character : null); if (val2 != null && (attack || attackSecondary)) { List availableAttacks = val2.GetAvailableAttacks(); if (availableAttacks.Count > 0) { ItemData val3 = availableAttacks[Random.Range(0, availableAttacks.Count)]; val2.EquipItem(val3, true); } val.DoAttack((Character)null, false); } } public void ApplyControlls(Vector3 moveDir, Vector3 lookDir, bool run, bool autoRun, bool block) { //IL_002a: 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_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: 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_00f1: 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_0100: Expected I4, but got Unknown //IL_00ce: 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) if ((Object)(object)Player.m_localPlayer == (Object)null) { return; } float skillFactor = ((Character)Player.m_localPlayer).GetSkills().GetSkillFactor((SkillType)110); Speed val = (Speed)4; Vector3 val2 = Vector3.zero; if (run || block || moveDir.z > 0.5f) { val2 = lookDir; if (!m_character.IsFlying()) { val2.y = 0f; } if (((Vector3)(ref val2)).sqrMagnitude > 0f) { ((Vector3)(ref val2)).Normalize(); } } if (run) { val = (Speed)2; } else if (moveDir.z > 0.5f) { val = (Speed)1; } else if (moveDir.z < -0.5f) { val = (Speed)0; } else if (block) { val = (Speed)3; } m_nview.InvokeRPC("Controls", new object[3] { val2, (int)val, skillFactor }); } public void RPC_Controls(long sender, Vector3 rideDir, int rideSpeed, float skill) { //IL_001d: 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_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) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Invalid comparison between Unknown and I4 //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Invalid comparison between Unknown and I4 //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Invalid comparison between Unknown and I4 //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) if (!m_nview.IsOwner()) { return; } m_rideSkill = skill; if (rideDir != Vector3.zero) { m_controlDir = rideDir; } switch (rideSpeed) { case 3: if ((int)m_speed == 1 || (int)m_speed == 2) { return; } break; case 4: if ((int)m_speed == 3) { m_speed = (Speed)0; } return; } m_speed = (Speed)rideSpeed; } public void UpdateRidingSkill(float dt) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Invalid comparison between Unknown and I4 m_raiseSkillTimer += dt; if (!((double)m_raiseSkillTimer <= 1.0)) { m_raiseSkillTimer = 0f; if ((int)m_speed == 2) { ((Character)Player.m_localPlayer).RaiseSkill((SkillType)110, 1f); } } } public void ResetControlls() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) m_controlDir = Vector3.zero; m_speed = (Speed)0; m_rideSkill = 0f; } public Component GetControlledComponent() { return (Component)(object)m_character; } public Vector3 GetPosition() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return ((Component)this).transform.position; } public void RPC_RemoveSaddle(long sender, Vector3 userPoint) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (m_nview.IsOwner() && !HaveValidUser()) { DropSaddle(userPoint); } } public void RPC_RequestControl(long sender, long playerID) { if (m_nview.IsOwner()) { CalculateHaveValidUser(); if (GetUser() == playerID || !HaveValidUser()) { UpdateAttachRotation(); m_nview.GetZDO().Set(ZDOVars.s_user, playerID); ResetControlls(); m_nview.InvokeRPC(sender, "RequestRespons", new object[1] { true }); m_nview.GetZDO().SetOwner(sender); } else { m_nview.InvokeRPC(sender, "RequestRespons", new object[1] { false }); } } } public void UpdateAttachRotation() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)m_attachPoint == (Object)null)) { Vector3 forward = ((Component)this).transform.forward; forward.y = 0f; if (!(((Vector3)(ref forward)).sqrMagnitude < 0.0001f)) { ((Vector3)(ref forward)).Normalize(); m_attachPoint.rotation = Quaternion.LookRotation(forward, Vector3.up); } } } public bool HaveValidUser() { return m_haveValidUser; } public void CalculateHaveValidUser() { //IL_004c: 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) m_haveValidUser = false; long user = GetUser(); if (user == 0) { return; } List allCharacterZDOS = ZNet.instance.GetAllCharacterZDOS(); for (int i = 0; i < allCharacterZDOS.Count; i++) { ZDO val = allCharacterZDOS[i]; if (((ZDOID)(ref val.m_uid)).UserID == user) { m_haveValidUser = Vector3.Distance(val.GetPosition(), ((Component)this).transform.position) < m_maxUseRange; break; } } } public void RPC_ReleaseControl(long sender, long playerID) { if (m_nview.IsOwner() && GetUser() == playerID) { m_nview.GetZDO().Set(ZDOVars.s_user, 0L); ResetControlls(); } } public void RPC_RequestRespons(long sender, bool granted) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)Player.m_localPlayer)) { if (granted && (Object)(object)m_attachPoint != (Object)null) { Player.m_localPlayer.StartDoodadControl((IDoodadController)(object)this); ((Character)Player.m_localPlayer).AttachStart(m_attachPoint, ((Component)this).gameObject, false, false, false, m_attachAnimation, m_detachOffset, (Transform)null); } else { ((Character)Player.m_localPlayer).Message((MessageType)2, "$msg_inuse", 0, (Sprite)null); } } } public void OnUseStop(Player player) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) if (m_nview.IsValid()) { ZNetView nview = m_nview; object[] array = new object[1]; ZDOID zDOID = ((Character)player).GetZDOID(); array[0] = ((ZDOID)(ref zDOID)).UserID; nview.InvokeRPC("ReleaseControl", array); ((Character)player).AttachStop(); } } public bool IsLocalUser() { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)Player.m_localPlayer)) { return false; } long user = GetUser(); int result; if (user != 0L) { ZDOID zDOID = ((Character)Player.m_localPlayer).GetZDOID(); result = ((user == ((ZDOID)(ref zDOID)).UserID) ? 1 : 0); } else { result = 0; } return (byte)result != 0; } public long GetUser() { return ((Object)(object)m_nview == (Object)null || !m_nview.IsValid()) ? 0 : m_nview.GetZDO().GetLong(ZDOVars.s_user, 0L); } public bool InUseDistance(Humanoid human) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)m_attachPoint == (Object)null) { return false; } return (double)Vector3.Distance(((Component)human).transform.position, m_attachPoint.position) < (double)m_maxUseRange; } public void UseStamina(float v) { if ((double)v != 0.0 && m_nview.IsValid() && m_nview.IsOwner()) { float num = GetStamina() - v; if ((double)num < 0.0) { num = 0f; } SetStamina(num); m_staminaRegenTimer = 1f; } } public bool HaveStamina(float amount = 0f) { return m_nview.IsValid() && GetStamina() > amount; } public float GetStamina() { return ((Object)(object)m_nview == (Object)null || m_nview.GetZDO() == null) ? 0f : m_nview.GetZDO().GetFloat(ZDOVars.s_stamina, GetMaxStamina()); } public void SetStamina(float stamina) { m_nview.GetZDO().Set(ZDOVars.s_stamina, stamina); } public float GetMaxStamina() { return m_maxStamina; } public void UpdateStamina(float dt) { m_staminaRegenTimer -= dt; if (!(m_staminaRegenTimer > 0f) && !m_character.InAttack() && !m_character.IsSwimming()) { float stamina = GetStamina(); float maxStamina = GetMaxStamina(); if (!(stamina >= maxStamina)) { float num = (m_tambable.IsHungry() ? m_staminaRegenHungry : m_staminaRegen); float num2 = 1f - stamina / maxStamina; float num3 = num + num2 * num; float num4 = stamina + num3 * dt; SetStamina(Mathf.Min(num4, maxStamina)); } } } public float GetRiderSkill() { return m_rideSkill; } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class CharacterData { public string ClonedFrom = ""; public string PrefabName = ""; public string Name = ""; public string Group = ""; public string Faction = ""; public bool Boss; public bool DoNotHideBossHUD; public string BossEvent = ""; public string DefeatSetGlobalKey = ""; public bool AISkipTarget; public float CrouchSpeed; public float WalkSpeed; public float Speed; public float TurnSpeed; public float RunSpeed; public float RunTurnSpeed; public float FlySlowSpeed; public float FlyFastSpeed; public float FlyTurnSpeed; public float Acceleration; public float JumpForce; public float JumpForceForward; public float JumpForceTiredFactor; public float AirControl; public bool CanSwim; public float SwimDepth; public float SwimSpeed; public float SwimTurnSpeed; public float SwimAcceleration; public string GroundTilt = ""; public float GroundTiltSpeed; public bool Flying; public float JumpStaminaUsage; public bool DisableWhileSleeping; public bool TolerateWater; public bool TolerateFire; public bool TolerateSmoke; public bool TolerateTar; public float Health; public string BluntResistance = "Normal"; public string SlashResistance = "Normal"; public string PierceResistance = "Normal"; public string ChopResistance = "Normal"; public string PickaxeResistance = "Normal"; public string FireResistance = "Normal"; public string FrostResistance = "Normal"; public string LightningResistance = "Normal"; public string PoisonResistance = "Normal"; public string SpiritResistance = "Normal"; public bool StaggerWhenBlocked; public float StaggerDamageFactor; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref CharacterRef r) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_02ea: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0305: Unknown result type (might be due to invalid IL or missing references) //IL_0306: Unknown result type (might be due to invalid IL or missing references) //IL_0320: Unknown result type (might be due to invalid IL or missing references) //IL_0321: Unknown result type (might be due to invalid IL or missing references) //IL_033b: Unknown result type (might be due to invalid IL or missing references) //IL_033c: Unknown result type (might be due to invalid IL or missing references) //IL_0356: 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_0372: 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_038e: Unknown result type (might be due to invalid IL or missing references) //IL_0390: 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_03ac: Unknown result type (might be due to invalid IL or missing references) //IL_03c6: Unknown result type (might be due to invalid IL or missing references) //IL_03c8: Unknown result type (might be due to invalid IL or missing references) //IL_03e2: Unknown result type (might be due to invalid IL or missing references) //IL_03e4: Unknown result type (might be due to invalid IL or missing references) //IL_03fe: Unknown result type (might be due to invalid IL or missing references) //IL_0400: Unknown result type (might be due to invalid IL or missing references) //IL_0405: Unknown result type (might be due to invalid IL or missing references) //IL_0411: Expected O, but got I4 //IL_0306->IL0306: Incompatible stack types: O vs I4 //IL_0305->IL0306: Incompatible stack types: I4 vs O //IL_0305->IL0306: Incompatible stack types: O vs I4 if (r == null) { r = new CharacterRef(); } r.m_name = Name; r.m_group = Group; r.m_faction = FactionManager.GetFaction(Faction); r.m_boss = Boss; r.m_dontHideBossHud = DoNotHideBossHUD; r.m_bossEvent = BossEvent; r.m_defeatSetGlobalKey = DefeatSetGlobalKey; r.m_aiSkipTarget = AISkipTarget; r.m_crouchSpeed = CrouchSpeed; r.m_walkSpeed = WalkSpeed; r.m_speed = Speed; r.m_turnSpeed = TurnSpeed; r.m_runSpeed = RunSpeed; r.m_runTurnSpeed = RunTurnSpeed; r.m_acceleration = Acceleration; r.m_jumpForce = JumpForce; r.m_jumpForceForward = JumpForceForward; r.m_jumpForceTiredFactor = JumpForceTiredFactor; r.m_airControl = AirControl; r.m_jumpStaminaUsage = JumpStaminaUsage; r.m_flying = Flying; r.m_flySlowSpeed = FlySlowSpeed; r.m_flyFastSpeed = FlyFastSpeed; r.m_flyTurnSpeed = FlyTurnSpeed; r.m_canSwim = CanSwim; r.m_swimDepth = SwimDepth; r.m_swimSpeed = SwimSpeed; r.m_swimTurnSpeed = SwimTurnSpeed; r.m_swimAcceleration = SwimAcceleration; if (!string.IsNullOrEmpty(GroundTilt) && Enum.TryParse(GroundTilt, ignoreCase: true, out GroundTiltType result)) { r.m_groundTilt = result; } r.m_groundTiltSpeed = GroundTiltSpeed; r.m_disableWhileSleeping = DisableWhileSleeping; r.m_tolerateWater = TolerateWater; r.m_tolerateFire = TolerateFire; r.m_tolerateSmoke = TolerateSmoke; r.m_tolerateTar = TolerateTar; r.m_health = Health; r.m_staggerWhenBlocked = StaggerWhenBlocked; r.m_staggerDamageFactor = StaggerDamageFactor; object obj = r; DamageModifiers value = default(DamageModifiers); int num; if (Enum.TryParse(BluntResistance, ignoreCase: true, out DamageModifier result2)) { obj = result2; num = (int)obj; } else { num = 0; obj = num; num = (int)obj; } value.m_blunt = (DamageModifier)obj; num = (Enum.TryParse(PierceResistance, ignoreCase: true, out DamageModifier result3) ? ((int)result3) : 0); value.m_pierce = (DamageModifier)num; num = (Enum.TryParse(SlashResistance, ignoreCase: true, out DamageModifier result4) ? ((int)result4) : 0); value.m_slash = (DamageModifier)num; num = (Enum.TryParse(PickaxeResistance, ignoreCase: true, out DamageModifier result5) ? ((int)result5) : 0); value.m_pickaxe = (DamageModifier)num; num = (Enum.TryParse(ChopResistance, ignoreCase: true, out DamageModifier result6) ? ((int)result6) : 0); value.m_chop = (DamageModifier)num; num = (Enum.TryParse(FireResistance, ignoreCase: true, out DamageModifier result7) ? ((int)result7) : 0); value.m_fire = (DamageModifier)num; num = (Enum.TryParse(FrostResistance, ignoreCase: true, out DamageModifier result8) ? ((int)result8) : 0); value.m_frost = (DamageModifier)num; num = (Enum.TryParse(PoisonResistance, ignoreCase: true, out DamageModifier result9) ? ((int)result9) : 0); value.m_poison = (DamageModifier)num; num = (Enum.TryParse(LightningResistance, ignoreCase: true, out DamageModifier result10) ? ((int)result10) : 0); value.m_lightning = (DamageModifier)num; num = (Enum.TryParse(SpiritResistance, ignoreCase: true, out DamageModifier result11) ? ((int)result11) : 0); value.m_spirit = (DamageModifier)num; ((CharacterRef)num).m_damageModifiers = value; } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref HumanoidRef r) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_02ea: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0305: Unknown result type (might be due to invalid IL or missing references) //IL_0306: Unknown result type (might be due to invalid IL or missing references) //IL_0320: Unknown result type (might be due to invalid IL or missing references) //IL_0321: Unknown result type (might be due to invalid IL or missing references) //IL_033b: Unknown result type (might be due to invalid IL or missing references) //IL_033c: Unknown result type (might be due to invalid IL or missing references) //IL_0356: 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_0372: 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_038e: Unknown result type (might be due to invalid IL or missing references) //IL_0390: 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_03ac: Unknown result type (might be due to invalid IL or missing references) //IL_03c6: Unknown result type (might be due to invalid IL or missing references) //IL_03c8: Unknown result type (might be due to invalid IL or missing references) //IL_03e2: Unknown result type (might be due to invalid IL or missing references) //IL_03e4: Unknown result type (might be due to invalid IL or missing references) //IL_03fe: Unknown result type (might be due to invalid IL or missing references) //IL_0400: Unknown result type (might be due to invalid IL or missing references) //IL_0405: Unknown result type (might be due to invalid IL or missing references) //IL_0411: Expected O, but got I4 //IL_0306->IL0306: Incompatible stack types: O vs I4 //IL_0305->IL0306: Incompatible stack types: I4 vs O //IL_0305->IL0306: Incompatible stack types: O vs I4 if (r == null) { r = new HumanoidRef(); } r.m_name = Name; r.m_group = Group; r.m_faction = FactionManager.GetFaction(Faction); r.m_boss = Boss; r.m_dontHideBossHud = DoNotHideBossHUD; r.m_bossEvent = BossEvent; r.m_defeatSetGlobalKey = DefeatSetGlobalKey; r.m_aiSkipTarget = AISkipTarget; r.m_crouchSpeed = CrouchSpeed; r.m_walkSpeed = WalkSpeed; r.m_speed = Speed; r.m_turnSpeed = TurnSpeed; r.m_runSpeed = RunSpeed; r.m_runTurnSpeed = RunTurnSpeed; r.m_acceleration = Acceleration; r.m_jumpForce = JumpForce; r.m_jumpForceForward = JumpForceForward; r.m_jumpForceTiredFactor = JumpForceTiredFactor; r.m_airControl = AirControl; r.m_jumpStaminaUsage = JumpStaminaUsage; r.m_flying = Flying; r.m_flySlowSpeed = FlySlowSpeed; r.m_flyFastSpeed = FlyFastSpeed; r.m_flyTurnSpeed = FlyTurnSpeed; r.m_canSwim = CanSwim; r.m_swimDepth = SwimDepth; r.m_swimSpeed = SwimSpeed; r.m_swimTurnSpeed = SwimTurnSpeed; r.m_swimAcceleration = SwimAcceleration; if (!string.IsNullOrEmpty(GroundTilt) && Enum.TryParse(GroundTilt, ignoreCase: true, out GroundTiltType result)) { r.m_groundTilt = result; } r.m_groundTiltSpeed = GroundTiltSpeed; r.m_disableWhileSleeping = DisableWhileSleeping; r.m_tolerateWater = TolerateWater; r.m_tolerateFire = TolerateFire; r.m_tolerateSmoke = TolerateSmoke; r.m_tolerateTar = TolerateTar; r.m_health = Health; r.m_staggerWhenBlocked = StaggerWhenBlocked; r.m_staggerDamageFactor = StaggerDamageFactor; object obj = r; DamageModifiers value = default(DamageModifiers); int num; if (Enum.TryParse(BluntResistance, ignoreCase: true, out DamageModifier result2)) { obj = result2; num = (int)obj; } else { num = 0; obj = num; num = (int)obj; } value.m_blunt = (DamageModifier)obj; num = (Enum.TryParse(PierceResistance, ignoreCase: true, out DamageModifier result3) ? ((int)result3) : 0); value.m_pierce = (DamageModifier)num; num = (Enum.TryParse(SlashResistance, ignoreCase: true, out DamageModifier result4) ? ((int)result4) : 0); value.m_slash = (DamageModifier)num; num = (Enum.TryParse(PickaxeResistance, ignoreCase: true, out DamageModifier result5) ? ((int)result5) : 0); value.m_pickaxe = (DamageModifier)num; num = (Enum.TryParse(ChopResistance, ignoreCase: true, out DamageModifier result6) ? ((int)result6) : 0); value.m_chop = (DamageModifier)num; num = (Enum.TryParse(FireResistance, ignoreCase: true, out DamageModifier result7) ? ((int)result7) : 0); value.m_fire = (DamageModifier)num; num = (Enum.TryParse(FrostResistance, ignoreCase: true, out DamageModifier result8) ? ((int)result8) : 0); value.m_frost = (DamageModifier)num; num = (Enum.TryParse(PoisonResistance, ignoreCase: true, out DamageModifier result9) ? ((int)result9) : 0); value.m_poison = (DamageModifier)num; num = (Enum.TryParse(LightningResistance, ignoreCase: true, out DamageModifier result10) ? ((int)result10) : 0); value.m_lightning = (DamageModifier)num; num = (Enum.TryParse(SpiritResistance, ignoreCase: true, out DamageModifier result11) ? ((int)result11) : 0); value.m_spirit = (DamageModifier)num; ((CharacterRef)num).m_damageModifiers = value; } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class EffectInfo { public string PrefabName = ""; public bool Enabled; public int Variant = -1; public bool Attach; public bool Follow; public bool InheritParentRotation; public bool InheritParentScale; public bool MultiplyParentVisualScale; public bool RandomRotation; public bool Scale; public string ChildTransform = ""; public EffectListRef.EffectDataRef ToRef() { return new EffectListRef.EffectDataRef { m_prefab = PrefabName, m_variant = Variant, m_attach = Attach, m_follow = Follow, m_inheritParentRotation = InheritParentRotation, m_inheritParentScale = InheritParentScale, m_multiplyParentVisualScale = MultiplyParentVisualScale, m_randomRotation = RandomRotation, m_scale = Scale, m_childTransform = ChildTransform }; } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class AttackData { public string OriginalPrefab = ""; public string Name = ""; public string AnimationState = ""; public int ToolTier; public float Damage; public float Blunt; public float Slash; public float Pierce; public float Chop; public float Pickaxe; public float Fire; public float Frost; public float Lightning; public float Poison; public float Spirit; public float AttackForce; public bool Dodgeable; public bool Blockable; public string SpawnOnHit = ""; public string SpawnOnHitTerrain = ""; public string AttackStatusEffect = ""; public float AttackStatusEffectChance; public string AttackType = ""; public string AttackAnimation = ""; public bool HitTerrain; public bool HitFriendly; public float DamageMultiplier; public float DamageMultiplierPerMissingHP; public float DamageMultiplierByTotalHealthMissing; public float ForceMultiplier; public float StaggerMultiplier; public float RecoilPushback; public int SelfDamage; public string AttackOriginJoint = ""; public float AttackRange; public float AttackHeight; public float AttackOffset; public string SpawnOnTrigger = ""; public bool ToggleFlying; public bool Attach; public float AttackAngle; public float AttackRayWidth; public float MaxYAngle; public bool LowerDamagePerHit; public bool HitThroughWalls; public float AttackRangeMinimum; public float AttackInterval; public float AttackMaxAngle; public string Projectile = ""; public string MaterialOverride = ""; public void Set(ref ItemDataSharedRef r) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) r.m_prefab = Name; r.m_toolTier = ToolTier; r.m_damages = new DamageTypes { m_damage = Damage, m_blunt = Blunt, m_slash = Slash, m_pierce = Pierce, m_chop = Chop, m_pickaxe = Pickaxe, m_fire = Fire, m_frost = Frost, m_lightning = Lightning, m_poison = Poison, m_spirit = Spirit }; r.m_attackForce = AttackForce; r.m_dodgeable = Dodgeable; r.m_blockable = Blockable; if (r.m_attack == null) { r.m_attack = new AttackRef(); } r.m_attack.m_attackAnimation = AttackAnimation; r.m_attack.m_spawnOnHit = SpawnOnHit; r.m_attack.m_spawnOnTrigger = SpawnOnTrigger; r.m_attackStatusEffect = AttackStatusEffect; r.m_attackStatusEffectChance = AttackStatusEffectChance; if (Enum.TryParse(AttackType, ignoreCase: true, out AttackType result)) { r.m_attack.m_attackType = result; } r.m_attack.m_hitTerrain = HitTerrain; r.m_attack.m_damageMultiplier = DamageMultiplier; r.m_attack.m_damageMultiplierPerMissingHP = DamageMultiplierPerMissingHP; r.m_attack.m_damageMultiplierByTotalHealthMissing = DamageMultiplierByTotalHealthMissing; r.m_attack.m_forceMultiplier = ForceMultiplier; r.m_attack.m_staggerMultiplier = StaggerMultiplier; r.m_attack.m_recoilPushback = RecoilPushback; r.m_attack.m_selfDamage = SelfDamage; r.m_attack.m_attackOriginJoint = AttackOriginJoint; r.m_attack.m_attackRange = AttackRange; r.m_attack.m_attackHeight = AttackHeight; r.m_attack.m_attackOffset = AttackOffset; r.m_attack.m_toggleFlying = ToggleFlying; r.m_attack.m_attach = Attach; r.m_attack.m_attackAngle = AttackAngle; r.m_attack.m_attackRayWidth = AttackRayWidth; r.m_attack.m_maxYAngle = MaxYAngle; r.m_attack.m_lowerDamagePerHit = LowerDamagePerHit; r.m_attack.m_hitThroughWalls = HitThroughWalls; r.m_aiAttackRangeMin = AttackRangeMinimum; r.m_aiAttackInterval = AttackInterval; r.m_aiAttackMaxAngle = AttackMaxAngle; } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class RandomItemData { public string PrefabName = ""; public float Chance; public void Set(ref HumanoidRef.RandomItem r) { r.m_prefab = PrefabName; r.m_chance = Chance; } public HumanoidRef.RandomItem ToRef() { return new HumanoidRef.RandomItem { m_prefab = PrefabName, m_chance = Chance }; } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class ProjectileData { public string Name = ""; public float Damage; public float Blunt; public float Slash; public float Pierce; public float Chop; public float Pickaxe; public float Fire; public float Frost; public float Lightning; public float Poison; public float Spirit; public float AOE; public bool Dodgeable; public bool Blockable; public float AttackForce; public float BackstabBonus; public string StatusEffect = ""; public float HealthReturn; public bool CanHitWater; public float Duration; public float Gravity; public float Drag; public float RayRadius; public bool StayAfterHitStatic; public bool StayAfterHitDynamic; public float StayDuration; public bool Bounce; public bool BounceOnWater; public float BouncePower; public float BounceRoughness; public int MaxBounces; public float MinBounceVelocity; public bool RespawnItemOnHit; public bool SpawnOnDuration; public string SpawnOnHit = ""; public float SpawnOnHitChance; public int SpawnCount; public List RandomSpawnOnHit = new List(); public int RandomSpawnOnHitCount; public bool RandomSpawnSkipLava; public bool StaticHitOnly; public bool GroundHitOnly; public bool SpawnRandomRotation; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref ProjectileRef r) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) if (r != null) { r.m_damage = new DamageTypes { m_damage = Damage, m_blunt = Blunt, m_slash = Slash, m_pierce = Pierce, m_chop = Chop, m_pickaxe = Pickaxe, m_fire = Fire, m_frost = Frost, m_lightning = Lightning, m_poison = Poison, m_spirit = Spirit }; r.m_aoe = AOE; r.m_dodgeable = Dodgeable; r.m_blockable = Blockable; r.m_attackForce = AttackForce; r.m_backstabBonus = BackstabBonus; r.m_statusEffect = StatusEffect; r.m_healthReturn = HealthReturn; r.m_bounce = Bounce; r.m_bounceOnWater = BounceOnWater; r.m_respawnItemOnHit = RespawnItemOnHit; r.m_spawnOnHit = SpawnOnHit; r.m_spawnOnHitChance = SpawnOnHitChance; r.m_spawnCount = SpawnCount; r.m_randomSpawnOnHit = RandomSpawnOnHit; r.m_randomSpawnOnHitCount = RandomSpawnOnHitCount; r.m_randomSpawnSkipLava = RandomSpawnSkipLava; r.m_staticHitOnly = StaticHitOnly; r.m_groundHitOnly = GroundHitOnly; r.m_spawnRandomRotation = SpawnRandomRotation; } } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class MonsterAIData { public float ViewRange; public float ViewAngle; public float HearRange; public bool MistVision; public float IdleSoundInterval; public float IdleSoundChance; public string PathAgentType = ""; public float MoveMinAngle; public bool SmoothMovement; public bool SerpentMovement; public float SerpentTurnRadius; public float JumpInterval; public float RandomCircleInterval; public float RandomMoveInterval; public float RandomMoveRange; public bool RandomFly; public float ChanceToTakeOff; public float ChanceToLand; public float GroundDuration; public float AirDuration; public float MaxLandAltitude; public float TakeoffTime; public float FlyAltitudeMin; public float FlyAltitudeMax; public float FlyAbsMinAltitude; public bool AvoidFire; public bool AfraidOfFire; public bool AvoidWater; public bool AvoidLava; public bool SkipLavaTargets; public bool Aggravatable; public bool PassiveAggressive; public string SpawnMessage = ""; public string DeathMessage = ""; public string AlertedMessage = ""; public float FleeRange; public float FleeAngle; public float FleeInterval; public float AlertRange; public bool FleeIfHurtWhenTargetCannotBeReached; public float FleeUnreachableSinceAttack; public float FleeUnreachableSinceHurt; public bool FleeIfNotAlerted; public float FleeIfLowHealth; public float FleeTimeSinceHurt; public bool FleeInLava; public bool CirculateWhileCharging; public bool CirculateWhileChargingFlying; public bool EnableHuntPlayer; public bool AttackPlayerObjects; public int PrivateAreaTriggerThreshold; public float InterceptTimeMax; public float InterceptTimeMin; public float MaxChaseDistance; public float MinAttackInterval; public float CircleTargetInterval; public float CircleTargetDuration; public float CircleTargetDistance; public bool Sleeping; public float WakeupRange; public bool NoiseWakeup; public float MaxNoiseWakeupRange; public float WakeupDelayMin; public float WakeupDelayMax; public bool AvoidLand; public List ConsumeItems = new List(); public float ConsumeRange; public float ConsumeSearchRange; public float ConsumeSearchInterval; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref MonsterAIRef r) { //IL_0094: Unknown result type (might be due to invalid IL or missing references) if (r == null) { r = new MonsterAIRef(); } r.m_viewRange = ViewRange; r.m_viewAngle = ViewAngle; r.m_hearRange = HearRange; r.m_mistVision = MistVision; r.m_idleSoundInterval = IdleSoundInterval; r.m_idleSoundChance = IdleSoundChance; if (Enum.TryParse(PathAgentType, ignoreCase: true, out AgentType result)) { r.m_pathAgentType = result; } r.m_moveMinAngle = MoveMinAngle; r.m_smoothMovement = SmoothMovement; r.m_serpentMovement = SerpentMovement; r.m_serpentTurnRadius = SerpentTurnRadius; r.m_jumpInterval = JumpInterval; r.m_randomCircleInterval = RandomCircleInterval; r.m_randomMoveInterval = RandomMoveInterval; r.m_randomMoveRange = RandomMoveRange; r.m_randomFly = RandomFly; r.m_chanceToTakeoff = ChanceToTakeOff; r.m_chanceToLand = ChanceToLand; r.m_groundDuration = GroundDuration; r.m_airDuration = AirDuration; r.m_maxLandAltitude = MaxLandAltitude; r.m_takeoffTime = TakeoffTime; r.m_flyAltitudeMin = FlyAltitudeMin; r.m_flyAltitudeMax = FlyAltitudeMax; r.m_flyAbsMinAltitude = FlyAbsMinAltitude; r.m_avoidFire = AvoidFire; r.m_afraidOfFire = AfraidOfFire; r.m_avoidWater = AvoidWater; r.m_avoidLava = AvoidLava; r.m_skipLavaTargets = SkipLavaTargets; r.m_aggravatable = Aggravatable; r.m_passiveAggresive = PassiveAggressive; r.m_spawnMessage = SpawnMessage; r.m_deathMessage = DeathMessage; r.m_alertedMessage = AlertedMessage; r.m_fleeRange = FleeRange; r.m_fleeAngle = FleeAngle; r.m_fleeInterval = FleeInterval; r.m_alertRange = AlertRange; r.m_fleeIfHurtWhenTargetCantBeReached = FleeIfHurtWhenTargetCannotBeReached; r.m_fleeUnreachableSinceAttacking = FleeUnreachableSinceAttack; r.m_fleeUnreachableSinceHurt = FleeUnreachableSinceHurt; r.m_fleeIfNotAlerted = FleeIfNotAlerted; r.m_fleeIfLowHealth = FleeIfLowHealth; r.m_fleeTimeSinceHurt = FleeTimeSinceHurt; r.m_fleeInLava = FleeInLava; r.m_circulateWhileCharging = CirculateWhileCharging; r.m_circulateWhileChargingFlying = CirculateWhileChargingFlying; r.m_enableHuntPlayer = EnableHuntPlayer; r.m_attackPlayerObjects = AttackPlayerObjects; r.m_privateAreaTriggerTreshold = PrivateAreaTriggerThreshold; r.m_interceptTimeMax = InterceptTimeMax; r.m_interceptTimeMin = InterceptTimeMin; r.m_maxChaseDistance = MaxChaseDistance; r.m_minAttackInterval = MinAttackInterval; r.m_circleTargetInterval = CircleTargetInterval; r.m_circleTargetDuration = CircleTargetDuration; r.m_circleTargetDistance = CircleTargetDistance; r.m_sleeping = Sleeping; r.m_wakeupRange = WakeupRange; r.m_noiseWakeup = NoiseWakeup; r.m_maxNoiseWakeupRange = MaxNoiseWakeupRange; r.m_wakeUpDelayMin = WakeupDelayMin; r.m_wakeUpDelayMax = WakeupDelayMax; r.m_avoidLand = AvoidLand; r.m_consumeItems = ConsumeItems; r.m_consumeRange = ConsumeRange; r.m_consumeSearchRange = ConsumeSearchRange; r.m_consumeSearchInterval = ConsumeSearchInterval; } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class AnimalAIData { public float ViewRange; public float ViewAngle; public float HearRange; public bool MistVision; public float IdleSoundInterval; public float IdleSoundChance; public string PathAgentType = ""; public float MoveMinAngle; public bool SmoothMovement; public bool SerpentMovement; public float SerpentTurnRadius; public float JumpInterval; public float RandomCircleInterval; public float RandomMoveInterval; public float RandomMoveRange; public bool RandomFly; public float ChanceToTakeOff; public float ChanceToLand; public float GroundDuration; public float AirDuration; public float MaxLandAltitude; public float TakeoffTime; public float FlyAltitudeMin; public float FlyAltitudeMax; public float FlyAbsMinAltitude; public bool AvoidFire; public bool AfraidOfFire; public bool AvoidWater; public bool AvoidLava; public bool SkipLavaTargets; public bool Aggravatable; public bool PassiveAggressive; public string SpawnMessage = ""; public string DeathMessage = ""; public string AlertedMessage = ""; public float FleeRange; public float FleeAngle; public float FleeInterval; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref AnimalAIRef reference) { //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got I4 //IL_0095->IL0095: Incompatible stack types: O vs I4 //IL_0094->IL0095: Incompatible stack types: I4 vs O //IL_0094->IL0095: Incompatible stack types: O vs I4 if (reference == null) { reference = new AnimalAIRef(); } reference.m_viewRange = ViewRange; reference.m_viewAngle = ViewAngle; reference.m_hearRange = HearRange; reference.m_mistVision = MistVision; reference.m_idleSoundInterval = IdleSoundInterval; reference.m_idleSoundChance = IdleSoundChance; object obj = reference; int num; if (Enum.TryParse(PathAgentType, ignoreCase: true, out AgentType result)) { obj = result; num = (int)obj; } else { num = 1; obj = num; num = (int)obj; } ((BaseAIRef)num).m_pathAgentType = (AgentType)obj; reference.m_moveMinAngle = MoveMinAngle; reference.m_smoothMovement = SmoothMovement; reference.m_serpentMovement = SerpentMovement; reference.m_serpentTurnRadius = SerpentTurnRadius; reference.m_jumpInterval = JumpInterval; reference.m_randomCircleInterval = RandomCircleInterval; reference.m_randomMoveInterval = RandomMoveInterval; reference.m_randomMoveRange = RandomMoveRange; reference.m_randomFly = RandomFly; reference.m_chanceToTakeoff = ChanceToTakeOff; reference.m_chanceToLand = ChanceToLand; reference.m_groundDuration = GroundDuration; reference.m_airDuration = AirDuration; reference.m_maxLandAltitude = MaxLandAltitude; reference.m_takeoffTime = TakeoffTime; reference.m_flyAltitudeMin = FlyAltitudeMin; reference.m_flyAltitudeMax = FlyAltitudeMax; reference.m_flyAbsMinAltitude = FlyAbsMinAltitude; reference.m_avoidFire = AvoidFire; reference.m_afraidOfFire = AfraidOfFire; reference.m_avoidWater = AvoidWater; reference.m_avoidLava = AvoidLava; reference.m_skipLavaTargets = SkipLavaTargets; reference.m_aggravatable = Aggravatable; reference.m_passiveAggresive = PassiveAggressive; reference.m_spawnMessage = SpawnMessage; reference.m_deathMessage = DeathMessage; reference.m_alertedMessage = AlertedMessage; reference.m_fleeRange = FleeRange; reference.m_fleeAngle = FleeAngle; reference.m_fleeInterval = FleeInterval; } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class CharacterDropData { public string PrefabName = ""; public int AmountMin; public int AmountMax; public float Chance; public bool OnePerPlayer; public bool LevelMultiplier; public bool DoNotScale; public void Set(ref DropRef r) { r.m_prefab = PrefabName; r.m_amountMin = AmountMin; r.m_amountMax = AmountMax; r.m_chance = Chance; r.m_onePerPlayer = OnePerPlayer; r.m_levelMultiplier = LevelMultiplier; r.m_dontScale = DoNotScale; } public DropRef ToRef() { DropRef dropRef = new DropRef(); dropRef.m_prefab = PrefabName; dropRef.m_amountMin = AmountMin; dropRef.m_amountMax = AmountMax; dropRef.m_chance = Chance; dropRef.m_onePerPlayer = OnePerPlayer; dropRef.m_levelMultiplier = LevelMultiplier; dropRef.m_dontScale = DoNotScale; return dropRef; } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class TameableData { public float FedDuration; public float TamingTime; public bool StartTamed; public bool Commandable; public float UnsummonDistance; public float UnsummonOnOwnerLogoutSeconds; public string LevelUpOwnerSkill = ""; public float LevelUpFactor; public bool DropSaddleOnDeath; public List RandomStartingName = new List(); [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref TameableRef r) { //IL_00b2: Unknown result type (might be due to invalid IL or missing references) if (TamingTime != 0f) { if (r == null) { r = new TameableRef(); } r.m_fedDuration = FedDuration; r.m_tamingTime = TamingTime; r.m_startsTamed = StartTamed; r.m_commandable = Commandable; r.m_unsummonDistance = UnsummonDistance; r.m_unsummonOnOwnerLogoutSeconds = UnsummonOnOwnerLogoutSeconds; r.m_levelUpOwnerSkill = (Enum.TryParse(LevelUpOwnerSkill, ignoreCase: true, out SkillType result) ? new SkillType?(result) : null); r.m_levelUpFactor = LevelUpFactor; r.m_dropSaddleOnDeath = DropSaddleOnDeath; r.m_randomStartingName = RandomStartingName; } } } [Serializable] public class ProcreationData { public float UpdateInterval; public float TotalCheckRange; public int MaxCreatures; public float PartnerCheckRange; public float PregnancyChance; public float PregnancyDuration; public int RequiredLovePoints; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] public string Offspring = ""; public int MinOffspringLevel; public float SpawnOffset; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref ProcreationRef r) { if (r != null) { r.m_updateInterval = UpdateInterval; r.m_totalCheckRange = TotalCheckRange; r.m_maxCreatures = MaxCreatures; r.m_partnerCheckRange = PartnerCheckRange; r.m_pregnancyChance = PregnancyChance; r.m_pregnancyDuration = PregnancyDuration; r.m_requiredLovePoints = RequiredLovePoints; r.m_offspring = Offspring; r.m_spawnOffset = SpawnOffset; r.m_minOffspringLevel = MinOffspringLevel; } } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class NPCTalkData { public string Name = ""; public float MaxRange; public float GreetRange; public float ByeRange; public float Offset; public float MinTalkInterval; public float HideDialogueDelay; public float RandomTalkInterval; public float RandomTalkChance; public List RandomTalk = new List(); public List RandomTalkInFactionBase = new List(); public List RandomGreets = new List(); public List RandomGoodbye = new List(); public List PrivateAreaAlarm = new List(); public List Aggravated = new List(); [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref NPCTalkRef r) { if (r != null) { r.m_name = Name; r.m_maxRange = MaxRange; r.m_greetRange = GreetRange; r.m_byeRange = ByeRange; r.m_offset = Offset; r.m_minTalkInterval = MinTalkInterval; r.m_hideDialogDelay = HideDialogueDelay; r.m_randomTalkInterval = RandomTalkInterval; r.m_randomTalkChance = RandomTalkChance; r.m_randomTalk = RandomTalk; r.m_randomTalkInFactionBase = RandomTalkInFactionBase; r.m_randomGreets = RandomGreets; r.m_randomGoodbye = RandomGoodbye; r.m_privateAreaAlarm = PrivateAreaAlarm; r.m_aggravated = Aggravated; } } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class GrowUpData { public float GrowTime; public bool InheritTame; public string GrownPrefab = ""; public List AltGrownPrefabs = new List(); [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref GrowUpRef r) { if (r == null) { return; } r.m_growTime = GrowTime; r.m_inheritTame = InheritTame; r.m_grownPrefab = GrownPrefab; if (AltGrownPrefabs.Count != 0) { r.m_altGrownPrefabs = AltGrownPrefabs.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (AltGrownData x) => x.ToRef()).ToList(); } } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class AltGrownData { public string GrownPrefab = ""; public float Weight; public GrowUpRef.GrownEntry ToRef() { return new GrowUpRef.GrownEntry { m_prefab = GrownPrefab, m_weight = Weight }; } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class LevelEffectData { public float Scale; public float Hue; public float Saturation; public float Value; public bool SetEmissiveColor; public VisualMethods.ColorData EmissiveColor = new VisualMethods.ColorData(); public string EnableObject = ""; public LevelSetupRef ToRef() { return new LevelSetupRef { m_scale = Scale, m_hue = Hue, m_saturation = Saturation, m_value = Value, m_setEmissiveColor = SetEmissiveColor, m_enableObject = EnableObject, m_emissiveColor = EmissiveColor.ToHex() }; } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class CreatureData { public VisualMethods.ScaleData m_scale = new VisualMethods.ScaleData(); public VisualMethods.ScaleData m_ragdollScale = new VisualMethods.ScaleData(); public Dictionary m_materials = new Dictionary(); public CharacterData m_characterData = new CharacterData(); public CharacterEffects m_effects = new CharacterEffects(); public List m_defaultItems = new List(); public List m_randomWeapons = new List(); public List m_randomArmors = new List(); public List m_randomShields = new List(); public List m_randomItems = new List(); public List m_randomSets = new List(); public MonsterAIData m_monsterAIData = new MonsterAIData(); public AnimalAIData m_animalAIData = new AnimalAIData(); public List m_characterDrops = new List(); public TameableData m_tameable = new TameableData(); public ProcreationData m_procreation = new ProcreationData(); public NPCTalkData m_npcTalk = new NPCTalkData(); public GrowUpData m_growUp = new GrowUpData(); public List m_levelEffects = new List(); public Dictionary m_particles = new Dictionary(); public VisualMethods.HumanData m_humanData = new VisualMethods.HumanData(); public List GetAllItems() { List list = new List(); list.AddRange(m_defaultItems); list.AddRange(m_randomWeapons); list.AddRange(m_randomArmors); list.AddRange(m_randomShields); list.Add(m_randomSets.SelectMany([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (RandomItemSetsData x) => x.m_items).ToArray()); return list; } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class ItemAttackData { public AttackData m_attackData = new AttackData(); public ItemEffects m_effects = new ItemEffects(); public void Set(ItemDataSharedRef r) { m_attackData.Set(ref r); m_effects.Set(ref r); } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class RandomItemSetsData { public string m_name = ""; public List m_items = new List(); public HumanoidRef.ItemSet ToRef() { return new HumanoidRef.ItemSet { m_name = m_name, m_items = m_items.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (ItemAttackData x) => x.m_attackData.Name).ToArray() }; } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class CharacterEffects { public List m_hitEffects = new List(); public List m_critHitEffects = new List(); public List m_backstabHitEffects = new List(); public List m_deathEffects = new List(); public List m_waterEffects = new List(); public List m_tarEffects = new List(); public List m_slideEffects = new List(); public List m_jumpEffects = new List(); public List m_flyingContinuousEffects = new List(); public List m_pickupEffects = new List(); public List m_dropEffects = new List(); public List m_consumeItemEffects = new List(); public List m_equipEffects = new List(); public List m_perfectBlockEffects = new List(); public List m_alertedEffects = new List(); public List m_idleSounds = new List(); public List m_wakeupEffects = new List(); public List m_birthEffects = new List(); public List m_loveEffects = new List(); public List m_tamedEffects = new List(); public List m_soothEffects = new List(); public List m_petEffects = new List(); public List m_unSummonEffects = new List(); public List m_randomTalkFX = new List(); public List m_randomGreetFX = new List(); public List m_randomGoodbyeFX = new List(); [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref TameableRef r) { if (r != null) { r.m_tamedEffect = ToEffectListRef(m_tamedEffects); r.m_sootheEffect = ToEffectListRef(m_soothEffects); r.m_petEffect = ToEffectListRef(m_petEffects); r.m_unSummonEffect = ToEffectListRef(m_unSummonEffects); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref ProcreationRef r) { if (r != null) { r.m_birthEffects = ToEffectListRef(m_birthEffects); r.m_loveEffects = ToEffectListRef(m_loveEffects); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref NPCTalkRef r) { if (r != null) { r.m_randomGreetFX = ToEffectListRef(m_randomGreetFX); r.m_randomGoodbyeFX = ToEffectListRef(m_randomGoodbyeFX); r.m_randomTalkFX = ToEffectListRef(m_randomTalkFX); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref CharacterRef reference) { if (reference == null) { reference = new CharacterRef(); } reference.m_hitEffects = ToEffectListRef(m_hitEffects); reference.m_critHitEffects = ToEffectListRef(m_critHitEffects); reference.m_backstabHitEffects = ToEffectListRef(m_backstabHitEffects); reference.m_deathEffects = ToEffectListRef(m_deathEffects); reference.m_waterEffects = ToEffectListRef(m_waterEffects); reference.m_tarEffects = ToEffectListRef(m_tarEffects); reference.m_slideEffects = ToEffectListRef(m_slideEffects); reference.m_jumpEffects = ToEffectListRef(m_jumpEffects); reference.m_flyingContinuousEffect = ToEffectListRef(m_flyingContinuousEffects); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref MonsterAIRef reference) { if (reference == null) { reference = new MonsterAIRef(); } reference.m_wakeupEffects = ToEffectListRef(m_wakeupEffects); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public void Set(ref HumanoidRef reference) { if (reference == null) { reference = new HumanoidRef(); } reference.m_consumeItemEffects = ToEffectListRef(m_consumeItemEffects); reference.m_equipEffects = ToEffectListRef(m_equipEffects); reference.m_perfectBlockEffect = ToEffectListRef(m_perfectBlockEffects); } [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public EffectListRef ToEffectListRef(List infos) { if (infos.Count == 0) { return null; } EffectListRef effectListRef = new EffectListRef(); effectListRef.m_effectPrefabs = infos.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (EffectInfo x) => x.ToRef()).ToList(); return effectListRef; } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class ItemEffects { public List m_hitEffects = new List(); public List m_hitTerrainEffects = new List(); public List m_blockEffects = new List(); public List m_startEffects = new List(); public List m_holdStartEffects = new List(); public List m_equipEffects = new List(); public List m_unEquipEffects = new List(); public List m_triggerEffects = new List(); public List m_trailStartEffects = new List(); public void Set(ref ItemDataSharedRef r) { r.m_hitEffect = ToEffectListRef(m_hitEffects); r.m_hitTerrainEffect = ToEffectListRef(m_hitTerrainEffects); r.m_blockEffect = ToEffectListRef(m_blockEffects); r.m_startEffect = ToEffectListRef(m_startEffects); r.m_holdStartEffect = ToEffectListRef(m_holdStartEffects); r.m_triggerEffect = ToEffectListRef(m_triggerEffects); r.m_trailStartEffect = ToEffectListRef(m_trailStartEffects); } [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public EffectListRef ToEffectListRef(List infos) { if (infos.Count == 0) { return null; } return new EffectListRef { m_effectPrefabs = infos.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (EffectInfo x) => x.ToRef()).ToList() }; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class LegacyManager { private static readonly string LegacyFolderPath; public static readonly Dictionary creaturesToConvert; static LegacyManager() { LegacyFolderPath = Path.Combine(ConfigManager.DirectoryPath, "Legacy"); creaturesToConvert = new Dictionary(); } public static void ConvertAll(ConsoleEventArgs args) { if (creaturesToConvert.Count <= 0) { args.Context.LogWarning("No legacy files found."); return; } Load(); args.Context.LogInfo($"Converted {creaturesToConvert.Count} legacy file into v.0.2.x format"); } public static void Convert(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); return; } if (!creaturesToConvert.TryGetValue(@string, out var value)) { args.Context.LogWarning("No legacy creature data found for " + @string); return; } Convert(value); args.Context.LogInfo("Converted " + @string + " legacy file into v.0.2.x format"); } public static void Start() { ImportDirs(); ImportFiles(); if (creaturesToConvert.Count > 0) { MonsterDBPlugin.LogInfo($"Loaded {creaturesToConvert.Count} legacy files. Use command convert_all, to export to new file structure."); } } private static void Load() { foreach (CreatureData value in creaturesToConvert.Values) { Convert(value); } } private static bool Read(string folderPath) { CreatureData creatureData = new CreatureData(); VisualMethods.ReadVisuals(folderPath, ref creatureData); HumanoidMethods.ReadHumanoid(folderPath, ref creatureData); CharacterMethods.ReadCharacter(folderPath, ref creatureData); MonsterAIMethods.ReadMonsterAI(folderPath, ref creatureData); AnimalAIMethods.ReadAnimalAI(folderPath, ref creatureData); CharacterDropMethods.ReadCharacterDrops(folderPath, ref creatureData); TameableMethods.ReadTameable(folderPath, ref creatureData); ProcreationMethods.ReadProcreation(folderPath, ref creatureData); NPCTalkMethods.ReadNPCTalk(folderPath, ref creatureData); GrowUpMethods.ReadGrowUp(folderPath, ref creatureData); LevelEffectsMethods.ReadLevelEffects(folderPath, ref creatureData); creaturesToConvert[creatureData.m_characterData.PrefabName] = creatureData; return true; } private static void ImportDirs() { List list = new List(); string path = Path.Combine(ConfigManager.DirectoryPath, "Creatures"); string path2 = Path.Combine(ConfigManager.DirectoryPath, "Clones"); if (Directory.Exists(LegacyFolderPath)) { list.AddRange(Directory.GetDirectories(LegacyFolderPath)); } if (Directory.Exists(path2)) { list.AddRange(Directory.GetDirectories(path2)); } if (Directory.Exists(path)) { list.AddRange(Directory.GetDirectories(path)); } for (int i = 0; i < list.Count; i++) { string folderPath = list[i]; Read(folderPath); } } private static void ImportFiles() { if (!Directory.Exists(LegacyFolderPath)) { return; } string[] files = Directory.GetFiles(LegacyFolderPath, "*.yml"); if (files.Length == 0) { return; } IDeserializer deserializer = new DeserializerBuilder().Build(); int num = 0; foreach (string path in files) { try { string input = File.ReadAllText(path); CreatureData creatureData = deserializer.Deserialize(input); creaturesToConvert[creatureData.m_characterData.PrefabName] = creatureData; num++; } catch { MonsterDBPlugin.LogWarning("Failed to deserialize file: " + Path.GetFileName(path)); } } MonsterDBPlugin.LogDebug($"Imported {num} creature data files"); } private static void Update(GameObject critter, CreatureData data) { VisualMethods.Update(critter, data); TameableMethods.Update(critter, data); HumanoidMethods.Update(critter, data); CharacterMethods.Update(critter, data); MonsterAIMethods.Update(critter, data); AnimalAIMethods.Update(critter, data); CharacterDropMethods.Update(critter, data); ProcreationMethods.Update(critter, data); NPCTalkMethods.Update(critter, data); GrowUpMethods.Update(critter, data); LevelEffectsMethods.Update(critter, data); } private static void Convert(CreatureData data) { bool flag = !string.IsNullOrEmpty(data.m_characterData.ClonedFrom); string clonedFrom = data.m_characterData.ClonedFrom; string text = (string.IsNullOrEmpty(data.m_characterData.ClonedFrom) ? data.m_characterData.PrefabName : data.m_characterData.ClonedFrom); GameObject val = PrefabManager.GetPrefab(text); if ((Object)(object)val == (Object)null) { MonsterDBPlugin.LogWarning("Legacy Conversion: Failed to find prefab: " + text); return; } if (flag) { val = CreatureManager.Clone(val, data.m_characterData.PrefabName, write: false); string prefabName = "MDB_" + data.m_characterData.PrefabName + "_ragdoll"; foreach (EffectInfo deathEffect in data.m_effects.m_deathEffects) { if (deathEffect.PrefabName.EndsWith("ragdoll")) { deathEffect.PrefabName = prefabName; } } } if ((Object)(object)val == (Object)null) { return; } List allItems = data.GetAllItems(); allItems.RemoveAll((ItemAttackData x) => string.IsNullOrEmpty(x.m_attackData.OriginalPrefab)); foreach (ItemAttackData item in allItems) { GameObject prefab = PrefabManager.GetPrefab(item.m_attackData.OriginalPrefab); if (!((Object)(object)prefab == (Object)null)) { ItemManager.TryClone(prefab, item.m_attackData.Name, out var _, write: false); } } CreatureManager.TrySave(val, out var data2, flag, clonedFrom); LoadManager.originals.Remove(((Object)val).name); Update(val, data); CreatureManager.Write(val, flag, clonedFrom); if (data2 != null) { LoadManager.originals[((Object)val).name] = data2; } } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class AudioManager { public static readonly Dictionary clips; static AudioManager() { clips = new Dictionary(); } public static void Start() { HashSet audioExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) { ".wav", ".mp3", ".ogg", ".flac", ".aac", ".m4a", ".wma", ".aiff", ".aif" }; string[] array = (from f in Directory.GetFiles(FileManager.ImportFolder, "*", SearchOption.AllDirectories) where audioExtensions.Contains(Path.GetExtension(f)) select f).ToArray(); foreach (string filePath in array) { new AudioRef(filePath); } } [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public static AudioClip ReadAudioFile(string file) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Invalid comparison between Unknown and I4 //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Invalid comparison between Unknown and I4 //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip("file:///" + file.Replace("\\", "/"), (AudioType)0); try { audioClip.SendWebRequest(); while (!audioClip.isDone) { } if ((int)audioClip.result == 2 || (int)audioClip.result == 3) { MonsterDBPlugin.LogWarning("Failed to load audio file: " + audioClip.error); return null; } DownloadHandlerAudioClip val = (DownloadHandlerAudioClip)audioClip.downloadHandler; AudioClip audioClip2 = val.audioClip; ((Object)audioClip2).name = Path.GetFileNameWithoutExtension(file); MonsterDBPlugin.LogDebug("Successfully loaded audio: " + ((Object)audioClip2).name); return audioClip2; } finally { ((IDisposable)audioClip)?.Dispose(); } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class AudioRef { public string filePath; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] private readonly AudioClip clip; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public GameObject sfx; public AudioRef(string filePath) { this.filePath = filePath; clip = AudioManager.ReadAudioFile(filePath); if (!((Object)(object)clip != (Object)null)) { return; } Clone clone = new Clone("sfx_Bonemass_idle", ((Object)clip).name); clone.OnCreated += delegate(GameObject p) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) ZSFX val = default(ZSFX); if (p.TryGetComponent(ref val)) { val.m_captionType = (CaptionType)2; val.m_closedCaptionToken = ((Object)clip).name; val.m_secondaryCaptionToken = ""; val.m_audioClips = (AudioClip[])(object)new AudioClip[1] { clip }; sfx = p; } TimedDestruction val2 = default(TimedDestruction); if (p.TryGetComponent(ref val2)) { val2.m_timeout = clip.length; } MonsterDBPlugin.LogInfo("Loaded SFX as " + ((Object)p).name); }; AudioManager.clips[((Object)clip).name] = this; } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class Clone { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] private GameObject Source; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] private GameObject Prefab; public readonly string SourceName; private readonly string NewName; private bool Loaded; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [method: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [field: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public event Action OnCreated; public Clone(string prefabName, string newName) { SourceName = prefabName; NewName = newName; CloneManager.clones[newName] = this; } public Clone(GameObject prefab, string newName) : this(((Object)prefab).name, newName) { Source = prefab; } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] internal GameObject Create() { if (Loaded) { return Prefab; } if (Source == null) { Source = PrefabManager.GetPrefab(SourceName); } if ((Object)(object)Source == (Object)null) { return null; } Prefab = Object.Instantiate(Source, CloneManager.GetRootTransform(), false); ((Object)Prefab).name = NewName; this.OnCreated?.Invoke(Prefab); PrefabManager.RegisterPrefab(Prefab); CloneManager.prefabs[((Object)Prefab).name] = Prefab; Loaded = true; return Prefab; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class CloneManager { private static readonly GameObject root; internal static readonly Dictionary prefabs; internal static readonly Dictionary clones; static CloneManager() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown prefabs = new Dictionary(); clones = new Dictionary(); root = new GameObject("MonsterDB_prefab_root"); Object.DontDestroyOnLoad((Object)(object)root); root.SetActive(false); } public static Transform GetRootTransform() { return root.transform; } public static void Clear() { for (int i = 0; i < root.transform.childCount; i++) { GameObject gameObject = ((Component)root.transform.GetChild(i)).gameObject; int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)gameObject).name); if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { ZNetScene.instance.m_prefabs.Remove(gameObject); ZNetScene.instance.m_namedPrefabs.Remove(stableHashCode); } if (Object.op_Implicit((Object)(object)ObjectDB.instance)) { ObjectDB.instance.m_items.Remove(gameObject); ObjectDB.instance.m_itemByHash.Remove(stableHashCode); } PrefabManager.PrefabsToRegister.Remove(gameObject); PrefabManager._prefabs.Remove(((Object)gameObject).name); MonsterDBPlugin.LogDebug("Destroyed " + ((Object)gameObject).name); Object.Destroy((Object)(object)gameObject); } prefabs.Clear(); clones.Clear(); } public static bool IsClone(string prefabName, out string sourceName) { if (!clones.TryGetValue(prefabName, out var value)) { sourceName = ""; return false; } sourceName = value.SourceName; return true; } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class CommandManager { [Serializable] [CompilerGenerated] private sealed class <>c { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static readonly <>c <>9 = new <>c(); [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static ConsoleEventFailable <>9__3_0; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static Func, bool> <>9__3_1; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static Func, string> <>9__3_2; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 0, 1 })] public static Action <>9__3_3; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] internal object b__3_0(ConsoleEventArgs args) { if (args.Length < 2) { return true; } if (!commands.TryGetValue(args[1], out var value)) { return true; } return value.Run(args); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] internal bool b__3_1(KeyValuePair x) { return !x.Value.IsSecret(); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] internal string b__3_2(KeyValuePair x) { return x.Key; } internal void b__3_3(ConsoleEventArgs args) { StringBuilder stringBuilder = new StringBuilder(); foreach (KeyValuePair command in commands) { if (!command.Value.IsSecret() && !(command.Key == "help")) { stringBuilder.Clear(); stringBuilder.AppendFormat("{0} - {1}", command.Key, command.Value.m_description); if (command.Value.m_adminOnly) { stringBuilder.Append(" (admin only)"); } args.Context.AddString(stringBuilder.ToString()); } } } } private static readonly string startCommand; public static readonly Dictionary commands; static CommandManager() { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Expected O, but got Unknown //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Expected O, but got Unknown commands = new Dictionary(); Harmony harmony = MonsterDBPlugin.harmony; startCommand = "MonsterDB".ToLower(); harmony.Patch((MethodBase)AccessTools.Method(typeof(Terminal), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(CommandManager), "Patch_Terminal_Awake", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(Terminal), "updateSearch", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(CommandManager), "Patch_Terminal_UpdateSearch", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(Terminal), "tabCycle", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(CommandManager), "Patch_Terminal_TabCycle", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } private static void Patch_Terminal_Awake() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown //IL_008a: Unknown result type (might be due to invalid IL or missing references) string text = startCommand; object obj = <>c.<>9__3_0; if (obj == null) { ConsoleEventFailable val = [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (ConsoleEventArgs args) => { if (args.Length < 2) { return true; } Command value; return (!commands.TryGetValue(args[1], out value)) ? ((object)true) : ((object)value.Run(args)); }; <>c.<>9__3_0 = val; obj = (object)val; } new ConsoleCommand(text, "use help to find available commands", (ConsoleEventFailable)obj, false, false, false, false, false, new ConsoleOptionsFetcher(Enumerable.ToList), false, false, false); new Command("help", "list of available commands", delegate(ConsoleEventArgs args) { StringBuilder stringBuilder = new StringBuilder(); foreach (KeyValuePair command in commands) { if (!command.Value.IsSecret() && !(command.Key == "help")) { stringBuilder.Clear(); stringBuilder.AppendFormat("{0} - {1}", command.Key, command.Value.m_description); if (command.Value.m_adminOnly) { stringBuilder.Append(" (admin only)"); } args.Context.AddString(stringBuilder.ToString()); } } }); } private static bool Patch_Terminal_UpdateSearch(Terminal __instance, string word) { if ((Object)(object)__instance.m_search == (Object)null) { return true; } string[] array = ((TMP_InputField)__instance.m_input).text.Split(new char[1] { ' ' }); if (array.Length < 3) { return true; } if (array[0] != startCommand) { return true; } return HandleSearch(__instance, word, array); } private static bool HandleSearch(Terminal __instance, string word, string[] strArray) { if (!commands.TryGetValue(strArray[1], out var value)) { return true; } if (value.HasOptions() && strArray.Length > 2) { string word2 = strArray[2]; List list = value.FetchOptions(strArray.Length - 1, word2); string currentSearch = strArray[^1]; List list2; if (!string.IsNullOrEmpty(currentSearch)) { int num = list.IndexOf(currentSearch); list2 = ((num != -1) ? list.GetRange(num, list.Count - num) : list); list2 = list2.FindAll((string x) => x.ToLower().Contains(currentSearch.ToLower())); } else { list2 = list; } if (list2.Count <= 0) { __instance.m_search.text = value.GetDescription(strArray); } else { __instance.m_lastSearch.Clear(); __instance.m_lastSearch.AddRange(list2); __instance.m_lastSearch.Remove(word); __instance.m_search.text = ""; int num2 = 10; int num3 = Math.Min(__instance.m_lastSearch.Count, num2); for (int i = 0; i < num3; i++) { string text = __instance.m_lastSearch[i]; TMP_Text search = __instance.m_search; search.text = search.text + text + " "; } if (__instance.m_lastSearch.Count <= num2) { return false; } int num4 = __instance.m_lastSearch.Count - num2; TMP_Text search2 = __instance.m_search; search2.text += $"... {num4} more."; } } else { __instance.m_search.text = value.GetDescription(strArray); } return false; } private static void Patch_Terminal_TabCycle(Terminal __instance, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] ref List options) { if (string.IsNullOrEmpty(((TMP_InputField)__instance.m_input).text)) { return; } string[] array = ((TMP_InputField)__instance.m_input).text.Split(new char[1] { ' ' }); if (array.Length < 2) { return; } string b = array[0]; if (string.Equals(startCommand, b, StringComparison.OrdinalIgnoreCase)) { string key = array[1]; string word = ((array.Length > 2) ? array[2] : ""); if (commands.TryGetValue(key, out var value)) { options = value.FetchOptions(array.Length - 1, word); } } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class Extensions { private static readonly Dictionary canFlyToggleCache = new Dictionary(); private static readonly MethodInfo LoadImage = AccessTools.Method(typeof(ImageConversion), "LoadImage", new Type[2] { typeof(Texture2D), typeof(byte[]) }, (Type[])null); public static string GetString(this ConsoleEventArgs args, int index, string defaultValue = "") { if (args.Length < index + 1) { return defaultValue; } return args[index]; } public static float GetFloat(this ConsoleEventArgs args, int index, float defaultValue = 0f) { if (args.Length < index + 1) { return defaultValue; } string s = args[index]; float result; return float.TryParse(s, out result) ? result : defaultValue; } public static int GetInt(this ConsoleEventArgs args, int index, int defaultValue = 0) { if (args.Length < index + 1) { return defaultValue; } string s = args[index]; int result; return int.TryParse(s, out result) ? result : defaultValue; } public static string GetStringFrom(this ConsoleEventArgs args, int index, string defaultValue = "") { if (args.Length < index + 1) { return defaultValue; } return string.Join(" ", args.Args.Skip(index)); } public static HashSet GetAttacks(this Humanoid humanoid) { HashSet hashSet = new HashSet(); if (humanoid.m_defaultItems != null) { hashSet.AddRange(humanoid.m_defaultItems); } if (humanoid.m_randomWeapon != null) { hashSet.AddRange(humanoid.m_randomWeapon); } if (humanoid.m_randomSets != null) { hashSet.AddRange(humanoid.m_randomSets.SelectMany([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (ItemSet x) => x.m_items).ToArray()); } ItemDrop val = default(ItemDrop); hashSet.RemoveWhere((GameObject x) => (Object)(object)x == (Object)null || !x.TryGetComponent(ref val) || string.IsNullOrEmpty(val.m_itemData.m_shared.m_attack.m_attackAnimation)); return hashSet; } public static HashSet GetItems(this Humanoid humanoid) { HashSet hashSet = new HashSet(); if (humanoid.m_defaultItems != null) { hashSet.AddRange(humanoid.m_defaultItems); } if (humanoid.m_randomWeapon != null) { hashSet.AddRange(humanoid.m_randomWeapon); } if (humanoid.m_randomShield != null) { hashSet.AddRange(humanoid.m_randomShield); } if (humanoid.m_randomArmor != null) { hashSet.AddRange(humanoid.m_randomArmor); } if (humanoid.m_randomSets != null) { hashSet.AddRange(humanoid.m_randomSets.SelectMany([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (ItemSet x) => x.m_items).ToArray()); } if (humanoid.m_randomItems != null) { hashSet.AddRange(humanoid.m_randomItems.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (RandomItem x) => x.m_prefab).ToArray()); } hashSet.RemoveWhere((GameObject x) => (Object)(object)x == (Object)null || !Object.op_Implicit((Object)(object)x.GetComponent())); return hashSet; } public static ItemDataSharedRef[] ToItemDataSharedRefArray(this HashSet items) { List list = new List(); foreach (GameObject item in items) { PrefabManager.AddToCache(item); ItemDrop component = item.GetComponent(); if (!((Object)(object)component == (Object)null)) { ItemDataSharedRef itemDataSharedRef = new ItemDataSharedRef(); itemDataSharedRef.Setup(component.m_itemData.m_shared); itemDataSharedRef.m_prefab = ((Object)item).name; list.Add(itemDataSharedRef); } } return list.ToArray(); } public static HumanoidRef.RandomItem[] ToHumanoidRefRandomItemArray(this RandomItem[] ria) { return (from x in ria where x != null && (Object)(object)x.m_prefab != (Object)null select new HumanoidRef.RandomItem { m_prefab = ((Object)x.m_prefab).name, m_chance = x.m_chance }).ToArray(); } public static RandomItem[] ToHumanoidRandomItemArray(this HumanoidRef.RandomItem[] ria) { return (from x in ria.Where([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (HumanoidRef.RandomItem x) => !string.IsNullOrEmpty(x.m_prefab)).Select((Func)([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (HumanoidRef.RandomItem x) => new RandomItem { m_prefab = PrefabManager.GetPrefab(x.m_prefab), m_chance = x.m_chance })) where (Object)(object)x.m_prefab != (Object)null select x).ToArray(); } public static HumanoidRef.ItemSet[] ToHumanoidRefItemSetArray(this ItemSet[] isa) { return (from x in isa where x != null select new HumanoidRef.ItemSet { m_name = x.m_name, m_items = (from it in x.m_items where (Object)(object)it != (Object)null select ((Object)it).name).ToArray() }).ToArray(); } public static ItemSet[] ToHumanoidItemSetArray(this HumanoidRef.ItemSet[] isa) { return isa.Where([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (HumanoidRef.ItemSet x) => x.m_items.Length != 0).Select((Func)([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (HumanoidRef.ItemSet x) => new ItemSet { m_name = x.m_name, m_items = (from p in x.m_items where !string.IsNullOrEmpty(p) select PrefabManager.GetPrefab(p) into p where (Object)(object)p != (Object)null select p).ToArray() })).ToArray(); } public static string[] ToGameObjectNameArray(this GameObject[] goa) { return (from x in goa where (Object)(object)x != (Object)null select ((Object)x).name).ToArray(); } public static GameObject[] ToGameObjectArray(this string[] goNames) { return (from x in goNames where !string.IsNullOrEmpty(x) select PrefabManager.GetPrefab(x) into x where (Object)(object)x != (Object)null select x).ToArray(); } public static List ToRef(this List cd) { return (from x in cd where (Object)(object)x.m_prefab != (Object)null select new DropRef(x)).ToList(); } public static List FromRef(this List dr) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown List list = new List(); for (int i = 0; i < dr.Count; i++) { DropRef dropRef = dr[i]; Drop val = new Drop(); dropRef.UpdateFields(val, dropRef.m_prefab ?? "Null", log: false); list.Add(val); } return list; } public static List ToStepEffectRefList(this List effects) { return effects.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (StepEffect f) => new StepEffectRef(f)).ToList(); } public static List ToFootStepEffects(this List effects, List defaultValues) { //IL_0058: 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_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Expected O, but got Unknown Dictionary<(string, MotionType, GroundMaterial), StepEffect> dictionary = defaultValues.ToSafeDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (StepEffect x) => (x.m_name, x.m_motionType, x.m_material)); List list = new List(); for (int i = 0; i < effects.Count; i++) { StepEffectRef stepEffectRef = effects[i]; if (stepEffectRef.m_effectPrefabs != null) { (string, MotionType, GroundMaterial) key = (stepEffectRef.m_name, stepEffectRef.m_motionType, stepEffectRef.m_material); if (!dictionary.TryGetValue(key, out var value)) { value = new StepEffect { m_name = stepEffectRef.m_name, m_motionType = stepEffectRef.m_motionType, m_material = stepEffectRef.m_material }; } value.m_effectPrefabs = CleanupFootStepEffects(stepEffectRef.m_effectPrefabs.ToGameObjectArray()); dictionary[key] = value; list.Add(value); } } return list; } private static GameObject[] CleanupFootStepEffects(GameObject[] effects) { List list = new List(); foreach (GameObject val in effects) { if ((Object)(object)val == (Object)null) { continue; } if (Object.op_Implicit((Object)(object)val.GetComponent())) { string text = ((Object)val).name + "_No_ZNetView"; if (CloneManager.prefabs.TryGetValue(text, out var value)) { list.Add(value); continue; } Clone clone = new Clone(val, text); clone.OnCreated += delegate(GameObject p) { p.Remove(); }; value = clone.Create(); if (!((Object)(object)value == (Object)null)) { list.Add(value); } } else { list.Add(val); } } return list.ToArray(); } public static List ToGrowUpRefEntryList(this List ge) { return (from x in ge where (Object)(object)x.m_prefab != (Object)null select new GrowUpRef.GrownEntry(x)).ToList(); } public static List FromRef(this List ge) { return (from x in ge select x.ToGrowUpGrowEntry() into x where (Object)(object)x.m_prefab != (Object)null select x).ToList(); } public static List ToRef(this List list) { return list.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (RandomValue x) => new RandomAnimationRef.RandomValueRef { m_name = x.m_name, m_values = x.m_values, m_interval = x.m_interval, m_floatValue = x.m_floatValue, m_floatTransition = x.m_floatTransition }).ToList(); } public static List FromRef(this List list) { return ((IEnumerable)list).Select((Func)([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (RandomAnimationRef.RandomValueRef x) => new RandomValue { m_name = x.m_name, m_values = x.m_values, m_interval = x.m_interval, m_floatValue = x.m_floatValue, m_floatTransition = x.m_floatTransition })).ToList(); } public static EffectListRef ToEffectListRef(this EffectList el) { EffectListRef effectListRef = new EffectListRef(); EffectData[] effectPrefabs = el.m_effectPrefabs; foreach (EffectData val in effectPrefabs) { if (!((Object)(object)val.m_prefab == (Object)null)) { EffectListRef.EffectDataRef effectDataRef = new EffectListRef.EffectDataRef(); effectDataRef.Setup(val); effectListRef.Add(effectDataRef); } } return effectListRef; } public static void Add<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(this List list, params T[] values) { list.AddRange(values); } public static void CopyFrom<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] V>(this T target, V source) where T : MonoBehaviour where V : MonoBehaviour { Dictionary dictionary = typeof(T).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToSafeDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (FieldInfo f) => f.Name); FieldInfo[] fields = typeof(V).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { if (dictionary.TryGetValue(fieldInfo.Name, out var value) && value.FieldType.IsAssignableFrom(fieldInfo.FieldType)) { value.SetValue(target, fieldInfo.GetValue(source)); } } } public static void Remove<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>(this GameObject prefab) where T : Component { T val = default(T); if (prefab.TryGetComponent(ref val)) { Object.DestroyImmediate((Object)(object)val); } } private static void AddRange<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(this HashSet set, params T[] values) { foreach (T item in values) { set.Add(item); } } public static Dictionary ToSafeDictionary<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] K, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] V>(this IEnumerable enumerable, Func func) { Dictionary dictionary = new Dictionary(); foreach (V item in enumerable) { K key = func(item); if (!dictionary.ContainsKey(key)) { dictionary[key] = item; } } return dictionary; } public static List GetAvailableAttacks(this Humanoid humanoid) { return (from item in humanoid.GetInventory().GetAllItems() where item.IsWeapon() && ((Character)humanoid).m_baseAI.CanUseAttack(item) select item).ToList(); } public static bool CanToggleFly(this Character character) { string prefabName = Utils.GetPrefabName(((Object)character).name); if (canFlyToggleCache.TryGetValue(prefabName, out var value)) { return value; } bool flag = character.m_animator.parameters.Any([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (AnimatorControllerParameter p) => { string name = p.name; return (name == "fly_takeoff" || name == "fly_land") ? true : false; }); canFlyToggleCache[prefabName] = flag; return flag; } public static List ToBaitSettingsRefList(this List baitSettings) { return (from x in baitSettings where (Object)(object)x.m_bait != (Object)null select new BaitSettingRef { m_bait = ((Object)x.m_bait).name, m_chance = x.m_chance }).ToList(); } public static List ToBaitSettingsList(this List reference) { return (from x in reference.Where([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (BaitSettingRef x) => !string.IsNullOrEmpty(x.m_bait)).Select((Func)([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (BaitSettingRef x) => { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown BaitSetting val = new BaitSetting(); GameObject prefab = PrefabManager.GetPrefab(x.m_bait); val.m_bait = ((prefab != null) ? prefab.GetComponent() : null); val.m_chance = x.m_chance; return val; })) where (Object)(object)x.m_bait != (Object)null select x).ToList(); } public static List ToDropDataRefList(this List dropData) { return (from x in dropData where (Object)(object)x.m_item != (Object)null select new DropDataRef(x)).ToList(); } public static List ToDropDataList(this List reference) { return (from x in reference select x.ToDropData() into x where (Object)(object)x.m_item != (Object)null select x).ToList(); } public static AttackRef ToAttackRef(this Attack att) { AttackRef attackRef = new AttackRef(); attackRef.Setup(att); return attackRef; } public static List ToItemNameList(this List items) { return (from x in items where (Object)(object)x != (Object)null select ((Object)x).name).ToList(); } public static List ToItemDropList(this List il) { return (from x in il select PrefabManager.GetPrefab(x) into x where (Object)(object)x != (Object)null select x.GetComponent() into x where (Object)(object)x != (Object)null select x).ToList(); } public static string[] ToSpriteNameArray(this Sprite[] icons) { return icons.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (Sprite x) => ((Object)x).name).ToArray(); } public static Sprite[] ToSpriteArray(this string[] spriteNames) { return (from x in spriteNames select TextureManager.GetSprite(x, null) into x where (Object)(object)x != (Object)null select x).ToArray(); } public static List ToSpawnDataRefList(this List sps) { return sps.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (SpawnData x) => new SpawnDataRef(x)).ToList(); } public static RequirementRef[] ToRequirementRef(this Requirement[] requirements) { List list = new List(); foreach (Requirement requirement in requirements) { RequirementRef item = new RequirementRef(requirement); list.Add(item); } return list.ToArray(); } public static Requirement[] ToPieceRequirements(this RequirementRef[] requirements) { List list = new List(); foreach (RequirementRef requirementRef in requirements) { if (!requirementRef.TryGetPieceRequirement(out var requirement)) { MonsterDBPlugin.LogWarning("Invalid requirement"); } else { list.Add(requirement); } } return list.ToArray(); } public static List ToSpawnDataRefList(this List spawns) { return spawns.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (SpawnData s) => new SpawnAreaRef.SpawnDataRef(s)).ToList(); } public static List ToSpawnAreaSpawnDataList(this List spawns) { return (from s in spawns select s.ToSpawnData() into s where (Object)(object)s.m_prefab != (Object)null select s).ToList(); } public static bool LoadImage4x(this Texture2D tex, byte[] data) { return (bool)LoadImage.Invoke(null, new object[2] { tex, data }); } public static List ToLevelSetupRefList(this List ls) { return ls.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (LevelSetup x) => new LevelSetupRef(x)).ToList(); } public static LightRef[] ToLightRefList(this Light[] lights) { return lights.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (Light x) => new LightRef(x)).ToArray(); } public static MaterialRef[] ToMaterialRefArray(this Material[] mats) { List list = new List(); foreach (Material val in mats) { if (!((Object)(object)val == (Object)null)) { list.Add(new MaterialRef(val)); } } return list.ToArray(); } public static string ToRGBAString(this Color color) { return ((object)(Color)(ref color)).ToString(); } public static string ToHexString(this Color color, bool includeAlpha = true) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_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) //IL_0026: Unknown result type (might be due to invalid IL or missing references) Color32 val = Color32.op_Implicit(color); return includeAlpha ? $"#{val.r:X2}{val.g:X2}{val.b:X2}{val.a:X2}" : $"#{val.r:X2}{val.g:X2}{val.b:X2}"; } public static Color FromHexOrRGBA(this string input, Color defaultValue) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0152: 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_0056: 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_0174: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_0196: 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_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrWhiteSpace(input)) { return defaultValue; } if (input.StartsWith("#")) { input = input.TrimStart(new char[1] { '#' }); if (input.Length != 6 && input.Length != 8) { return defaultValue; } byte b = byte.Parse(input.Substring(0, 2), NumberStyles.HexNumber); byte b2 = byte.Parse(input.Substring(2, 2), NumberStyles.HexNumber); byte b3 = byte.Parse(input.Substring(4, 2), NumberStyles.HexNumber); byte b4 = ((input.Length == 8) ? byte.Parse(input.Substring(6, 2), NumberStyles.HexNumber) : byte.MaxValue); return Color32.op_Implicit(new Color32(b, b2, b3, b4)); } if (input.StartsWith("RGBA")) { int num = input.IndexOf('(') + 1; int num2 = input.IndexOf(')'); string[] array = input.Substring(num, num2 - num).Split(new char[1] { ',' }); if (array.Length != 4) { return defaultValue; } if (!float.TryParse(array[0], NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.InvariantInfo, out var result)) { return defaultValue; } if (!float.TryParse(array[1], NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.InvariantInfo, out var result2)) { return defaultValue; } if (!float.TryParse(array[2], NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.InvariantInfo, out var result3)) { return defaultValue; } if (!float.TryParse(array[3], NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.InvariantInfo, out var result4)) { return defaultValue; } return new Color(result, result2, result3, result4); } return defaultValue; } public static ParticleSystemRef[] ToParticleSystemRefArray(this ParticleSystem[] particleSystems) { return particleSystems.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (ParticleSystem x) => new ParticleSystemRef(x)).ToArray(); } public static GradientAlphaKeyRef[] ToRef(this GradientAlphaKey[] keys) { return keys.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (GradientAlphaKey x) => new GradientAlphaKeyRef(x)).ToArray(); } public static GradientAlphaKey[] FromRef(this GradientAlphaKeyRef[] keys) { return keys.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (GradientAlphaKeyRef x) => x.ToGradientAlphaKey()).ToArray(); } public static GradientColorKeyRef[] ToRef(this GradientColorKey[] keys) { return keys.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (GradientColorKey x) => new GradientColorKeyRef(x)).ToArray(); } public static GradientColorKey[] FromRef(this GradientColorKeyRef[] keys) { return keys.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (GradientColorKeyRef x) => x.ToGradientColorKey()).ToArray(); } public static RendererRef[] ToRendererRefArray(this Renderer[] renderers) { return (from x in renderers select new RendererRef(x) into x orderby x.m_parent, x.m_index select x).ToArray(); } public static int GetInt(this string[] parts, int index, int defaultValue = 0) { if (parts.Length - 1 < index) { return defaultValue; } int result; return int.TryParse(parts[index].Trim(), out result) ? result : 0; } public static float GetFloat(this string[] parts, int index, float defaultValue = 0f) { if (parts.Length - 1 < index) { return defaultValue; } float result; return float.TryParse(parts[index].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out result) ? result : defaultValue; } public static bool GetBool(this string[] parts, int index, bool defaultValue = false) { if (parts.Length - 1 < index) { return defaultValue; } bool result; return bool.TryParse(parts[index].Trim(), out result) ? result : defaultValue; } public static string GetString(this string[] parts, int index, string defaultValue = "") { if (parts.Length - 1 < index) { return defaultValue; } return parts[index].Trim(); } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class Command { public readonly string m_description; private readonly bool m_isSecret; public readonly bool m_adminOnly; private readonly Action m_command; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1, 1 })] private readonly Func> m_tabOptions; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1, 1, 1 })] private readonly Func m_descriptions; public bool Run(ConsoleEventArgs args) { if (!IsAdmin()) { return true; } m_command(args); return true; } private bool IsAdmin() { if (!Object.op_Implicit((Object)(object)ZNet.m_instance)) { return true; } if (!m_adminOnly || ((Terminal)Console.instance).IsCheatsEnabled() || ZNet.instance.LocalPlayerIsAdminOrHost()) { return true; } Console.instance.Print("Admin Only"); return false; } public bool IsSecret() { return m_isSecret; } public List FetchOptions(int i, string word = "") { return (m_tabOptions == null) ? new List() : m_tabOptions(i, word); } public bool HasOptions() { return m_tabOptions != null; } public bool HasDescriptions() { return m_descriptions != null; } public string GetDescription(string[] args) { return (m_descriptions == null) ? m_description : m_descriptions(args, m_description); } public Command(string input, string description, Action command, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1, 1 })] Func> optionsFetcher = null, bool isSecret = false, bool adminOnly = false, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1, 1, 1 })] Func descriptions = null) { m_description = description; m_command = command; m_isSecret = isSecret; m_tabOptions = optionsFetcher; m_adminOnly = adminOnly; m_descriptions = descriptions; CommandManager.commands[input] = this; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class Commands { private const string HEX_Gray = "#B2BEB5"; private const string HEX_SoftBlue = "#60A5FA"; private const string HEX_Green = "#34D399"; private const string HEX_Amber = "#FBBF24"; private const string HEX_Red = "#F87171"; private static readonly List ExportOptions = GetBaseTypes(BaseType.None, BaseType.Ragdoll).Union(new List { "texture", "sprite", "raid", "bones", "uv" }).ToList(); private static readonly List SearchTypes = new List(5) { "item", "texture", "tex", "sprite", "shader" }; public static void LogInfo(this Terminal terminal, string msg) { terminal.Log("#34D399", msg); } public static void LogWarning(this Terminal terminal, string msg) { terminal.Log("#FBBF24", msg); } public static void LogError(this Terminal terminal, string msg) { terminal.Log("#F87171", msg); } public static void LogDebug(this Terminal terminal, string msg) { terminal.Log("#60A5FA", msg); } public static void Log(this Terminal terminal, string hex, string msg) { terminal.AddString("" + msg + ""); } public static string RemoveRootPath(this string filepath) { return filepath.Replace(Paths.ConfigPath, "...\\BepInEx\\config\\"); } public static void Init() { new Command("export", "[Type][ID]: Export YML file", Export, GetExportOptions, isSecret: false, adminOnly: false, GetExportDescriptions); new Command("reload", "Reloads all files in import folder", LoadManager.ReloadAll, null, isSecret: false, adminOnly: true); new Command("convert", "[Name]: Convert specific or all legacy file into v.0.2.x format", Convert, GetConvertOptions, isSecret: false, adminOnly: false, GetConvertDescription); new Command("update", "[FileName]: Update YML file", Update, GetUpdateOptions, isSecret: false, adminOnly: true); new Command("reset", "[Type][Name]: Reset prefab to factory settings", Revert, GetRevertOptions, isSecret: false, adminOnly: true); new Command("clone", "[Type][ID][Name]: Clone prefab and export YML file", Clone, GetCloneOptions, isSecret: false, adminOnly: true, GetCloneDescriptions); new Command("search", "[Type][ID]: Search item, texture or shader by name", Search, GetSearchOptions, isSecret: false, adminOnly: false, GetSearchDescriptions); new Command("create", "[ID]: create item from non-item prefabs", ItemManager.CreateItem, GetZNetPrefabNames, isSecret: false, adminOnly: true); new Command("snapshot", "[ID][lightIntensity?][x?][y?][z?][w?]: Generates and exports a prefab icon", Snapshot.Run, GetAllPrefabOptions); new Command("print_shader_properties", "[shaderName]", ShaderRef.PrintShaderProperties, ShaderRef.GetShaderOptions, isSecret: true); new Command("clean", "cleans modified prefab against original values to output smallest file necessary", Clean, GetModifiedPrefabNames, isSecret: false, adminOnly: true); if (Chainloader.PluginInfos.ContainsKey("com.ValheimModding.NewtonsoftJsonDetector")) { new Command("rrr", "read and convert all rrr files found in RRR folder", RRRConvert); } InitOldCommands(); } [Obsolete] private static void InitOldCommands() { new Command("write", "[PrefabID]: save creature YML to Export folder", CreatureManager.WriteCreatureYML, CreatureManager.GetCreatureOptions, isSecret: true); new Command("write_all", "save all creatures YML to Export folder", CreatureManager.WriteAllCreatureYML, null, isSecret: true); new Command("mod", "[FileName]: read YML file from Import and update", CreatureManager.ReadCreatureYML, GetYMLFileOptions, isSecret: true, adminOnly: true); new Command("revert", "[prefabName]: revert creature to factory settings", CreatureManager.ResetCreature, GetOriginalCreatureOptions, isSecret: true, adminOnly: true); new Command("clone_character", "[prefabName][newName]: must be a character", CreatureManager.CloneCreature, CreatureManager.GetCreatureOptions, isSecret: true, adminOnly: true); new Command("export_bones", "[prefabName]: export prefab hierarchy", CreatureManager.WriteHierarchy, GetAllPrefabOptions, isSecret: true); new Command("write_all_creature_spawners", "Export all creature spawner prefab YML files", CreatureSpawnerManager.WriteAllCreatureSpawners, null, isSecret: true); new Command("write_creature_spawner", "Export specific creature spawner prefab YML file", CreatureSpawnerManager.WriteCreatureSpawner, CreatureSpawnerManager.GetCreatureSpawnersOptions, isSecret: true); new Command("write_egg", "[prefabName]: save egg reference to Export folder", EggManager.WriteEggYML, EggManager.GetEggOptions, isSecret: true); new Command("write_all_egg", "save all egg references to Export folder", EggManager.WriteAllEggYML, null, isSecret: true); new Command("mod_egg", "[fileName]: read egg reference from Import folder", EggManager.ReadEgg, GetYMLFileOptions, isSecret: true, adminOnly: true); new Command("revert_egg", "[prefabName]: revert egg to factory settings", EggManager.ResetEgg, EggManager.GetResetOptions, isSecret: true, adminOnly: true); new Command("clone_egg", "[prefabName][newName]: must be an item", EggManager.CloneEgg, GetItemOptions, isSecret: true, adminOnly: true); new Command("write_fish", "[prefabName]: write fish YML to Export folder", FishManager.WriteFishYML, FishManager.GetFishOptions, isSecret: true); new Command("write_all_fish", "write all fish YML to Export folder", FishManager.WriteAllFishYML, null, isSecret: true); new Command("mod_fish", "[fileName]: read fish reference from Import folder", FishManager.UpdateFishYML, GetYMLFileOptions, isSecret: true, adminOnly: true); new Command("revert_fish", "[prefabName]: revert fish to factory settings", FishManager.ResetFish, FishManager.GetResetFishOptions, isSecret: true, adminOnly: true); new Command("clone_fish", "[prefabName][newName]: must be a fish", FishManager.CloneFish, FishManager.GetFishOptions, isSecret: true, adminOnly: true); new Command("write_item", "[prefabName]: write item YML to Export folder", ItemManager.WriteItemYML, GetItemOptions, isSecret: true); new Command("mod_item", "[fileName]: read item YML from Import folder", ItemManager.UpdateItemYML, GetYMLFileOptions, isSecret: true, adminOnly: true); new Command("revert_item", "[prefabName]: revert item to factory settings", ItemManager.ResetItem, ItemManager.GetResetItemOptions, isSecret: true, adminOnly: true); new Command("clone_item", "[prefabName][newName]: must be an item", ItemManager.CloneItem, GetItemOptions, isSecret: true, adminOnly: true); new Command("search_item", "search item by name", ItemManager.SearchItem, ItemManager.GetSearchItemOptions, isSecret: true); new Command("write_projectile", "[prefabName]", ProjectileManager.WriteProjectileYML, ProjectileManager.GetProjectileOptions, isSecret: true); new Command("clone_projectile", "[prefabName][newName]: clones projectile and writes YML file", ProjectileManager.CloneProjectile, ProjectileManager.GetProjectileOptions, isSecret: true, adminOnly: true); new Command("write_all_raids", "Export all raid events as YML files", RaidManager.WriteAllRaidYML, null, isSecret: true); new Command("write_raid", "Export specific raid event as YML file", RaidManager.WriteRaidYML, RaidManager.GetRaidOptions, isSecret: true); new Command("update_raids", "Read all raid files from Raids and update Random Event System", RaidManager.UpdateRaid, null, isSecret: true, adminOnly: true); new Command("write_spawnability", "[prefabName]: write spawn ability YML file", SpawnAbilityManager.WriteSpawnAbilityYML, SpawnAbilityManager.GetSpawnAbilityOptions, isSecret: true); new Command("clone_spawnability", "[prefabName]: clone spawn ability YML file", SpawnAbilityManager.CloneSpawnAbility, SpawnAbilityManager.GetSpawnAbilityOptions, isSecret: true, adminOnly: true); new Command("export_main_tex", "[prefabName]: export creature main texture", TextureManager.ExportMainTextures, CreatureManager.GetCreatureOptions, isSecret: true); new Command("export_tex", "[textureName]: export texture as png", TextureManager.ExportTexture, TextureManager.GetTextureOptions, isSecret: true); new Command("search_tex", "search texture names", TextureManager.SearchTextures, TextureManager.GetTextureOptions, isSecret: true); new Command("search_sprite", "search sprite names", TextureManager.SearchSprites, TextureManager.GetSpriteOptions, isSecret: true); new Command("export_sprite", "[spriteName]: export sprite texture as png", TextureManager.ExportSprite, TextureManager.GetSpriteOptions, isSecret: true); new Command("search_shader", "[query]: returns list of shader names that contains query", ShaderRef.SearchShaders, ShaderRef.GetShaderOptions, isSecret: true); new Command("write_visual", "[prefabName]: write prefab visual data YML file", VisualManager.WriteVisualYML, GetAllPrefabOptions, isSecret: true); new Command("clone_visual", "[prefabName]: clone prefab and write visual YML file", VisualManager.CloneVisual, GetAllPrefabOptions, isSecret: true, adminOnly: true); } private static List GetZNetPrefabNames(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : PrefabManager.GetAllPrefabNames()); if (1 == 0) { } return result; } private static List GetOriginalCreatureOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : LoadManager.GetOriginalKeys()); if (1 == 0) { } return result; } private static List GetAllPrefabOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : PrefabManager.GetAllPrefabNames()); if (1 == 0) { } return result; } private static List GetItemOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : PrefabManager.GetAllPrefabNames()); if (1 == 0) { } return result; } private static void CleanAll(ConsoleEventArgs args) { int num = 0; foreach (KeyValuePair item in LoadManager.modified) { if (item.Value.Clean()) { string contents = ConfigManager.Serialize(item.Value); string path = item.Value.Prefab + ".CLEANED.yml"; string path2 = Path.Combine(FileManager.ExportFolder, path); File.WriteAllText(path2, contents); num++; } } args.Context.LogInfo($"Cleaned up {num} files"); } private static void Clean(ConsoleEventArgs args) { string @string = args.GetString(2); Header value; if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("> Specify target prefab"); } else if (@string.Equals("all", StringComparison.InvariantCultureIgnoreCase)) { CleanAll(args); } else if (!LoadManager.modified.TryGetValue(@string, out value)) { args.Context.LogWarning("Failed to find modified prefab: " + @string); } else if (value.Clean()) { string contents = ConfigManager.Serialize(value); string path = value.Prefab + ".CLEANED.yml"; string text = Path.Combine(FileManager.ExportFolder, path); File.WriteAllText(text, contents); args.Context.LogInfo("Cleaned up " + @string); args.Context.LogInfo(text.RemoveRootPath() ?? ""); } else { args.Context.LogDebug("[" + @string + "] Nothing to clean up"); } } private static List GetModifiedPrefabNames(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : LoadManager.modified.Keys.Union(new <>z__ReadOnlySingleElementList("all")).ToList()); if (1 == 0) { } return result; } private static void Clone(ConsoleEventArgs args) { string @string = args.GetString(2); BaseType result; if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Specify type"); } else if (!Enum.TryParse(@string, ignoreCase: true, out result)) { args.Context.LogWarning("Invalid type"); } else { CloneBase(result, args); } } private static string GetCloneDescriptions(string[] args, string defaultValue) { if (args.Length < 3) { return defaultValue; } string value = args[2]; if (string.IsNullOrEmpty(value)) { return defaultValue; } if (!Enum.TryParse(value, ignoreCase: true, out var result)) { return defaultValue; } return string.Format("[PrefabID][Name]: Clone {1} prefab and write YML file", "#B2BEB5", result); } private static List GetCloneOptions(int i, string word) { if (1 == 0) { } List result = i switch { 2 => GetBaseTypes(BaseType.None, BaseType.All), 3 => GetCloneTypeOptions(word), _ => new List(), }; if (1 == 0) { } return result; } private static List GetCloneTypeOptions(string word) { BaseType result; return Enum.TryParse(word, ignoreCase: true, out result) ? GetCloneOptionByBase(result) : PrefabManager.GetAllPrefabNames(); } private static List GetCloneOptionByBase(BaseType type) { if (1 == 0) { } List result; switch (type) { case BaseType.Character: result = PrefabManager.GetAllPrefabNames(); break; case BaseType.Humanoid: result = PrefabManager.GetAllPrefabNames(); break; case BaseType.Egg: case BaseType.Item: case BaseType.Fish: result = PrefabManager.GetAllPrefabNames(); break; case BaseType.Projectile: result = PrefabManager.GetAllPrefabNames(); break; case BaseType.SpawnAbility: result = PrefabManager.GetAllPrefabNames(); break; case BaseType.CreatureSpawner: result = PrefabManager.GetAllPrefabNames(); break; case BaseType.Human: result = new List(1) { "Player" }; break; case BaseType.SpawnArea: result = PrefabManager.GetAllPrefabNames(); break; default: result = PrefabManager.GetAllPrefabNames(); break; } if (1 == 0) { } return result; } private static void CloneBase(BaseType baseType, ConsoleEventArgs args) { string @string = args.GetString(3); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Specify prefab"); return; } string string2 = args.GetString(4); if (string.IsNullOrEmpty(string2)) { args.Context.LogWarning("Specify new name"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); return; } if (CloneManager.IsClone(((Object)prefab).name, out var sourceName)) { args.Context.LogWarning("Already a clone of " + sourceName); return; } GameObject clone; switch (baseType) { case BaseType.Humanoid: case BaseType.Character: case BaseType.Human: CreatureManager.Clone(prefab, string2, write: true, args.Context); break; case BaseType.Egg: if (!EggManager.TryClone(prefab, string2)) { args.Context.LogWarning("Failed to clone egg " + @string); } break; case BaseType.Item: if (!ItemManager.TryClone(prefab, string2, out clone, write: true, "", args.Context)) { args.Context.LogWarning("Failed to clone item " + @string); } break; case BaseType.Fish: if (!FishManager.TryClone(prefab, string2, write: true, args.Context)) { args.Context.LogWarning("Failed to clone fish " + @string); } break; case BaseType.Projectile: if (!ProjectileManager.TryClone(prefab, string2, out clone, write: true, "", args.Context)) { args.Context.LogWarning("Failed to clone projectile " + @string); } break; case BaseType.SpawnAbility: if (!SpawnAbilityManager.TryClone(prefab, string2, out clone, write: true, "", args.Context)) { args.Context.LogWarning("Failed to clone spawn ability " + @string); } break; case BaseType.Visual: if (!VisualManager.TryClone(prefab, string2, out clone, write: true, "", args.Context)) { args.Context.LogWarning("Failed to clone prefab " + @string); } break; case BaseType.CreatureSpawner: if (!CreatureSpawnerManager.TryClone(prefab, string2, write: true, args.Context)) { args.Context.LogWarning("Failed to clone creature spawner " + @string); } break; case BaseType.Ragdoll: if (!RagdollManager.TryClone(prefab, string2, out clone, write: true, "", args.Context)) { args.Context.LogWarning("Failed to clone ragdoll " + @string); } break; case BaseType.SpawnArea: if (!SpawnAreaManager.TryClone(prefab, string2, write: true, args.Context)) { args.Context.LogWarning("Failed to clone spawn area " + ((Object)prefab).name); } break; default: args.Context.LogWarning("Invalid type"); break; } } private static List GetConvertOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : LegacyManager.creaturesToConvert.Keys.Append("all").ToList()); if (1 == 0) { } return result; } private static string GetConvertDescription(string[] args, string defaultValue) { if (args.Length < 3) { return defaultValue; } string text = args[2]; if (string.IsNullOrEmpty(text)) { return defaultValue; } return "Convert " + text + " legacy file into v.0.2.x format"; } private static void Convert(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); } else if (@string.Equals("all", StringComparison.CurrentCultureIgnoreCase)) { LegacyManager.ConvertAll(args); } else { LegacyManager.Convert(args); } } private static List GetBaseTypes(params BaseType[] ignoreTypes) { return (from BaseType type in Enum.GetValues(typeof(BaseType)) where !ignoreTypes.Contains(type) select type).Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (BaseType type) => { BaseType baseType = type; return baseType.ToString(); }).ToList(); } private static List GetExportOptions(int i, string word) { if (1 == 0) { } List result = i switch { 2 => ExportOptions, 3 => GetExportTypeOptions(word), _ => new List(), }; if (1 == 0) { } return result; } private static List GetExportTypeOptions(string word) { if (1 == 0) { } BaseType result; List result2 = word switch { "texture" => TextureManager.GetAllTextures().Keys.Union(PrefabManager.GetAllPrefabNames()).ToList(), "sprite" => TextureManager.GetAllSprites().Keys.ToList(), "raid" => RaidManager.GetRaidNames().Append("all").ToList(), "uv" => PrefabManager.GetAllPrefabNames().ToList(), _ => Enum.TryParse(word, ignoreCase: true, out result) ? GetOptionsByBase(result) : PrefabManager.GetAllPrefabNames(), }; if (1 == 0) { } return result2; } private static List GetOptionsByBase(BaseType type) { if (1 == 0) { } List result = type switch { BaseType.Character => PrefabManager.GetAllPrefabNames().Append("all").ToList(), BaseType.Humanoid => PrefabManager.GetAllPrefabNames().Append("all").ToList(), BaseType.Egg => PrefabManager.GetAllPrefabNames().Append("all").ToList(), BaseType.Item => PrefabManager.GetAllPrefabNames(), BaseType.Fish => PrefabManager.GetAllPrefabNames().Append("all").ToList(), BaseType.Projectile => PrefabManager.GetAllPrefabNames(), BaseType.SpawnAbility => PrefabManager.GetAllPrefabNames(), BaseType.CreatureSpawner => PrefabManager.GetAllPrefabNames().Append("all").ToList(), BaseType.SpawnArea => PrefabManager.GetAllPrefabNames().Append("all").ToList(), BaseType.Human => new List(1) { "Player" }, BaseType.All => new List(), BaseType.SpawnData => SpawnManager.GetCachedSpawnDataIds(), _ => PrefabManager.GetAllPrefabNames(), }; if (1 == 0) { } return result; } private static string GetExportDescriptions(string[] args, string defaultValue) { if (args.Length < 3) { return defaultValue; } string text = args[2]; if (string.IsNullOrEmpty(text)) { return defaultValue; } if (1 == 0) { } BaseType result; string result2 = text switch { "texture" => "[TextureID]: Export texture png", "sprite" => "[SpriteID]: Export sprite png", "raid" => "[EventName]: Export raid YML file", "bones" => "[PrefabID]: Export prefab hierarchy", "uv" => "[PrefabID][BkgColor?][LineColor?]: Export prefab UVs", _ => (!Enum.TryParse(text, ignoreCase: true, out result)) ? defaultValue : ((result == BaseType.All) ? "Export Aggregate YML file of all imported YML files" : string.Format("[PrefabID]: Export {1} YML file", "#B2BEB5", result)), }; if (1 == 0) { } return result2; } private static void Export(ConsoleEventArgs args) { string @string = args.GetString(2); BaseType result; if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Specify type"); } else if (!Enum.TryParse(@string, ignoreCase: true, out result)) { switch (@string) { case "texture": TextureManager.ExportTextureOrPrefabTextures(args.Context, args.GetStringFrom(3)); break; case "sprite": TextureManager.ExportSprite(args.Context, args.GetStringFrom(3)); break; case "raid": RaidManager.WriteRaidYML(args.Context, args.GetString(3)); break; case "bones": CreatureManager.WriteHierarchy(args.Context, args.GetString(3)); break; case "uv": UV.ExportMaps(args.Context, args.GetString(3), args.GetString(4), args.GetString(5)); break; } } else { ExportBase(result, args); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] private static void ExportAllCharacters(Terminal context = null) { List allPrefabs = PrefabManager.GetAllPrefabs(); for (int i = 0; i < allPrefabs.Count; i++) { GameObject val = allPrefabs[i]; string sourceName; bool isClone = CloneManager.IsClone(((Object)val).name, out sourceName); if (!CreatureManager.Write(val, isClone, sourceName, context)) { context?.LogError("Failed to export character " + ((Object)val).name); } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] private static void ExportAllEggs(Terminal context = null) { List allPrefabs = PrefabManager.GetAllPrefabs(); for (int i = 0; i < allPrefabs.Count; i++) { GameObject val = allPrefabs[i]; string sourceName; bool isClone = CloneManager.IsClone(((Object)val).name, out sourceName); if (!EggManager.Write(val, isClone, sourceName, context)) { context?.LogWarning("Failed to export egg " + ((Object)val).name); } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] private static void ExportAllItems(Terminal context = null) { List allPrefabs = PrefabManager.GetAllPrefabs(); for (int i = 0; i < allPrefabs.Count; i++) { GameObject val = allPrefabs[i]; string sourceName; bool isClone = CloneManager.IsClone(((Object)val).name, out sourceName); if (!ItemManager.Write(val, isClone, sourceName, "", context)) { context?.LogWarning("Failed to export item " + ((Object)val).name); } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] private static void ExportAllFish(Terminal context = null) { List allPrefabs = PrefabManager.GetAllPrefabs(); for (int i = 0; i < allPrefabs.Count; i++) { GameObject val = allPrefabs[i]; string sourceName; bool isClone = CloneManager.IsClone(((Object)val).name, out sourceName); if (!FishManager.Write(val, isClone, sourceName, context)) { context?.LogWarning("Failed to export fish " + ((Object)val).name); } } } private static void ExportBase(BaseType baseType, ConsoleEventArgs args) { if (baseType == BaseType.All) { FileManager.Export(FileManager.ImportFolder); args.Context.LogInfo("Exported all MonsterDB imported files into a single aggregated file."); return; } string @string = args.GetString(3); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Specify prefab"); return; } if (baseType == BaseType.SpawnData) { @string = args.GetStringFrom(3); if (SpawnManager.Export(@string, out var filepath)) { args.Context.LogInfo("Exported " + @string + " Spawn Data"); args.Context.LogInfo(filepath.RemoveRootPath()); } else { args.Context.LogError("Failed to export " + @string + " spawn data"); } return; } if (@string == "all") { switch (baseType) { case BaseType.Humanoid: case BaseType.Character: case BaseType.Human: ExportAllCharacters(args.Context); break; case BaseType.Egg: ExportAllEggs(args.Context); break; case BaseType.Item: ExportAllItems(args.Context); break; case BaseType.Fish: ExportAllFish(args.Context); break; default: args.Context.LogWarning($"Export {baseType} all not supported"); break; } return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); return; } string sourceName; bool isClone = CloneManager.IsClone(((Object)prefab).name, out sourceName); switch (baseType) { case BaseType.Humanoid: case BaseType.Character: case BaseType.Human: if (!CreatureManager.Write(prefab, isClone, sourceName, args.Context)) { args.Context.LogError($"Failed to export {baseType} {((Object)prefab).name}"); } break; case BaseType.Egg: if (!EggManager.Write(prefab, isClone, sourceName, args.Context)) { args.Context.LogError($"Failed to export {baseType} {((Object)prefab).name}"); } break; case BaseType.Item: if (!ItemManager.Write(prefab, isClone, sourceName, "", args.Context)) { args.Context.LogError($"Failed to export {baseType} {((Object)prefab).name}"); } break; case BaseType.Fish: if (!FishManager.Write(prefab, isClone, sourceName, args.Context)) { args.Context.LogError($"Failed to export {baseType} {((Object)prefab).name}"); } break; case BaseType.Projectile: if (!ProjectileManager.Write(prefab, isClone, sourceName)) { args.Context.LogError($"Failed to export {baseType} {((Object)prefab).name}"); } break; case BaseType.SpawnAbility: if (!SpawnAbilityManager.Write(prefab, isClone, sourceName, "", args.Context)) { args.Context.LogError($"Failed to export {baseType} {((Object)prefab).name}"); } break; case BaseType.Visual: if (!VisualManager.Write(prefab, isClone, sourceName, "", args.Context)) { args.Context.LogError($"Failed to export {baseType} {((Object)prefab).name}"); } break; case BaseType.CreatureSpawner: if (!CreatureSpawnerManager.Write(prefab, isClone, sourceName, args.Context)) { args.Context.LogError($"Failed to export {baseType} {((Object)prefab).name}"); } break; case BaseType.SpawnArea: if (!SpawnAreaManager.Write(prefab, isClone, sourceName, "", args.Context)) { args.Context.LogError($"Failed to export {baseType} {((Object)prefab).name}"); } break; case BaseType.Ragdoll: break; } } private static void Revert(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Specify type"); return; } string text = @string; string text2 = text; if (Enum.TryParse(@string, ignoreCase: true, out var result)) { RevertBase(result, args); } else { args.Context.LogWarning("Invalid type"); } } private static void RevertBase(BaseType baseType, ConsoleEventArgs args) { string @string = args.GetString(3); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Specify prefab"); return; } switch (baseType) { case BaseType.None: break; case BaseType.All: LoadManager.ResetAll
(); args.Context.LogInfo("Reverted All"); break; default: LoadManager.Reset
(@string); args.Context.LogInfo("Reverted " + @string); break; } } private static List GetRevertOptions(int i, string word) { if (1 == 0) { } BaseType result; List result2 = i switch { 2 => GetBaseTypes(), 3 => Enum.TryParse(word, ignoreCase: true, out result) ? GetCloneOptionByBase(result) : PrefabManager.GetAllPrefabNames(), _ => new List(), }; if (1 == 0) { } return result2; } private static void RRRConvert(ConsoleEventArgs args) { RRRConverter.Read(); RRRConverter.ConvertAll(args); } private static List GetSearchOptions(int i, string word) { if (1 == 0) { } List result = i switch { 2 => SearchTypes, 3 => GetSearchTypeOptions(word), _ => new List(), }; if (1 == 0) { } return result; } private static List GetSearchTypeOptions(string word) { if (1 == 0) { } List result; switch (word) { case "item": result = PrefabManager.SearchCache(""); break; case "texture": case "tex": result = TextureManager.GetAllTextures().Keys.ToList(); break; case "shader": result = ShaderRef.GetShaderNames(); break; case "sprite": result = TextureManager.GetSpriteNames(); break; default: result = new List(); break; } if (1 == 0) { } return result; } private static string GetSearchDescriptions(string[] args, string defaultValue) { if (args.Length < 3) { return defaultValue; } string text = args[2]; if (string.IsNullOrEmpty(text)) { return defaultValue; } return "[Query]: Search " + text + " by name"; } private static void Search(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Specify type"); return; } string stringFrom = args.GetStringFrom(3); if (string.IsNullOrEmpty(stringFrom)) { args.Context.LogWarning("Specify query"); return; } switch (@string) { case "item": { List list2 = PrefabManager.SearchCache(stringFrom); for (int l = 0; l < list2.Count; l++) { string text4 = list2[l]; args.Context.LogDebug("- " + text4); MonsterDBPlugin.LogInfo(text4); } break; } case "texture": case "tex": { List list = TextureManager.GetAllTextures().Keys.ToList(); for (int j = 0; j < list.Count; j++) { string text2 = list[j]; if (text2.ToLower().Contains(stringFrom.ToLower())) { args.Context.LogDebug("- " + text2); MonsterDBPlugin.LogInfo(text2); } } break; } case "shader": { List shaderNames = ShaderRef.GetShaderNames(); for (int k = 0; k < shaderNames.Count; k++) { string text3 = shaderNames[k]; if (text3.ToLower().Contains(stringFrom.ToLower())) { args.Context.LogDebug("- " + text3); MonsterDBPlugin.LogInfo(text3); } } break; } case "sprite": { List spriteNames = TextureManager.GetSpriteNames(); for (int i = 0; i < spriteNames.Count; i++) { string text = spriteNames[i]; if (text.ToLower().Contains(stringFrom.ToLower())) { args.Context.LogDebug("- " + text); MonsterDBPlugin.LogInfo(text); } } break; } } } private static void Update(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameter"); } else if (@string.Equals("all", StringComparison.CurrentCultureIgnoreCase)) { List modFileNames = FileManager.GetModFileNames(); for (int i = 0; i < modFileNames.Count; i++) { string filePath = Path.Combine(FileManager.ImportFolder, modFileNames[i] + ".yml"); FileManager.Read(filePath); args.Context.LogInfo("Updated " + modFileNames[i]); } } else if (@string.Equals("raids", StringComparison.CurrentCultureIgnoreCase)) { RaidManager.Read(); RaidManager.Update(); args.Context.LogInfo("Updated all raids"); } else { string filePath2 = Path.Combine(FileManager.ImportFolder, @string + ".yml"); FileManager.Read(filePath2); args.Context.LogInfo("Updated " + @string); } } private static List GetYMLFileOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : FileManager.GetModFileNames().ToList()); if (1 == 0) { } return result; } private static List GetUpdateOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : FileManager.GetModFileNames().Union(new <>z__ReadOnlyArray(new string[2] { "all", "raids" })).ToList()); if (1 == 0) { } return result; } } public enum Toggle { On = 1, Off = 0 } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class ConfigManager { private static readonly FieldPrefixStrippingNamingConvention NamingConvention; private static readonly ISerializer serializer; private static readonly ISerializer fullSerializer; private static readonly IDeserializer deserializer; private static readonly ConfigFile Config; public static readonly ConfigSync ConfigSync; private static readonly string ConfigFileName; private static readonly string ConfigFileFullPath; public static readonly string DirectoryPath; private static readonly ConfigEntry logLevels; private static readonly ConfigEntry detailedDebugLogs; private static readonly ConfigEntry fullFile; public static T Deserialize<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(string data) { return deserializer.Deserialize(data); } public static string Serialize<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T obj, bool full = true) { if (obj == null) { return ""; } using StringWriter stringWriter = new StringWriter(); if (fullFile.Value == Toggle.On && full) { fullSerializer.Serialize(stringWriter, obj, obj.GetType()); } else { serializer.Serialize(stringWriter, obj, obj.GetType()); } return stringWriter.ToString(); } public static bool ShouldLog(LogLevel type) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) return ((Enum)logLevels.Value).HasFlag((Enum)(object)type); } public static bool ShouldLogDetails() { return detailedDebugLogs.Value == Toggle.On; } static ConfigManager() { NamingConvention = new FieldPrefixStrippingNamingConvention("m_"); serializer = new SerializerBuilder().ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull | DefaultValuesHandling.OmitDefaults | DefaultValuesHandling.OmitEmptyCollections).DisableAliases().WithNamingConvention(NamingConvention) .WithTypeConverter(InvariantCultureFloatConverter.Instance) .WithTypeConverter(VectorConverter.Instance) .Build(); fullSerializer = new SerializerBuilder().DisableAliases().WithNamingConvention(NamingConvention).WithTypeConverter(InvariantCultureFloatConverter.Instance) .Build(); deserializer = new DeserializerBuilder().IgnoreUnmatchedProperties().WithNamingConvention(NamingConvention).WithTypeConverter(FactionConverter.Instance) .WithTypeConverter(VectorConverter.Instance) .WithTypeConverter(InvariantCultureFloatConverter.Instance) .Build(); Config = ((BaseUnityPlugin)MonsterDBPlugin.instance).Config; ConfigFileName = "RustyMods.MonsterDB.cfg"; ConfigFileFullPath = Path.Combine(Paths.ConfigPath, ConfigFileName); ConfigSync = new ConfigSync("RustyMods.MonsterDB") { DisplayName = "MonsterDB", CurrentVersion = "0.3.5", MinimumRequiredVersion = "0.3.5" }; DirectoryPath = Path.Combine(Paths.ConfigPath, "MonsterDB"); if (!Directory.Exists(DirectoryPath)) { Directory.CreateDirectory(DirectoryPath); } ConfigEntry lockingConfig = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only."); ConfigSync.AddLockingConfigEntry(lockingConfig); logLevels = config("1 - General", "Log Levels", (LogLevel)63, "Set log levels", synchronizedSetting: false); detailedDebugLogs = config("1 - General", "Detailed Debug Logs", Toggle.Off, "If on, debug logs will be detailed", synchronizedSetting: false); fullFile = config("1 - General", "Full File", Toggle.Off, "If on, exported YML will display all fields", synchronizedSetting: false); } public static void Start() { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown Harmony harmony = MonsterDBPlugin.harmony; harmony.Patch((MethodBase)AccessTools.Method(typeof(ZNet), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(ConfigManager), "Patch_ZNet_Awake", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static void Patch_ZNet_Awake(ZNet __instance) { FactionManager.Init(__instance); LoadManager.Init(__instance); SpawnManager.Init(__instance); RaidManager.Init(__instance); LocalizationManager.Init(__instance); } public static void SetupWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private static void ReadConfigValues(object sender, FileSystemEventArgs e) { if (!File.Exists(ConfigFileFullPath)) { return; } try { MonsterDBPlugin.LogDebug("ReadConfigValues called"); Config.Reload(); } catch { MonsterDBPlugin.LogError("There was an issue loading your " + ConfigFileName); MonsterDBPlugin.LogError("Please check your config entries for spelling and format!"); } } public static ConfigEntry config<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry val2 = Config.Bind(group, name, value, val); SyncedConfigEntry syncedConfigEntry = ConfigSync.AddConfigEntry(val2); syncedConfigEntry.SynchronizedConfig = synchronizedSetting; return val2; } public static ConfigEntry config<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty()), synchronizedSetting); } } public class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [UsedImplicitly] public string Category; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [UsedImplicitly] public Action CustomDrawer; } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public sealed class FieldPrefixStrippingNamingConvention : INamingConvention { [CompilerGenerated] [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string P; public FieldPrefixStrippingNamingConvention(string prefix) { P = prefix; base..ctor(); } public string Apply(string value) { return value.StartsWith(P) ? value.Substring(P.Length) : value; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public sealed class FactionConverter : IYamlTypeConverter { public static readonly IYamlTypeConverter Instance = new FactionConverter(); public bool Accepts(Type type) { return (Nullable.GetUnderlyingType(type) ?? type) == typeof(Faction); } public object ReadYaml(IParser parser, Type type) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) YamlDotNet.Core.Events.Scalar scalar = parser.Consume(); return FactionManager.GetFaction(scalar.Value); } public void WriteYaml(IEmitter emitter, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] object value, Type type) { //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) if (value != null) { Faction val = (Faction)value; emitter.Emit(new YamlDotNet.Core.Events.Scalar(((object)(Faction)(ref val)).ToString())); } } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public sealed class VectorConverter : IYamlTypeConverter { public static readonly VectorConverter Instance = new VectorConverter(); public bool Accepts(Type type) { return (Nullable.GetUnderlyingType(type) ?? type) == typeof(Vector3Ref); } public object ReadYaml(IParser parser, Type type) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) if (parser.Current is YamlDotNet.Core.Events.Scalar scalar) { parser.MoveNext(); float num = float.Parse(scalar.Value.Replace(',', '.'), CultureInfo.InvariantCulture); return (object)new Vector3(num, num, num); } parser.Consume(); float x = 1f; float y = 1f; float z = 1f; MappingEnd @event; while (!parser.TryConsume(out @event)) { string value = parser.Consume().Value; string value2 = parser.Consume().Value; switch (value.ToLower()) { case "x": x = float.Parse(value2.Replace(',', '.'), CultureInfo.InvariantCulture); break; case "y": y = float.Parse(value2.Replace(',', '.'), CultureInfo.InvariantCulture); break; case "z": z = float.Parse(value2.Replace(',', '.'), CultureInfo.InvariantCulture); break; } } return new Vector3Ref(x, y, z); } public void WriteYaml(IEmitter emitter, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] object value, Type type) { if (!(value is Vector3Ref)) { return; } Vector3Ref vector3Ref = (Vector3Ref)value; if (true) { if (Mathf.Approximately(vector3Ref.x, vector3Ref.y) && Mathf.Approximately(vector3Ref.y, vector3Ref.z)) { emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, vector3Ref.x.ToString(CultureInfo.InvariantCulture), ScalarStyle.Plain, isPlainImplicit: true, isQuotedImplicit: false)); return; } emitter.Emit(new MappingStart()); emitter.Emit(new YamlDotNet.Core.Events.Scalar("x")); emitter.Emit(new YamlDotNet.Core.Events.Scalar(vector3Ref.x.ToString(CultureInfo.InvariantCulture))); emitter.Emit(new YamlDotNet.Core.Events.Scalar("y")); emitter.Emit(new YamlDotNet.Core.Events.Scalar(vector3Ref.y.ToString(CultureInfo.InvariantCulture))); emitter.Emit(new YamlDotNet.Core.Events.Scalar("z")); emitter.Emit(new YamlDotNet.Core.Events.Scalar(vector3Ref.z.ToString(CultureInfo.InvariantCulture))); emitter.Emit(new MappingEnd()); } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public sealed class InvariantCultureFloatConverter : IYamlTypeConverter { public static readonly InvariantCultureFloatConverter Instance = new InvariantCultureFloatConverter(); public bool Accepts(Type type) { return type == typeof(float) || type == typeof(double) || type == typeof(decimal); } public object ReadYaml(IParser parser, Type type) { YamlDotNet.Core.Events.Scalar scalar = parser.Consume(); if (1 == 0) { } object result; if (type == typeof(float)) { result = float.Parse(scalar.Value, CultureInfo.InvariantCulture); } else if (type == typeof(double)) { result = double.Parse(scalar.Value, CultureInfo.InvariantCulture); } else { if (!(type == typeof(decimal))) { throw new NotSupportedException(); } result = decimal.Parse(scalar.Value, CultureInfo.InvariantCulture); } if (1 == 0) { } return result; } public void WriteYaml(IEmitter emitter, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] object value, Type type) { if (1 == 0) { } string text; if (!(value is float num)) { if (!(value is double num2)) { if (!(value is decimal num3)) { throw new NotSupportedException(); } text = num3.ToString(CultureInfo.InvariantCulture); } else { text = num2.ToString(CultureInfo.InvariantCulture); } } else { text = num.ToString(CultureInfo.InvariantCulture); } if (1 == 0) { } string value2 = text; emitter.Emit(new YamlDotNet.Core.Events.Scalar(value2)); } } public enum ConversionType { Fermenter, CookingStation, Smelter } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class ItemConversionRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_prefab; public ConversionType? m_type; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_from; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_to; public int? m_producedItems; public float? m_cookTime; public bool TryToFermenterConversion(out ItemConversion conversion) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown conversion = new ItemConversion(); if (!TryGetItems(out var from, out var to)) { return false; } conversion.m_from = from; conversion.m_to = to; conversion.m_producedItems = m_producedItems.GetValueOrDefault(1); return true; } public bool TryToSmelterConversion(out ItemConversion conversion) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown conversion = new ItemConversion(); if (!TryGetItems(out var from, out var to)) { return false; } conversion.m_from = from; conversion.m_to = to; return true; } public bool TryToCookingConversion(out ItemConversion conversion) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown conversion = new ItemConversion(); if (!TryGetItems(out var from, out var to)) { return false; } conversion.m_from = from; conversion.m_to = to; conversion.m_cookTime = m_cookTime.GetValueOrDefault(5f); return true; } private bool TryGetItems(out ItemDrop from, out ItemDrop to) { from = null; to = null; if (m_from == null || m_to == null) { return false; } GameObject prefab = PrefabManager.GetPrefab(m_from); GameObject prefab2 = PrefabManager.GetPrefab(m_to); if ((Object)(object)prefab == (Object)null || (Object)(object)prefab2 == (Object)null) { return false; } if (!prefab.TryGetComponent(ref from) || !prefab2.TryGetComponent(ref to)) { return false; } return true; } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public sealed class BaseCreatureSpawner : Header { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 6)] public CreatureSpawnerRef CreatureSpawner; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 7)] public RandomSpawnRef RandomSpawn; public BaseCreatureSpawner() { } public BaseCreatureSpawner(GameObject prefab, bool isClone = false, string clonedFrom = "") { Setup(prefab, isClone, clonedFrom); } public override void Setup(GameObject prefab, bool isClone = false, string source = "") { base.Setup(prefab, isClone, source); Type = BaseType.CreatureSpawner; Prefab = ((Object)prefab).name; ClonedFrom = source; IsCloned = isClone; SetupCreatureSpawner(prefab); SetupRandomSpawn(prefab); } public void SetupCreatureSpawner(GameObject prefab) { CreatureSpawner component = default(CreatureSpawner); if (prefab.TryGetComponent(ref component)) { CreatureSpawner = new CreatureSpawnerRef(component); } } public void SetupRandomSpawn(GameObject prefab) { RandomSpawn component = default(RandomSpawn); if (prefab.TryGetComponent(ref component)) { RandomSpawn = new RandomSpawnRef(component); } } public override void CopyFields(Header original) { base.CopyFields(original); if (original is BaseCreatureSpawner baseCreatureSpawner && CreatureSpawner != null && baseCreatureSpawner.CreatureSpawner != null) { CreatureSpawner.ResetTo(baseCreatureSpawner.CreatureSpawner); } } public override void Update() { GameObject prefab = PrefabManager.GetPrefab(Prefab); if (!((Object)(object)prefab == (Object)null)) { UpdatePrefab(prefab); base.Update(); LoadManager.files.PrefabToUpdate = Prefab; LoadManager.files.Add(this); } } private void UpdatePrefab(GameObject prefab) { UpdateCreatureSpawner(prefab); } private void UpdateCreatureSpawner(GameObject prefab) { CreatureSpawner target = default(CreatureSpawner); if (CreatureSpawner != null && prefab.TryGetComponent(ref target)) { CreatureSpawner.UpdateFields(target, ((Object)prefab).name, log: true); } } private void UpdateRandomSpawn(GameObject prefab) { RandomSpawn target = default(RandomSpawn); if (RandomSpawn != null && prefab.TryGetComponent(ref target)) { RandomSpawn.UpdateFields(target, ((Object)prefab).name, log: true); } } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class CreatureSpawnerManager { [Obsolete] public static void WriteAllCreatureSpawners(ConsoleEventArgs args) { foreach (GameObject allPrefab in PrefabManager.GetAllPrefabs()) { bool isClone = false; string source = ""; if (CloneManager.clones.TryGetValue(((Object)allPrefab).name, out var value)) { isClone = true; source = value.SourceName; } Write(allPrefab, isClone, source); } } [Obsolete] public static void WriteCreatureSpawner(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab " + @string); return; } if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { args.Context.LogWarning("Prefab " + @string + " is not a CreatureSpawner"); return; } string sourceName; bool isClone = CloneManager.IsClone(((Object)prefab).name, out sourceName); Write(prefab, isClone, sourceName); } [Obsolete] public static List GetCreatureSpawnersOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : PrefabManager.GetAllPrefabNames()); if (1 == 0) { } return result; } public static bool Write(GameObject prefab, bool isClone, string source, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { string contents = Save(prefab, isClone, source); string text = Path.Combine(FileManager.ExportFolder, ((Object)prefab).name + ".yml"); File.WriteAllText(text, contents); context?.LogInfo("Exported Creature Spawner " + ((Object)prefab).name); context?.LogInfo(text.RemoveRootPath()); return true; } private static string Save(GameObject prefab, bool isClone, string clonedFrom) { BaseCreatureSpawner original = LoadManager.GetOriginal(((Object)prefab).name); if (original != null) { return ConfigManager.Serialize(original); } original = new BaseCreatureSpawner(prefab, isClone, clonedFrom); LoadManager.originals.Add(((Object)prefab).name, original); return ConfigManager.Serialize(original); } public static bool TryClone(GameObject source, string cloneName, bool write = true, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (CloneManager.prefabs.ContainsKey(cloneName)) { context?.LogWarning("Clone " + cloneName + " already exists"); return false; } if (!Object.op_Implicit((Object)(object)source.GetComponent())) { context?.LogWarning(((Object)source).name + " missing Creature Spawner component"); return false; } Clone clone = new Clone(source, cloneName); clone.OnCreated += delegate(GameObject p) { MonsterDBPlugin.LogDebug("Cloned " + ((Object)source).name + " as " + cloneName); if (write) { Write(p, isClone: true, ((Object)source).name, context); } }; clone.Create(); context?.LogInfo("Cloned " + ((Object)source).name + " as " + cloneName); return true; } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class CreatureSpawnerRef : Reference { public string m_creaturePrefab; [YamlMember(Description = "Level")] public int? m_maxLevel = 1; public int? m_minLevel = 1; public float? m_levelupChance = 10f; [YamlMember(Description = "Spawn settings", Alias = "m_respawnTimeMinutes")] public float? m_respawnTimeMinuts = 20f; public float? m_triggerDistance = 60f; public float? m_triggerNoise; public bool? m_spawnAtNight = true; public bool? m_spawnAtDay = true; public bool? m_requireSpawnArea; public bool? m_spawnInPlayerBase; public bool? m_wakeUpAnimation; public int? m_spawnInterval = 5; public string m_requiredGlobalKey = ""; public string m_blockingGlobalKey = ""; public bool? m_setPatrolSpawnPoint; [YamlMember(Description = "Spawn group blocking, Spawners sharing the same ID within eachothers radiuses will be grouped together, and will never spawn more than the specified max group size. Weight will also be taken into account, prioritizing those with higher weight randomly.")] public int? m_spawnGroupID; public int? m_maxGroupSpawned = 1; public float? m_spawnGroupRadius; public float? m_spawnerWeight = 1f; public EffectListRef m_spawnEffects; public CreatureSpawnerRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public CreatureSpawnerRef(CreatureSpawner component) { Setup(component); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class RandomSpawnRef : Reference { [YamlMember(Description = "Visual enabled while not spawning")] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_OffObject; [YamlMember(Description = "0.0 - 100.0")] public float? m_chanceToSpawn = 50f; public Theme? m_dungeonRequireTheme; public Biome? m_requireBiome; public bool? m_notInLava; [YamlMember(Description = "Elevation span (water is 30)")] public int? m_minElevation = -10000; public int? m_maxElevation = 10000; public RandomSpawnRef() { } public RandomSpawnRef(RandomSpawn component) { Setup(component); } protected override void UpdateGameObject<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, string targetName, string goName, bool log) { object obj = target; RandomSpawn val = (RandomSpawn)((obj is RandomSpawn) ? obj : null); if (val == null) { return; } if (string.IsNullOrEmpty(goName)) { targetField.SetValue(target, null); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": null"); } return; } Transform val2 = Utils.FindChild(((Component)val).transform, goName, (IterativeSearchType)0); if ((Object)(object)val2 != (Object)null) { targetField.SetValue(target, ((Component)val2).gameObject); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + ((Object)val2).name); } } } } [Serializable] public class AnimalAIRef : BaseAIRef { public float? m_timeToSafe; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_consumeItems; public float? m_consumeRange; public float? m_consumeSearchRange; public float? m_consumeSearchInterval; public AnimalAIRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public AnimalAIRef(AnimalAI ai) { Setup(ai); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class BaseAIRef : Reference { public float? m_viewRange; public float? m_viewAngle; public float? m_hearRange; public bool? m_mistVision; public EffectListRef m_alertedEffects; public EffectListRef m_idleSound; public float? m_idleSoundInterval; public float? m_idleSoundChance; public AgentType? m_pathAgentType; public float? m_moveMinAngle; public bool? m_smoothMovement; public bool? m_serpentMovement; public float? m_serpentTurnRadius; public float? m_jumpInterval; public float? m_randomCircleInterval; public float? m_randomMoveInterval; public float? m_randomMoveRange; public bool? m_randomFly; public float? m_chanceToTakeoff; public float? m_chanceToLand; [YamlMember(Description = "Flying")] public float? m_groundDuration; public float? m_airDuration; public float? m_maxLandAltitude; public float? m_takeoffTime; public float? m_flyAltitudeMin; public float? m_flyAltitudeMax; public float? m_flyAbsMinAltitude; public bool? m_avoidFire; public bool? m_afraidOfFire; public bool? m_avoidWater; public bool? m_avoidLava; public bool? m_skipLavaTargets; public bool? m_avoidLavaFlee; public bool? m_aggravatable; [YamlMember(Alias = "m_passiveAggressive")] public bool? m_passiveAggresive; public string m_spawnMessage; public string m_deathMessage; public string m_alertedMessage; public float? m_fleeRange; public float? m_fleeAngle; public float? m_fleeInterval; public bool? m_patrol; } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class MonsterAIRef : BaseAIRef { public float? m_alertRange; public bool? m_fleeIfHurtWhenTargetCantBeReached; public float? m_fleeUnreachableSinceAttacking; public float? m_fleeUnreachableSinceHurt; public bool? m_fleeIfNotAlerted; public float? m_fleeIfLowHealth; public float? m_fleeTimeSinceHurt; public bool? m_fleeInLava; public float? m_fleePheromoneMin; public float? m_fleePheromoneMax; public bool? m_circulateWhileCharging; public bool? m_circulateWhileChargingFlying; public bool? m_enableHuntPlayer; public bool? m_attackPlayerObjects; [YamlMember(Alias = "m_privateAreaTriggerThreshold")] public int? m_privateAreaTriggerTreshold; public float? m_interceptTimeMax; public float? m_interceptTimeMin; public float? m_maxChaseDistance; public float? m_minAttackInterval; public float? m_circleTargetInterval; public float? m_circleTargetDuration; public float? m_circleTargetDistance; public bool? m_sleeping; public float? m_wakeupRange; public bool? m_noiseWakeup; public float? m_maxNoiseWakeupRange; public EffectListRef m_wakeupEffects; public EffectListRef m_sleepEffects; public float? m_wakeUpDelayMin; public float? m_wakeUpDelayMax; public float? m_fallAsleepDistance; public bool? m_avoidLand; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [YamlMember(Description = "Tameable")] public List m_consumeItems; public float? m_consumeRange; public float? m_consumeSearchRange; public float? m_consumeSearchInterval; public MonsterAIRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public MonsterAIRef(MonsterAI ai) { Setup(ai); } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class CharacterRef : Reference { [YamlMember(Order = 0)] public string m_name; [YamlMember(Order = 1)] public string m_group; [YamlMember(Order = 2)] public Faction? m_faction; [YamlMember(Order = 3)] public bool? m_boss; [YamlMember(Order = 4)] public bool? m_dontHideBossHud; [YamlMember(Order = 5)] public string m_bossEvent; [YamlMember(Order = 6)] public string m_defeatSetGlobalKey; [YamlMember(Order = 7)] public bool? m_aiSkipTarget; [YamlMember(Order = 8, Description = "Speed")] public float? m_crouchSpeed; [YamlMember(Order = 9)] public float? m_walkSpeed; [YamlMember(Order = 10)] public float? m_speed; [YamlMember(Order = 11)] public float? m_turnSpeed; [YamlMember(Order = 12)] public float? m_runSpeed; [YamlMember(Order = 13)] public float? m_runTurnSpeed; [YamlMember(Order = 14)] public float? m_acceleration; [YamlMember(Order = 15, Description = "Jumping")] public float? m_jumpForce; [YamlMember(Order = 16)] public float? m_jumpForceForward; [YamlMember(Order = 17)] public float? m_jumpForceTiredFactor; [YamlMember(Order = 18)] public float? m_airControl; [YamlMember(Order = 19)] public float? m_jumpStaminaUsage; [YamlMember(Order = 20, Description = "Flying")] public bool? m_flying; [YamlMember(Order = 21)] public float? m_flySlowSpeed; [YamlMember(Order = 22)] public float? m_flyFastSpeed; [YamlMember(Order = 23)] public float? m_flyTurnSpeed; [YamlMember(Order = 24)] public bool? m_canSwim; [YamlMember(Order = 25)] public float? m_swimDepth; [YamlMember(Order = 26)] public float? m_swimSpeed; [YamlMember(Order = 27)] public float? m_swimTurnSpeed; [YamlMember(Order = 28)] public float? m_swimAcceleration; [YamlMember(Order = 29)] public GroundTiltType? m_groundTilt; [YamlMember(Order = 30)] public float? m_groundTiltSpeed; [YamlMember(Order = 31, Description = "Gravity disabled while sleeping")] public bool? m_disableWhileSleeping; [YamlMember(Order = 32)] public bool? m_useAltStatusEffectScaling; [YamlMember(Order = 33)] public bool? m_tolerateWater; [YamlMember(Order = 34)] public bool? m_tolerateFire; [YamlMember(Order = 35)] public bool? m_tolerateSmoke; [YamlMember(Order = 36)] public bool? m_tolerateTar; [YamlMember(Order = 37, Description = "Effects")] public EffectListRef m_hitEffects; [YamlMember(Order = 38)] public EffectListRef m_critHitEffects; [YamlMember(Order = 39)] public EffectListRef m_backstabHitEffects; [YamlMember(Order = 40)] public EffectListRef m_deathEffects; [YamlMember(Order = 41)] public EffectListRef m_waterEffects; [YamlMember(Order = 42)] public EffectListRef m_tarEffects; [YamlMember(Order = 43)] public EffectListRef m_slideEffects; [YamlMember(Order = 44)] public EffectListRef m_jumpEffects; [YamlMember(Order = 45)] public EffectListRef m_flyingContinuousEffect; [YamlMember(Order = 46)] public EffectListRef m_pheromoneLoveEffect; [YamlMember(Order = 47, Description = "Base Health")] public float? m_health; [YamlMember(Order = 48)] public float? m_regenAllHPTime; [YamlMember(Order = 49)] public DamageModifiers? m_damageModifiers; [YamlMember(Order = 50)] public bool? m_staggerWhenBlocked; [YamlMember(Order = 51)] public float? m_staggerDamageFactor; [YamlMember(Order = 52)] public float? m_enemyAdrenalineMultiplier; [YamlMember(Order = 53, Description = "Lava")] public float? m_minLavaMaskThreshold; [YamlMember(Order = 54)] public float? m_heatBuildupBase; [YamlMember(Order = 55)] public float? m_heatCooldownBase; [YamlMember(Order = 56)] public float? m_heatBuildupWater; [YamlMember(Order = 57)] public float? m_heatWaterTouchMultiplier; [YamlMember(Order = 58)] public float? m_lavaDamageTickInterval; [YamlMember(Order = 59)] public float? m_heatLevelFirstDamageThreshold; [YamlMember(Order = 60)] public float? m_lavaFirstDamage; [YamlMember(Order = 61)] public float? m_lavaFullDamage; [YamlMember(Order = 62)] public float? m_lavaAirDamageHeight; [YamlMember(Order = 63)] public float? m_dayHeatGainRunning; [YamlMember(Order = 64)] public float? m_dayHeatGainStill; [YamlMember(Order = 65)] public float? m_dayHeatEquipmentStop; [YamlMember(Order = 66)] public float? m_lavaSlowMax; [YamlMember(Order = 67)] public float? m_lavaSlowHeight; [YamlMember(Order = 68)] public EffectListRef m_lavaHeatEffects; public CharacterRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public CharacterRef(Character character) { Setup(character); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class HumanoidRef : CharacterRef { [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class ItemSet { public string m_name = ""; public string[] m_items = Array.Empty(); } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] public class RandomItem { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] public string m_prefab = ""; public float m_chance = 0.5f; } [YamlMember(Order = 100)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public string[] m_defaultItems; [YamlMember(Order = 101)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public string[] m_randomWeapon; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [YamlMember(Order = 102)] public string[] m_randomArmor; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [YamlMember(Order = 103)] public string[] m_randomShield; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [YamlMember(Order = 104)] public ItemSet[] m_randomSets; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [YamlMember(Order = 105)] public RandomItem[] m_randomItems; [YamlMember(Order = 106)] public EffectListRef m_consumeItemEffects; [YamlMember(Order = 107)] public EffectListRef m_equipEffects; [YamlMember(Order = 108)] public EffectListRef m_perfectBlockEffect; public HumanoidRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public HumanoidRef(Humanoid humanoid) { Setup(humanoid); } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class AoeRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] public string m_name = ""; [YamlMember(Description = "Attack (overridden by item)")] public bool? m_useAttackSettings = true; public DamageTypes? m_damage; public bool? m_scaleDamageByDistance; public bool? m_dodgeable; public bool? m_blockable; public int? m_toolTier; public float? m_attackForce; public float? m_backstabBonus = 4f; public string m_statusEffect = ""; public string m_statusEffectIfBoss = ""; public bool? m_attackForceForward; public string m_spawnOnHitTerrain = ""; public bool? m_hitTerrainOnlyOnce; public GroundMaterial? m_spawnOnGroundType; public float? m_groundLavaValue = -1f; public float? m_hitNoise; public bool? m_placeOnGround; public bool? m_randomRotation; public int? m_maxTargetsFromCenter; [YamlMember(Description = "Multi Spawn (Lava Bomb)")] public int? m_multiSpawnMin; public int? m_multiSpawnMax; public float? m_multiSpawnDistanceMin; public float? m_multiSpawnDistanceMax; public float? m_multiSpawnScaleMin; public float? m_multiSpawnScaleMax; public float? m_multiSpawnSpringDelayMax; [YamlMember(Description = "Chain Spawn")] public float? m_chainStartChance; public float? m_chainStartChanceFalloff = 0.8f; public float? m_chainChancePerTarget; public string m_chainObj = ""; public float? m_chainStartDelay; public int? m_chainMinTargets; public int? m_chainMaxTargets; public EffectListRef m_chainEffects; public float? m_chainDelay; public float? m_chainChance; public float? m_damageSelf; [YamlMember(Description = "Ignore targets")] public bool? m_hitOwner; public bool? m_hitParent = true; public bool? m_hitSame; public bool? m_hitFriendly = true; public bool? m_hitEnemy = true; public bool? m_hitCharacters = true; public bool? m_hitProps = true; public bool? m_hitTerrain; public bool? m_launchCharacters; public float? m_launchForceUpFactor = 0.5f; public bool? m_useTriggers; public bool? m_triggerEnterOnly; public float? m_radius = 4f; [YamlMember(Description = "Wait this long before we start doing any damage")] public float? m_activationDelay; public float? m_ttl = 4f; [YamlMember(Description = "When set, ttl will be a random value between tll and ttlMax")] public float? m_ttlMax; public bool? m_hitAfterTtl; public float? m_hitInterval = 1f; public bool? m_hitOnEnable; public bool? m_attachToCaster; public EffectListRef m_hitEffects; public EffectListRef m_initiateEffect; public AoeRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public AoeRef(Aoe aoe) { Setup(aoe); } } [Serializable] public class CharacterDropRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_drops; [YamlMember(Description = "Only works if Character Death Effects do not have a ragdoll")] public bool? m_dropsEnabled; public CharacterDropRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public CharacterDropRef(CharacterDrop characterDrop) { Setup(characterDrop); } } [Serializable] public class DropRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_prefab; public int? m_amountMin; public int? m_amountMax; public float? m_chance; public bool? m_onePerPlayer; public bool? m_levelMultiplier; public bool? m_dontScale; public DropRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public DropRef(Drop drop) { m_prefab = ((Object)drop.m_prefab).name; m_chance = drop.m_chance; m_amountMin = drop.m_amountMin; m_amountMax = drop.m_amountMax; m_dontScale = drop.m_dontScale; m_levelMultiplier = drop.m_levelMultiplier; m_onePerPlayer = drop.m_onePerPlayer; } } [Serializable] public class CharacterTimedDestructionRef : Reference { public float? m_timeoutMin; public float? m_timeoutMax; public bool? m_triggerOnAwake; public CharacterTimedDestructionRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public CharacterTimedDestructionRef(CharacterTimedDestruction component) { Setup(component); } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class CinderRef : Reference { [YamlMember(Description = "If prefab != cinderPrefab, this will not update")] public string m_prefab = ""; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_firePrefab; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_houseFirePrefab; public float? m_gravity; public float? m_drag; public float? m_windStrength; public int? m_spread = 4; [YamlMember(Description = "0.0 - 1.0")] public float m_chanceToIgniteGrass; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public EffectListRef m_hitEffects; public CinderRef() { } public CinderRef(Cinder component) { Setup(component); m_prefab = ((Object)component).name; } public void Update(GameObject prefab, bool isInstance) { Cinder target = default(Cinder); if (prefab.TryGetComponent(ref target)) { UpdateFields(target, ((Object)prefab).name, !isInstance); } } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class CinderSpawnerRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_cinderPrefab; public float? m_cinderInterval = 2f; public float? m_cinderChance = 0.1f; public float? m_cinderVel = 5f; public float? m_spawnOffset = 1f; public Vector3Ref? m_spawnOffsetPoint; public int? m_spread = 4; public int? m_instancesPerSpawn = 1; public bool? m_spawnOnAwake; public bool? m_spawnOnProjectileHit; [YamlMember(Description = "Will affect all new cinderPrefab instances, including cinderPrefab from other components")] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public CinderRef m_cinder; public CinderSpawnerRef() { } public CinderSpawnerRef(CinderSpawner component) { Setup(component); Cinder component2 = default(Cinder); if ((Object)(object)component.m_cinderPrefab != (Object)null && component.m_cinderPrefab.TryGetComponent(ref component2)) { m_cinder = new CinderRef(component2); } } public void Update(GameObject prefab, bool isInstance = false) { CinderSpawner val = default(CinderSpawner); if (prefab.TryGetComponent(ref val)) { UpdateFields(val, ((Object)prefab).name, !isInstance); if (m_cinder != null && (Object)(object)val.m_cinderPrefab != (Object)null && ((Object)val.m_cinderPrefab).name == m_cinder.m_prefab) { m_cinder.Update(val.m_cinderPrefab, isInstance); } } } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class DropProjectileOverDistanceRef : Reference { public string m_projectilePrefab; public float? m_distancePerProjectile = 5f; public float? m_spawnHeight = 1f; public bool? m_snapToGround; [YamlMember(Description = "If higher than 0, will force a spawn if nothing has spawned in that amount of time.")] public float? m_timeToForceSpawn = -1f; public float? m_minVelocity; public float? m_maxVelocity; public ProjectileRef m_projectile; public AoeRef m_projectileAoe; public DropProjectileOverDistanceRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public DropProjectileOverDistanceRef(DropProjectileOverDistance component) { Setup(component); if ((Object)(object)component.m_projectilePrefab != (Object)null) { Projectile projectile = default(Projectile); if (component.m_projectilePrefab.TryGetComponent(ref projectile)) { m_projectile = new ProjectileRef(projectile); } Aoe aoe = default(Aoe); if (component.m_projectilePrefab.TryGetComponent(ref aoe)) { m_projectileAoe = new AoeRef(aoe); } } } } [Serializable] public class FootStepRef : Reference { public bool? m_footlessFootsteps; public float? m_footlessTriggerDistance; public float? m_footstepCullDistance; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_effects; public FootStepRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public FootStepRef(FootStep comp) { Setup(comp); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class StepEffectRef : Reference { public string m_name = ""; public MotionType m_motionType = (MotionType)32; public GroundMaterial m_material = (GroundMaterial)1; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public string[] m_effectPrefabs; public StepEffectRef() { }//IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) public StepEffectRef(StepEffect effect) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) m_name = effect.m_name; m_motionType = effect.m_motionType; m_material = effect.m_material; m_effectPrefabs = effect.m_effectPrefabs.ToGameObjectNameArray(); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class GrowUpRef : Reference { [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class GrownEntry : Reference { public string m_prefab = ""; public float m_weight; public GrownEntry() { } public GrownEntry(GrownEntry entry) { m_prefab = ((Object)entry.m_prefab).name; m_weight = entry.m_weight; } public GrownEntry ToGrowUpGrowEntry() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown return new GrownEntry { m_prefab = PrefabManager.GetPrefab(m_prefab), m_weight = m_weight }; } } public float? m_growTime; public bool? m_inheritTame; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_grownPrefab; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_altGrownPrefabs; public GrowUpRef() { } public GrowUpRef(Growup growUp) { Setup(growUp); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class MovementDamageRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_runDamageObject; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public AoeRef m_areaOfEffect; public MovementDamageRef() { } public MovementDamageRef(MovementDamage md) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)md.m_runDamageObject == (Object)null)) { m_runDamageObject = ((Object)md.m_runDamageObject).name; Aoe val = default(Aoe); if (md.m_runDamageObject.TryGetComponent(ref val)) { m_areaOfEffect = new AoeRef { m_damage = val.m_damage }; } } } protected override void UpdateGameObject<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, string targetName, string goName, bool log) { object obj = target; MovementDamage val = (MovementDamage)((obj is MovementDamage) ? obj : null); if (val == null) { return; } if (string.IsNullOrEmpty(goName)) { targetField.SetValue(target, null); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": null"); } return; } Transform val2 = Utils.FindChild(((Component)val).transform, goName, (IterativeSearchType)0); if ((Object)(object)val2 != (Object)null) { targetField.SetValue(target, ((Component)val2).gameObject); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + ((Object)val2).name); } } } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class NPCTalkRef : Reference { public string m_name; public float? m_maxRange; public float? m_greetRange; public float? m_byeRange; public float? m_offset; public float? m_minTalkInterval; public float? m_hideDialogDelay; public float? m_randomTalkInterval; public float? m_randomTalkChance; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_randomTalk; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_randomTalkInFactionBase; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_randomGreets; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_randomGoodbye; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_privateAreaAlarm; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_aggravated; public EffectListRef m_randomTalkFX; public EffectListRef m_randomGreetFX; public EffectListRef m_randomGoodbyeFX; public NPCTalkRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public NPCTalkRef(NpcTalk component) { Setup(component); } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class ProcreationRef : Reference { public float? m_updateInterval; public float? m_totalCheckRange; public int? m_maxCreatures; public float? m_partnerCheckRange; public float? m_pregnancyChance; public float? m_pregnancyDuration; public int? m_requiredLovePoints; public string m_offspring; public int? m_minOffspringLevel; public float? m_spawnOffset; public float? m_spawnOffsetMax; public bool? m_spawnRandomDirection; public string m_seperatePartner; public string m_noPartnerOffspring; public EffectListRef m_birthEffects; public EffectListRef m_loveEffects; public ProcreationRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public ProcreationRef(Procreation component) { Setup(component); } } [Serializable] public class RandomAnimationRef : Reference { [Serializable] public class RandomValueRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] public string m_name = ""; public int m_values; public float m_interval; public bool m_floatValue; public float m_floatTransition = 1f; } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_values; } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class SaddleRef : Reference { public string m_hoverText; public float? m_maxUseRange; public Vector3Ref? m_detachOffset; public string m_attachAnimation; public float? m_maxStamina; public float? m_runStaminaDrain; public float? m_swimStaminaDrain; public float? m_staminaRegen; public float? m_staminaRegenHungry; public EffectListRef m_drownEffects; public string m_mountIcon; [YamlMember(Description = "If added saddle by MonsterDB, use this to position attach point")] public Vector3Ref? m_attachOffset; public string m_attachParent; public SaddleRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public SaddleRef(Sadle component) { Setup(component); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] protected override void UpdateGameObject<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, string targetName, string goName, bool log) { if (!((object)target is Saddle saddle)) { return; } if (string.IsNullOrEmpty(goName)) { targetField.SetValue(target, null); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": null"); } return; } Transform val = Utils.FindChild(((Component)saddle).transform, goName, (IterativeSearchType)0); if ((Object)(object)val != (Object)null) { targetField.SetValue(target, ((Component)val).gameObject); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + ((Object)val).name); } } } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class TameableRef : Reference { public float? m_fedDuration; public float? m_tamingTime; public bool? m_startsTamed; public EffectListRef m_tamedEffect; public EffectListRef m_sootheEffect; public EffectListRef m_petEffect; public bool? m_commandable; public float? m_unsummonDistance; public float? m_unsummonOnOwnerLogoutSeconds; public EffectListRef m_unSummonEffect; public SkillType? m_levelUpOwnerSkill; public float? m_levelUpFactor; public string m_saddleItem; public bool? m_dropSaddleOnDeath; public Vector3Ref? m_dropSaddleOffset; public float? m_dropItemVel; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_randomStartingName; public float? m_tamingSpeedMultiplierRange; public float? m_tamingBoostMultiplier; public bool? m_nameBeforeText; public string m_tameText; public TameableRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public TameableRef(Tameable component) { Setup(component); } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class VisEquipmentRef : Reference { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] [HarmonyPatch(typeof(VisEquipment), "AttachItem")] private static class VisEquipment_AttachItem_Patch { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] private static void Postfix(VisEquipment __instance, Transform joint, GameObject __result) { //IL_008f: 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) if (!((Object)(object)__result == (Object)null) && LoadManager.modified.TryGetValue(Utils.GetPrefabName(((Object)__instance).name), out var value) && value is BaseHumanoid baseHumanoid && baseHumanoid.VisEquipment != null) { TransformRef transformRef = baseHumanoid.VisEquipment.Get(joint); if (transformRef != null && transformRef.m_scale.HasValue) { __result.transform.localScale = Vector3.Scale(__result.transform.localScale, (Vector3)transformRef.m_scale.Value); } } } } public TransformRef m_leftHand; public TransformRef m_rightHand; public TransformRef m_helmet; public TransformRef m_backShield; public TransformRef m_backMelee; public TransformRef m_backTwohandedMelee; public TransformRef m_backBow; public TransformRef m_backTool; public TransformRef m_backAtgeir; public VisEquipmentRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public VisEquipmentRef(VisEquipment comp) { m_leftHand = (Object.op_Implicit((Object)(object)comp.m_leftHand) ? new TransformRef(comp.m_leftHand) : null); m_rightHand = (Object.op_Implicit((Object)(object)comp.m_rightHand) ? new TransformRef(comp.m_rightHand) : null); m_helmet = (Object.op_Implicit((Object)(object)comp.m_helmet) ? new TransformRef(comp.m_helmet) : null); m_backShield = (Object.op_Implicit((Object)(object)comp.m_backShield) ? new TransformRef(comp.m_backShield) : null); m_backMelee = (Object.op_Implicit((Object)(object)comp.m_backMelee) ? new TransformRef(comp.m_backMelee) : null); m_backTwohandedMelee = (Object.op_Implicit((Object)(object)comp.m_backTwohandedMelee) ? new TransformRef(comp.m_backTwohandedMelee) : null); m_backBow = (Object.op_Implicit((Object)(object)comp.m_backBow) ? new TransformRef(comp.m_backBow) : null); m_backTool = (Object.op_Implicit((Object)(object)comp.m_backTool) ? new TransformRef(comp.m_backTool) : null); m_backAtgeir = (Object.op_Implicit((Object)(object)comp.m_backAtgeir) ? new TransformRef(comp.m_backAtgeir) : null); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public TransformRef Get(Transform joint) { if (m_leftHand != null && m_leftHand.m_name == ((Object)joint).name) { return m_leftHand; } if (m_rightHand != null && m_rightHand.m_name == ((Object)joint).name) { return m_rightHand; } if (m_helmet != null && m_helmet.m_name == ((Object)joint).name) { return m_helmet; } if (m_backShield != null && m_backShield.m_name == ((Object)joint).name) { return m_backShield; } if (m_backMelee != null && m_backMelee.m_name == ((Object)joint).name) { return m_backMelee; } if (m_backTwohandedMelee != null && m_backTwohandedMelee.m_name == ((Object)joint).name) { return m_backTwohandedMelee; } if (m_backBow != null && m_backBow.m_name == ((Object)joint).name) { return m_backBow; } if (m_backTool != null && m_backTool.m_name == ((Object)joint).name) { return m_backTool; } if (m_backAtgeir != null && m_backAtgeir.m_name == ((Object)joint).name) { return m_backAtgeir; } return null; } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public override void UpdateFields<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, string targetName, bool log) { object obj = target; VisEquipment val = (VisEquipment)((obj is VisEquipment) ? obj : null); if (val == null) { return; } if (m_leftHand != null) { Transform val2 = m_leftHand.Find(((Component)val).gameObject, val.m_leftHand); if ((Object)(object)val2 != (Object)null) { val.m_leftHand = val2; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_leftHand: " + ((Object)val2).name); } m_leftHand.UpdateFields(val2, targetName, log); } else { val.m_leftHand = null; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_leftHand: null"); } } } if (m_rightHand != null) { Transform val3 = m_rightHand.Find(((Component)val).gameObject, val.m_rightHand); if ((Object)(object)val3 != (Object)null) { val.m_rightHand = val3; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_rightHand: " + ((Object)val3).name); } m_rightHand.UpdateFields(val3, targetName, log); } else { val.m_rightHand = null; } } if (m_helmet != null) { Transform val4 = m_helmet.Find(((Component)val).gameObject, val.m_helmet); if ((Object)(object)val4 != (Object)null) { val.m_helmet = val4; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_helmet: " + ((Object)val4).name); } m_helmet.UpdateFields(val4, targetName, log); } else { val.m_helmet = null; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_helmet: null"); } } } if (m_backShield != null) { Transform val5 = m_backShield.Find(((Component)val).gameObject, val.m_backShield); if ((Object)(object)val5 != (Object)null) { val.m_backShield = val5; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_backShield: " + ((Object)val5).name); } m_backShield.UpdateFields(val5, targetName, log); } else { val.m_backShield = null; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_backShield: null"); } } } if (m_backMelee != null) { Transform val6 = m_backMelee.Find(((Component)val).gameObject, val.m_backMelee); if ((Object)(object)val6 != (Object)null) { val.m_backMelee = val6; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_backMelee: " + ((Object)val6).name); } m_backMelee.UpdateFields(val6, targetName, log); } else { val.m_backMelee = null; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_backMelee: null"); } } } if (m_backTwohandedMelee != null) { Transform val7 = m_backTwohandedMelee.Find(((Component)val).gameObject, val.m_backTwohandedMelee); if ((Object)(object)val7 != (Object)null) { val.m_backTwohandedMelee = val7; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_backTwohandedMelee: " + ((Object)val7).name); } m_backTwohandedMelee.UpdateFields(val7, targetName, log); } else { val.m_backTwohandedMelee = null; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_backTwohandedMelee: null"); } } } if (m_backBow != null) { Transform val8 = m_backBow.Find(((Component)val).gameObject, val.m_backBow); if ((Object)(object)val8 != (Object)null) { val.m_backBow = val8; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_backBow: " + ((Object)val8).name); } m_backBow.UpdateFields(val8, targetName, log); } else { val.m_backBow = null; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_backBow: null"); } } } if (m_backTool != null) { Transform val9 = m_backTool.Find(((Component)val).gameObject, val.m_backTool); if ((Object)(object)val9 != (Object)null) { val.m_backTool = val9; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_backTool: " + ((Object)val9).name); } m_backTool.UpdateFields(val9, targetName, log); } else { val.m_backTool = null; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_backTool: null"); } } } if (m_backAtgeir == null) { return; } Transform val10 = m_backAtgeir.Find(((Component)val).gameObject, val.m_backAtgeir); if ((Object)(object)val10 != (Object)null) { val.m_backAtgeir = val10; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] m_backAtgeir: " + ((Object)val10).name); } m_backAtgeir.UpdateFields(val10, targetName, log); } else { val.m_backAtgeir = null; if (log) { MonsterDBPlugin.LogDebug(targetName + "] m_backAtgeir: null"); } } } public override bool IsNull() { return m_leftHand == null && m_rightHand == null && m_helmet == null && m_backShield == null && m_backMelee == null && m_backTwohandedMelee == null && m_backBow == null && m_backTool == null && m_backAtgeir == null; } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class TransformRef : Reference { [Persistent] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_name; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [Persistent] public string m_parent; [Persistent] public int? m_index; public Vector3Ref? m_position; public Vector3Ref? m_rotation; public Vector3Ref? m_scale; public TransformRef() { } public TransformRef(Transform transform) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) m_name = ((Object)transform).name; m_parent = ((Object)transform.parent).name; m_index = transform.GetSiblingIndex(); m_position = new Vector3Ref(transform.localPosition); Quaternion localRotation = transform.localRotation; m_rotation = new Vector3Ref(((Quaternion)(ref localRotation)).eulerAngles); m_scale = new Vector3Ref(transform.localScale); } public Transform Find(GameObject prefab, Transform defaultValue) { if (m_name == null) { return defaultValue; } if (m_parent == null || !m_index.HasValue) { if (((Object)defaultValue).name == m_name) { return defaultValue; } return Utils.FindChild(prefab.transform, m_name, (IterativeSearchType)0) ?? defaultValue; } if (((Object)defaultValue).name == m_name) { Transform parent = defaultValue.parent; if (((parent != null) ? ((Object)parent).name : null) == m_parent && defaultValue.GetSiblingIndex() == m_index) { return defaultValue; } } Transform[] componentsInChildren = prefab.GetComponentsInChildren(true); foreach (Transform val in componentsInChildren) { if (((Object)val).name == m_name) { Transform parent2 = val.parent; if (((parent2 != null) ? ((Object)parent2).name : null) == m_parent && val.GetSiblingIndex() == m_index) { return val; } } } return Utils.FindChild(prefab.transform, m_name, (IterativeSearchType)0) ?? defaultValue; } public override void UpdateFields<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, string targetName, bool log) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) object obj = target; Transform val = (Transform)((obj is Transform) ? obj : null); if (val == null) { return; } if (m_position.HasValue) { val.localPosition = m_position.Value; if (log) { MonsterDBPlugin.LogDebug($"[{targetName}][{((Object)val).name}] m_localPosition: {m_position.Value}"); } } if (m_rotation.HasValue) { val.localRotation = Quaternion.Euler((Vector3)m_rotation.Value); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}][{((Object)val).name}] m_localRotation: {m_rotation.Value}"); } } if (m_scale.HasValue) { val.localScale = m_scale.Value; if (log) { MonsterDBPlugin.LogDebug($"[{targetName}][{((Object)val).name}] m_localScale: {m_scale.Value}"); } } } public override bool Equals<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>(T other) { if (!(other is TransformRef transformRef)) { return false; } bool flag = transformRef.m_name == m_name && transformRef.m_parent == m_parent && transformRef.m_index == m_index; if (flag) { if (m_position.HasValue && transformRef.m_position.HasValue) { flag &= m_position.Equals(transformRef.m_position); } if (m_rotation.HasValue && transformRef.m_rotation.HasValue) { flag &= m_rotation.Equals(transformRef.m_rotation); } if (m_scale.HasValue && transformRef.m_scale.HasValue) { flag &= m_scale.Equals(transformRef.m_scale); } } return flag; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class CreatureManager { [Obsolete] public static void WriteCreatureYML(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); } else { Write(prefab, isClone: false, "", args.Context); } } [Obsolete] public static List GetCreatureOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : PrefabManager.GetAllPrefabNames()); if (1 == 0) { } return result; } [Obsolete] public static void WriteAllCreatureYML(ConsoleEventArgs args) { List allPrefabs = PrefabManager.GetAllPrefabs(); for (int i = 0; i < allPrefabs.Count; i++) { GameObject prefab = allPrefabs[i]; Write(prefab, isClone: false, "", args.Context); } args.Context.AddString($"Exported {allPrefabs.Count} creature YML files"); } [Obsolete] public static void ReadCreatureYML(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); return; } string filePath = Path.Combine(FileManager.ImportFolder, @string + ".yml"); FileManager.Read(filePath); args.Context.AddString("Updated " + @string); } [Obsolete] public static void ResetCreature(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid prefab"); return; } Base original = LoadManager.GetOriginal(@string); if (original == null) { args.Context.LogWarning("Original data not found"); return; } original.Update(); LoadManager.UpdateSync(); args.Context.AddString("Reverted " + @string); } [Obsolete] public static void CloneCreature(ConsoleEventArgs args) { string @string = args.GetString(2); string string2 = args.GetString(3); if (string.IsNullOrEmpty(@string) || string.IsNullOrEmpty(string2)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if (!((Object)(object)prefab == (Object)null)) { if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { args.Context.LogWarning("Invalid prefab, missing character component"); } else { Clone(prefab, string2); } } } [Obsolete] public static void WriteHierarchy(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab " + @string); return; } string text = Path.Combine(FileManager.ExportFolder, @string); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } string filePath = Path.Combine(text, @string + ".bones.yml"); ExportHierarchy(prefab, filePath); } public static void WriteHierarchy(Terminal context, string input) { if (string.IsNullOrEmpty(input)) { context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(input); if ((Object)(object)prefab == (Object)null) { context.LogWarning("Failed to find prefab " + input); return; } string text = Path.Combine(FileManager.ExportFolder, input); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } string text2 = Path.Combine(text, input + ".bones.yml"); ExportHierarchy(prefab, text2); context.LogInfo("Exported " + ((Object)prefab).name + " bones"); context.LogInfo(text2.RemoveRootPath()); } public static bool TrySave(GameObject prefab, out Base data, bool isClone = false, string source = "") { data = LoadManager.GetOriginal(((Object)prefab).name); if (data != null) { return true; } Character component = prefab.GetComponent(); BaseAI component2 = prefab.GetComponent(); if ((Object)(object)component == (Object)null || (Object)(object)component2 == (Object)null) { MonsterDBPlugin.LogWarning("Invalid prefab, missing Character or AI component"); return false; } if (component is Human && component2 is MonsterAI) { BaseHuman baseHuman = new BaseHuman(); baseHuman.Setup(prefab, isClone, source); data = baseHuman; } else if (component is Humanoid && component2 is MonsterAI) { BaseHumanoid baseHumanoid = new BaseHumanoid(); baseHumanoid.Setup(prefab, isClone, source); data = baseHumanoid; } else if (component2 is AnimalAI) { BaseCharacter baseCharacter = new BaseCharacter(); baseCharacter.Setup(prefab, isClone, source); data = baseCharacter; } if (data == null) { return false; } LoadManager.originals.Add(((Object)prefab).name, data); return true; } public static bool Write(GameObject prefab, bool isClone = false, string source = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { string text = Path.Combine(FileManager.ExportFolder, ((Object)prefab).name); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } string text2 = Path.Combine(text, ((Object)prefab).name + ".yml"); if (!TrySave(prefab, out var data, isClone, source)) { return false; } string contents = ConfigManager.Serialize(data); File.WriteAllText(text2, contents); MonsterDBPlugin.LogInfo("Saved " + ((Object)prefab).name + " to: " + text2); context?.LogInfo("Exported Creature " + ((Object)prefab).name); context?.LogInfo(text2.RemoveRootPath()); Character component = prefab.GetComponent(); if ((Object)(object)component != (Object)null) { if (component.m_deathEffects != null && component.m_deathEffects.m_effectPrefabs != null) { for (int i = 0; i < component.m_deathEffects.m_effectPrefabs.Length; i++) { EffectData val = component.m_deathEffects.m_effectPrefabs[i]; if ((Object)(object)val.m_prefab != (Object)null && Object.op_Implicit((Object)(object)val.m_prefab.GetComponent())) { string sourceName; bool isClone2 = CloneManager.IsClone(((Object)val.m_prefab).name, out sourceName); RagdollManager.Write(val.m_prefab, isClone2, sourceName, text); } } } Humanoid val2 = (Humanoid)(object)((component is Humanoid) ? component : null); if (val2 != null && !(val2 is Human)) { HashSet items = val2.GetItems(); if (items.Count > 0) { string text3 = Path.Combine(text, "items"); if (!Directory.Exists(text3)) { Directory.CreateDirectory(text3); } foreach (GameObject item in items) { string sourceName2; bool isClone3 = CloneManager.IsClone(((Object)item).name, out sourceName2); ItemManager.Write(item, isClone3, sourceName2, text3, context); } } } } return true; } private static void CloneRagdoll(Character character, string cloneName) { EffectData[] effectPrefabs = character.m_deathEffects.m_effectPrefabs; foreach (EffectData val in effectPrefabs) { if ((Object)(object)val.m_prefab != (Object)null && Object.op_Implicit((Object)(object)val.m_prefab.GetComponent())) { string cloneName2 = cloneName + "_ragdoll"; if (RagdollManager.TryClone(val.m_prefab, cloneName2, out var clone, write: false)) { val.m_prefab = clone; } break; } } } [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] private static GameObject ClonePlayer(GameObject source, Player player, string cloneName, bool write = true, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (CloneManager.prefabs.TryGetValue(cloneName, out var value)) { return value; } Clone clone = new Clone(source, cloneName); clone.OnCreated += delegate(GameObject prefab) { prefab.Remove(); prefab.Remove(); prefab.Remove(); prefab.Remove(); Human human = prefab.AddComponent(); human.CopyFrom(player); MonsterAI target = prefab.AddComponent(); MonsterAI component = PrefabManager.GetPrefab("Dverger").GetComponent(); target.CopyFrom(component); prefab.AddComponent(); prefab.GetComponent().m_persistent = true; ((Character)human).m_eye = Utils.FindChild(prefab.transform, "EyePos", (IterativeSearchType)0); if (write && ((Character)human).m_deathEffects != null) { CloneRagdoll((Character)(object)human, cloneName); } MonsterDBPlugin.LogDebug("Cloned " + ((Object)source).name + " as " + cloneName); if (write) { Write(prefab, isClone: true, ((Object)source).name, context); } }; return clone.Create(); } private static void CloneItems(Humanoid humanoid, string cloneName) { //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Expected O, but got Unknown //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Expected O, but got Unknown if (humanoid.m_defaultItems != null) { humanoid.m_defaultItems = CreateItems(humanoid.m_defaultItems, cloneName); } if (humanoid.m_randomWeapon != null) { humanoid.m_randomWeapon = CreateItems(humanoid.m_randomWeapon, cloneName); } if (humanoid.m_randomArmor != null) { humanoid.m_randomArmor = CreateItems(humanoid.m_randomArmor, cloneName); } if (humanoid.m_randomShield != null) { humanoid.m_randomShield = CreateItems(humanoid.m_randomShield, cloneName); } if (humanoid.m_randomItems != null) { List list = new List(); for (int i = 0; i < humanoid.m_randomItems.Length; i++) { RandomItem val = humanoid.m_randomItems[i]; string cloneName2 = "MDB_" + cloneName + "_" + ((Object)val.m_prefab).name; if (ItemManager.TryClone(val.m_prefab, cloneName2, out var clone, write: false)) { RandomItem item = new RandomItem { m_chance = val.m_chance, m_prefab = clone }; list.Add(item); } } humanoid.m_randomItems = list.ToArray(); } if (humanoid.m_randomSets != null) { List list2 = new List(); for (int j = 0; j < humanoid.m_randomSets.Length; j++) { ItemSet val2 = humanoid.m_randomSets[j]; ItemSet item2 = new ItemSet { m_name = val2.m_name, m_items = CreateItems(val2.m_items, cloneName) }; list2.Add(item2); } humanoid.m_randomSets = list2.ToArray(); } } [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public static GameObject Clone(GameObject source, string cloneName, bool write = true, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (CloneManager.prefabs.TryGetValue(cloneName, out var value)) { return value; } Player player = default(Player); if (source.TryGetComponent(ref player)) { return ClonePlayer(source, player, cloneName, write); } Clone clone = new Clone(source, cloneName); clone.OnCreated += delegate(GameObject prefab) { Character component = prefab.GetComponent(); if (write) { Humanoid val = (Humanoid)(object)((component is Humanoid) ? component : null); if (val != null) { CloneItems(val, cloneName); } } if (write && component.m_deathEffects != null) { CloneRagdoll(component, cloneName); } MonsterDBPlugin.LogDebug("Cloned " + ((Object)source).name + " as " + cloneName); if (write) { Write(prefab, isClone: true, ((Object)source).name, context); } }; return clone.Create(); } private static GameObject[] CreateItems(GameObject[] list, string cloneName) { List list2 = new List(); foreach (GameObject val in list) { if (!((Object)(object)val == (Object)null)) { string cloneName2 = "MDB_" + cloneName + "_" + ((Object)val).name; if (ItemManager.TryClone(val, cloneName2, out var clone, write: false)) { list2.Add(clone); } } } return list2.ToArray(); } private static void ExportHierarchy(GameObject root, string filePath) { if (!((Object)(object)root == (Object)null)) { if (string.IsNullOrEmpty(filePath)) { filePath = Path.Combine(FileManager.ExportFolder, ((Object)root).name + ".bones.yml"); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(((Object)root).name); for (int i = 0; i < root.transform.childCount; i++) { WriteTransform(stringBuilder, root.transform.GetChild(i), 1); } File.WriteAllText(filePath, stringBuilder.ToString()); MonsterDBPlugin.LogInfo("Saved " + ((Object)root).name + " hierarchy to " + filePath); } } private static void WriteTransform(StringBuilder builder, Transform t, int depth) { builder.Append(new string(' ', depth * 2)); builder.Append("- "); builder.AppendLine(((Object)t).name); for (int i = 0; i < t.childCount; i++) { WriteTransform(builder, t.GetChild(i), depth + 1); } } } [Serializable] [UsedImplicitly] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class Base : Header { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 8)] public VisualRef Visuals; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 9, Description = "If field removed, will remove component")] public CharacterDropRef Drops; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 10, Description = "If field removed, will remove component")] public TameableRef Tameable; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 11, Description = "If field removed, will remove component")] public ProcreationRef Procreation; [YamlMember(Order = 12, Description = "If field removed, will remove component")] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public GrowUpRef GrowUp; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 13, Description = "If field removed, will remove component")] public NPCTalkRef NPCTalk; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 14)] public MovementDamageRef MovementDamage; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 15)] public SaddleRef Saddle; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 16, Description = "If field removed, will remove component")] public DropProjectileOverDistanceRef DropProjectileOverDistance; [YamlMember(Order = 17)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public CinderSpawnerRef CinderSpawner; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 18)] public CharacterTimedDestructionRef TimedDestruction; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [YamlMember(Order = 19, Description = "If entries removed, will still be registered, set enabled too false to disable")] public SpawnDataRef[] SpawnData; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 20)] public FootStepRef FootStep; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [YamlMember(Order = 101, Description = "Reference only, these are attack animation triggers")] public List AnimationTriggers; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public override VisualRef GetVisualData() { return Visuals; } public override void Setup(GameObject prefab, bool isClone = false, string source = "") { base.Setup(prefab, isClone, source); SetupSharedFields(prefab, isClone, source); if (isClone) { SetupSpawnData(); } } public override void CopyFields(Header original) { base.CopyFields(original); if (original is Base @base) { if (Visuals != null && @base.Visuals != null) { Visuals.ResetTo(@base.Visuals); } if (@base.Drops == null) { Drops = null; } if (@base.Tameable == null) { Tameable = null; } if (@base.Procreation == null) { Procreation = null; } if (@base.GrowUp == null) { GrowUp = null; } if (@base.NPCTalk == null) { NPCTalk = null; } if (@base.Saddle == null) { Saddle = null; } if (Drops != null && @base.Drops != null) { Drops.ResetTo(@base.Drops); } if (Tameable != null && @base.Tameable != null) { Tameable.ResetTo(@base.Tameable); } if (Procreation != null && @base.Procreation != null) { Procreation.ResetTo(@base.Procreation); } if (GrowUp != null && @base.GrowUp != null) { GrowUp.ResetTo(@base.GrowUp); } if (NPCTalk != null && @base.NPCTalk != null) { NPCTalk.ResetTo(@base.NPCTalk); } if (MovementDamage != null && @base.MovementDamage != null) { MovementDamage.ResetTo(@base.MovementDamage); } if (Saddle != null && @base.Saddle != null) { Saddle.ResetTo(@base.Saddle); } if (DropProjectileOverDistance != null && @base.DropProjectileOverDistance != null) { DropProjectileOverDistance.ResetTo(@base.DropProjectileOverDistance); } if (CinderSpawner != null && @base.CinderSpawner != null) { CinderSpawner.ResetTo(@base.CinderSpawner); } if (TimedDestruction != null && @base.TimedDestruction != null) { TimedDestruction.ResetTo(@base.TimedDestruction); } if (FootStep != null && @base.FootStep != null) { FootStep.ResetTo(@base.FootStep); } } } protected void SetupAnimationTriggers(GameObject prefab) { if (Object.op_Implicit((Object)(object)prefab.GetComponentInChildren())) { ZNetView.m_forceDisableInit = true; GameObject val = Object.Instantiate(prefab); ZNetView.m_forceDisableInit = false; Animator componentInChildren = val.GetComponentInChildren(); AnimationTriggers = componentInChildren.parameters.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (AnimatorControllerParameter x) => x.name).ToList(); Object.DestroyImmediate((Object)(object)val); } } protected void SetupSharedFields(GameObject prefab, bool isClone = false, string source = "") { Prefab = ((Object)prefab).name; CharacterDrop characterDrop = default(CharacterDrop); if (prefab.TryGetComponent(ref characterDrop)) { Drops = new CharacterDropRef(characterDrop); } Growup growUp = default(Growup); if (prefab.TryGetComponent(ref growUp)) { GrowUp = new GrowUpRef(growUp); } Tameable component = default(Tameable); if (prefab.TryGetComponent(ref component)) { Tameable = new TameableRef(component); } Procreation component2 = default(Procreation); if (prefab.TryGetComponent(ref component2)) { Procreation = new ProcreationRef(component2); } NpcTalk component3 = default(NpcTalk); if (prefab.TryGetComponent(ref component3)) { NPCTalk = new NPCTalkRef(component3); } MovementDamage md = default(MovementDamage); if (prefab.TryGetComponent(ref md)) { MovementDamage = new MovementDamageRef(md); } Sadle componentInChildren = prefab.GetComponentInChildren(true); if ((Object)(object)componentInChildren != (Object)null) { Saddle = new SaddleRef(componentInChildren); } DropProjectileOverDistance component4 = default(DropProjectileOverDistance); if (prefab.TryGetComponent(ref component4)) { DropProjectileOverDistance = new DropProjectileOverDistanceRef(component4); } Visuals = new VisualRef(prefab); CinderSpawner component5 = default(CinderSpawner); if (prefab.TryGetComponent(ref component5)) { CinderSpawner = new CinderSpawnerRef(component5); } CharacterTimedDestruction component6 = default(CharacterTimedDestruction); if (prefab.TryGetComponent(ref component6)) { TimedDestruction = new CharacterTimedDestructionRef(component6); } SetupAnimationTriggers(prefab); FootStep comp = default(FootStep); if (prefab.TryGetComponent(ref comp)) { FootStep = new FootStepRef(comp); } if (isClone) { IsCloned = true; ClonedFrom = source; } } protected void SetupSpawnData() { SpawnDataRef spawnDataRef = new SpawnDataRef { m_name = "MDB " + Prefab + " Spawn Data", m_prefab = Prefab }; SpawnData = new SpawnDataRef[1] { spawnDataRef }; } public override void Update() { GameObject prefab = PrefabManager.GetPrefab(Prefab); if ((Object)(object)prefab == (Object)null) { return; } if (CreatureManager.TrySave(prefab, out var data, IsCloned, ClonedFrom)) { LoadManager.originalToModifiedList.Add(data, this); } UpdatePrefab(prefab); List allCharacters = Character.GetAllCharacters(); for (int i = 0; i < allCharacters.Count; i++) { Character val = allCharacters[i]; if (!((Object)(object)val == (Object)null) && !((Object)(object)((Component)val).gameObject == (Object)null)) { string prefabName = Utils.GetPrefabName(((Object)val).name); if (!(Prefab != prefabName)) { UpdatePrefab(((Component)val).gameObject, isInstance: true); } } } if (SpawnData != null) { for (int j = 0; j < SpawnData.Length; j++) { SpawnDataRef info = SpawnData[j]; SpawnManager.Update(info); } } base.Update(); } protected virtual void UpdatePrefab(GameObject prefab, bool isInstance = false) { UpdateLevelEffects(prefab, isInstance); UpdateVisual(prefab, isInstance); UpdateCharacterDrop(prefab, isInstance); UpdateGrowUp(prefab, isInstance); UpdateTameable(prefab, isInstance); UpdateProcreation(prefab, isInstance); UpdateNpcTalk(prefab, isInstance); UpdateMovementDamage(prefab, isInstance); UpdateSaddle(prefab, isInstance); UpdateDropProjectile(prefab, isInstance); UpdateCinderSpawner(prefab, isInstance); UpdateTimedDestruction(prefab, isInstance); UpdateFootStep(prefab, isInstance); } public void UpdateFootStep(GameObject prefab, bool isInstance) { FootStep target = default(FootStep); if (FootStep != null && prefab.TryGetComponent(ref target)) { FootStep.UpdateFields(target, ((Object)prefab).name, !isInstance); } } protected virtual void UpdateVisual(GameObject prefab, bool isInstance = false) { Visuals?.Update(prefab, isInstance, isItem: false); } protected void UpdateTimedDestruction(GameObject prefab, bool isInstance = false) { CharacterTimedDestruction target = default(CharacterTimedDestruction); if (TimedDestruction != null && prefab.TryGetComponent(ref target)) { TimedDestruction.UpdateFields(target, ((Object)prefab).name, !isInstance); } } protected void UpdateCinderSpawner(GameObject prefab, bool isInstance = false) { CinderSpawner?.Update(prefab, isInstance); } protected void UpdateLevelEffects(GameObject prefab, bool isInstance = false) { //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Expected O, but got Unknown LevelEffects componentInChildren = prefab.GetComponentInChildren(); if ((Object)(object)componentInChildren == (Object)null || !((Object)(object)componentInChildren != (Object)null)) { return; } VisualRef visuals = Visuals; if (visuals == null || visuals.m_levelSetups == null) { return; } Dictionary renderers = prefab.GetComponentsInChildren(true).ToSafeDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (Renderer f) => ((Object)f).name); List list = new List(); foreach (LevelSetupRef levelSetup in Visuals.m_levelSetups) { LevelSetup val = new LevelSetup(); levelSetup.Set(val, renderers); list.Add(val); } componentInChildren.m_levelSetups = list; } protected void UpdateCharacterDrop(GameObject prefab, bool isInstance = false) { CharacterDrop val = prefab.GetComponent(); if (!isInstance) { if ((Object)(object)val == (Object)null && Drops != null) { val = prefab.AddComponent(); } else if ((Object)(object)val != (Object)null && Drops == null) { prefab.Remove(); val = null; } } if ((Object)(object)val != (Object)null && Drops != null) { Drops.UpdateFields(val, ((Object)prefab).name, !isInstance); } } protected void UpdateGrowUp(GameObject prefab, bool isInstance = false) { Growup val = prefab.GetComponent(); if (!isInstance) { if ((Object)(object)val == (Object)null && GrowUp != null && !string.IsNullOrEmpty(GrowUp.m_grownPrefab)) { val = prefab.AddComponent(); } else if ((Object)(object)val != (Object)null && (GrowUp == null || string.IsNullOrEmpty(GrowUp.m_grownPrefab))) { prefab.Remove(); val = null; } } if ((Object)(object)val != (Object)null && GrowUp != null) { GrowUp.UpdateFields(val, ((Object)prefab).name, !isInstance); } } protected void UpdateTameable(GameObject prefab, bool isInstance = false) { Tameable val = prefab.GetComponent(); if (!isInstance) { if ((Object)(object)val == (Object)null && Tameable != null) { val = prefab.AddComponent(); } else if ((Object)(object)val != (Object)null && Tameable == null) { prefab.Remove(); val = null; } } if ((Object)(object)val != (Object)null && Tameable != null) { Tameable.UpdateFields(val, ((Object)prefab).name, !isInstance); } } protected void UpdateProcreation(GameObject prefab, bool isInstance = false) { Procreation val = prefab.GetComponent(); if (!isInstance) { if ((Object)(object)val == (Object)null && Procreation != null && !string.IsNullOrEmpty(Procreation.m_offspring)) { val = prefab.AddComponent(); } else if ((Object)(object)val != (Object)null && (Procreation == null || string.IsNullOrEmpty(Procreation.m_offspring))) { prefab.Remove(); val = null; } } if ((Object)(object)val != (Object)null && Procreation != null) { Procreation.UpdateFields(val, ((Object)prefab).name, !isInstance); } } protected void UpdateNpcTalk(GameObject prefab, bool isInstance = false) { NpcTalk val = prefab.GetComponent(); if (!isInstance) { if ((Object)(object)val == (Object)null && NPCTalk != null) { val = prefab.AddComponent(); } else if ((Object)(object)val != (Object)null && NPCTalk == null) { prefab.Remove(); val = null; } } if ((Object)(object)val != (Object)null && NPCTalk != null) { NPCTalk.UpdateFields(val, ((Object)prefab).name, !isInstance); } } protected void UpdateSaddle(GameObject prefab, bool isInstance = false) { Sadle componentInChildren = prefab.GetComponentInChildren(true); Saddle saddle = prefab.GetComponent(); if (!isInstance) { if (Saddle != null && (Object)(object)componentInChildren == (Object)null && (Object)(object)saddle == (Object)null) { saddle = prefab.AddComponent(); } else if (Saddle == null) { prefab.Remove(); saddle = null; } } if ((Object)(object)saddle != (Object)null && Saddle != null) { Saddle.UpdateFields(saddle, ((Object)prefab).name, !isInstance); saddle.Restart(); } if (!((Object)(object)componentInChildren == (Object)null) && Saddle != null) { Saddle.UpdateFields(componentInChildren, ((Object)prefab).name, !isInstance); } } protected void UpdateMovementDamage(GameObject prefab, bool isInstance = false) { MovementDamage target = default(MovementDamage); if (MovementDamage != null && MovementDamage.m_areaOfEffect != null && prefab.TryGetComponent(ref target)) { MovementDamage.m_areaOfEffect.UpdateFields(target, ((Object)prefab).name, !isInstance); } } protected void UpdateDropProjectile(GameObject prefab, bool isInstance = false) { DropProjectileOverDistance target = default(DropProjectileOverDistance); if (DropProjectileOverDistance != null && prefab.TryGetComponent(ref target)) { DropProjectileOverDistance.UpdateFields(target, ((Object)prefab).name, !isInstance); } } protected Dictionary GetDefaultItems(Humanoid humanoid) { Dictionary dictionary = new Dictionary(); if (humanoid.m_defaultItems != null) { GameObject[] defaultItems = humanoid.m_defaultItems; foreach (GameObject val in defaultItems) { if (!((Object)(object)val == (Object)null)) { dictionary[((Object)val).name] = val; } } } if (humanoid.m_randomWeapon != null) { GameObject[] randomWeapon = humanoid.m_randomWeapon; foreach (GameObject val2 in randomWeapon) { if (!((Object)(object)val2 == (Object)null)) { dictionary[((Object)val2).name] = val2; } } } if (humanoid.m_randomSets != null) { ItemSet[] randomSets = humanoid.m_randomSets; foreach (ItemSet val3 in randomSets) { GameObject[] items = val3.m_items; foreach (GameObject val4 in items) { if (!((Object)(object)val4 == (Object)null)) { dictionary[((Object)val4).name] = val4; } } } } return dictionary; } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class BaseCharacter : Base { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 6)] public CharacterRef Character; [YamlMember(Order = 7)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public AnimalAIRef AI; public override void Setup(GameObject prefab, bool isClone = false, string source = "") { Character component = prefab.GetComponent(); AnimalAI component2 = prefab.GetComponent(); if (!((Object)(object)component == (Object)null) && !((Object)(object)component2 == (Object)null)) { base.Setup(prefab, isClone, source); Type = BaseType.Character; Character = new CharacterRef(component); AI = new AnimalAIRef(component2); } } public override void Update() { base.Update(); LoadManager.files.PrefabToUpdate = Prefab; LoadManager.files.Add(this); } public override void CopyFields(Header original) { base.CopyFields(original); if (original is BaseCharacter baseCharacter) { if (Character != null && baseCharacter.Character != null) { Character.ResetTo(baseCharacter.Character); } if (AI != null && baseCharacter.AI != null) { AI.ResetTo(baseCharacter.AI); } } } protected override void UpdatePrefab(GameObject prefab, bool isInstance = false) { base.UpdatePrefab(prefab, isInstance); UpdateCharacter(prefab, isInstance); UpdateAnimalTameable(prefab, isInstance); UpdateFootStep(prefab, isInstance); } private void UpdateCharacter(GameObject prefab, bool isInstance = false) { Character component = prefab.GetComponent(); AnimalAI component2 = ((Component)component).GetComponent(); if (!((Object)(object)component == (Object)null) && !((Object)(object)component2 == (Object)null)) { Character?.UpdateFields(component, ((Object)prefab).name, !isInstance); AI?.UpdateFields(component2, ((Object)prefab).name, !isInstance); } } private void UpdateAnimalTameable(GameObject prefab, bool isInstance = false) { if (AI == null) { return; } if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { prefab.Remove(); return; } AnimalTameable target = default(AnimalTameable); if (!prefab.TryGetComponent(ref target)) { target = prefab.AddComponent(); } AI.UpdateFields(target, ((Object)prefab).name, !isInstance); } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class BaseHumanoid : Base { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 6)] public HumanoidRef Character; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 7)] public MonsterAIRef AI; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 8)] public VisEquipmentRef VisEquipment; public override void Setup(GameObject prefab, bool isClone = false, string source = "") { Humanoid component = prefab.GetComponent(); MonsterAI component2 = prefab.GetComponent(); if (!((Object)(object)component == (Object)null) && !((Object)(object)component2 == (Object)null)) { base.Setup(prefab, isClone, source); Type = BaseType.Humanoid; Character = new HumanoidRef(component); AI = new MonsterAIRef(component2); VisEquipment comp = default(VisEquipment); if (prefab.TryGetComponent(ref comp)) { VisEquipment = new VisEquipmentRef(comp); } } } public override void CopyFields(Header original) { base.CopyFields(original); if (original is BaseHumanoid baseHumanoid) { if (Character != null && baseHumanoid.Character != null) { Character.ResetTo(baseHumanoid.Character); } if (AI != null && baseHumanoid.AI != null) { AI.ResetTo(baseHumanoid.AI); } if (VisEquipment != null && baseHumanoid.VisEquipment != null) { VisEquipment.ResetTo(baseHumanoid.VisEquipment); } } } public override void Update() { base.Update(); LoadManager.files.PrefabToUpdate = Prefab; LoadManager.files.Add(this); } protected override void UpdatePrefab(GameObject prefab, bool isInstance = false) { base.UpdatePrefab(prefab, isInstance); if (isInstance) { UpdateIHumanoid(prefab); return; } UpdateHumanoid(prefab); UpdateVisEquipment(prefab); } private void UpdateVisEquipment(GameObject prefab) { VisEquipment target = default(VisEquipment); if (VisEquipment != null && prefab.TryGetComponent(ref target)) { VisEquipment.UpdateFields(target, ((Object)prefab).name, log: true); } } private void UpdateHumanoid(GameObject prefab) { Humanoid component = prefab.GetComponent(); MonsterAI component2 = prefab.GetComponent(); if (!((Object)(object)component == (Object)null) && !((Object)(object)component2 == (Object)null)) { Character?.UpdateFields(component, ((Object)prefab).name, log: true); AI?.UpdateFields(component2, ((Object)prefab).name, log: true); } } private void UpdateIHumanoid(GameObject prefab) { Humanoid component = prefab.GetComponent(); MonsterAI component2 = prefab.GetComponent(); if ((Object)(object)component == (Object)null || (Object)(object)component2 == (Object)null) { return; } Character?.UpdateFields(component, ((Object)prefab).name, log: false); AI?.UpdateFields(component2, ((Object)prefab).name, log: false); GameObject prefab2 = PrefabManager.GetPrefab(Prefab); if (!((Object)(object)prefab2 == (Object)null)) { Humanoid component3 = prefab2.GetComponent(); if (!((Object)(object)component3 == (Object)null)) { component.m_defaultItems = component3.m_defaultItems; component.m_randomWeapon = component3.m_randomWeapon; component.m_randomSets = component3.m_randomSets; component.m_randomArmor = component3.m_randomArmor; component.m_randomShield = component3.m_randomShield; component.m_inventory.RemoveAll(); ((Character)component).Start(); } } } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class BaseHuman : BaseHumanoid { public override void Setup(GameObject prefab, bool isClone = false, string source = "") { SetupVersions(); Human component = prefab.GetComponent(); MonsterAI component2 = prefab.GetComponent(); if (!((Object)(object)component == (Object)null) && !((Object)(object)component2 == (Object)null)) { SetupSharedFields(prefab, isClone, source); Type = BaseType.Human; Character = new HumanoidRef((Humanoid)(object)component); AI = new MonsterAIRef(component2); Visuals?.SetDefaultHumanFields(); if (isClone) { SetupSpawnData(); } } } public override void Update() { base.Update(); LoadManager.files.PrefabToUpdate = Prefab; LoadManager.files.Add(this); } protected override void UpdatePrefab(GameObject prefab, bool isInstance = false) { base.UpdatePrefab(prefab, isInstance); UpdateHuman(prefab); } private void UpdateHuman(GameObject prefab) { Human component = prefab.GetComponent(); if (Visuals != null) { if (Visuals.m_beards != null) { component.m_beards = Visuals.m_beards; } if (Visuals.m_hairs != null) { component.m_hairs = Visuals.m_hairs; } if (Visuals.m_modelIndex != null) { component.m_models = Visuals.m_modelIndex; } if (Visuals.m_skinColors != null) { component.m_skinColors = Visuals.m_skinColors; } if (Visuals.m_hairColors != null) { component.m_hairColors = Visuals.m_hairColors; } } } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class EffectListRef { [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class EffectDataRef : Reference { public string m_prefab = ""; public int m_variant = -1; public bool m_attach; public bool m_follow; public bool m_inheritParentRotation; public bool m_inheritParentScale; public bool m_multiplyParentVisualScale; public bool m_randomRotation; public bool m_scale; public string m_childTransform = string.Empty; [NonSerialized] [YamlIgnore] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] private EffectData _data; public EffectData ToEffectData() { //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_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Expected O, but got Unknown //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown if (_data != null) { return _data; } GameObject prefab = PrefabManager.GetPrefab(m_prefab); if (prefab == null) { MonsterDBPlugin.LogError("Effect Data Reference invalid: " + m_prefab); return new EffectData(); } _data = new EffectData { m_prefab = prefab, m_variant = m_variant, m_attach = m_attach, m_follow = m_follow, m_inheritParentRotation = m_inheritParentRotation, m_inheritParentScale = m_inheritParentScale, m_multiplyParentVisualScale = m_multiplyParentVisualScale, m_randomRotation = m_randomRotation, m_scale = m_scale, m_childTransform = m_childTransform }; return _data; } } public List m_effectPrefabs = new List(); [NonSerialized] [YamlIgnore] private readonly List data = new List(); [NonSerialized] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlIgnore] private EffectList _effects; [YamlIgnore] public EffectList Effects { get { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Expected O, but got Unknown if (_effects != null) { return _effects; } foreach (EffectDataRef effectPrefab in m_effectPrefabs) { data.Add(effectPrefab.ToEffectData()); } _effects = new EffectList { m_effectPrefabs = data.ToArray() }; return _effects; } } public GameObject[] Create(Vector3 basePos, Quaternion baseRot, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Transform baseParent = null, float scale = 1f, int variant = -1) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) return Effects.Create(basePos, baseRot, baseParent, scale, variant); } public EffectListRef(params string[] effects) { Add(effects); } public EffectListRef(params EffectDataRef[] refs) { m_effectPrefabs.AddRange(refs); } public EffectListRef() { } public void Add(params string[] effects) { foreach (string prefab in effects) { m_effectPrefabs.Add(new EffectDataRef { m_prefab = prefab }); } } public void Add(params EffectDataRef[] refs) { m_effectPrefabs.AddRange(refs); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class BaseAggregate : Header { [YamlMember(Order = 6)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1 })] public Dictionary humanoids; [YamlMember(Order = 7)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1 })] public Dictionary characters; [YamlMember(Order = 8)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1 })] public Dictionary humans; [YamlMember(Order = 9)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1 })] public Dictionary eggs; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1 })] [YamlMember(Order = 10)] public Dictionary items; [YamlMember(Order = 11)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1 })] public Dictionary fishes; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1 })] [YamlMember(Order = 12)] public Dictionary projectiles; [YamlMember(Order = 13)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1 })] public Dictionary ragdolls; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1 })] [YamlMember(Order = 14)] public Dictionary spawnAbilities; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1 })] [YamlMember(Order = 15)] public Dictionary visuals; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1 })] [YamlMember(Order = 16)] public Dictionary CreatureSpawners; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1, 1, 1 })] [YamlMember(Order = 17)] public Dictionary> translations; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1 })] [YamlMember(Order = 18)] public Dictionary SpawnAreas; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1, 1 })] [YamlMember(Order = 19)] public Dictionary SpawnDatas; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string PrefabToUpdate; public int Count() { return (humanoids?.Count + characters?.Count + humans?.Count + eggs?.Count + items?.Count + fishes?.Count + projectiles?.Count + ragdolls?.Count + spawnAbilities?.Count + visuals?.Count + SpawnAreas?.Count).GetValueOrDefault(); } public bool GetPrefabToUpdate(out Header header) { header = null; if (PrefabToUpdate == null || string.IsNullOrEmpty(PrefabToUpdate)) { return false; } if (humanoids != null && humanoids.TryGetValue(PrefabToUpdate, out var value)) { header = value; return true; } if (characters != null && characters.TryGetValue(PrefabToUpdate, out var value2)) { header = value2; return true; } if (humans != null && humans.TryGetValue(PrefabToUpdate, out var value3)) { header = value3; return true; } if (eggs != null && eggs.TryGetValue(PrefabToUpdate, out var value4)) { header = value4; return true; } if (items != null && items.TryGetValue(PrefabToUpdate, out var value5)) { header = value5; return true; } if (fishes != null && fishes.TryGetValue(PrefabToUpdate, out var value6)) { header = value6; return true; } if (projectiles != null && projectiles.TryGetValue(PrefabToUpdate, out var value7)) { header = value7; return true; } if (ragdolls != null && ragdolls.TryGetValue(PrefabToUpdate, out var value8)) { header = value8; return true; } if (spawnAbilities != null && spawnAbilities.TryGetValue(PrefabToUpdate, out var value9)) { header = value9; return true; } if (visuals != null && visuals.TryGetValue(PrefabToUpdate, out var value10)) { header = value10; return true; } if (SpawnAreas != null && SpawnAreas.TryGetValue(PrefabToUpdate, out var value11)) { header = value11; return true; } return false; } private void ParseTranslations(string filePath, string fileName) { if (translations == null) { translations = new Dictionary>(); } string[] array = fileName.Split(new char[1] { '.' }); if (array.Length != 2) { return; } string key = array[1]; string[] array2 = File.ReadAllLines(filePath); if (array2.Length == 0) { return; } translations[key] = new Dictionary(); foreach (string text in array2) { if (!string.IsNullOrEmpty(text) && !text.StartsWith("#")) { string[] array3 = text.Split(new char[1] { ':' }); if (array3.Length >= 2) { string key2 = array3[0].Trim(); string value = array3[1].Trim(); translations[key][key2] = value; } } } } public void Read(string directoryPath) { SetupVersions(); Type = BaseType.All; if (!Directory.Exists(directoryPath)) { return; } string[] files = Directory.GetFiles(directoryPath, "*.yml", SearchOption.AllDirectories); foreach (string text in files) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text); if (fileNameWithoutExtension.StartsWith("translations.")) { ParseTranslations(text, fileNameWithoutExtension); continue; } string data = File.ReadAllText(text); Header header = ConfigManager.Deserialize
(data); switch (header.Type) { case BaseType.Humanoid: { BaseHumanoid humanoid = ConfigManager.Deserialize(data); Add(humanoid); break; } case BaseType.Character: { BaseCharacter character = ConfigManager.Deserialize(data); Add(character); break; } case BaseType.Human: { BaseHuman human = ConfigManager.Deserialize(data); Add(human); break; } case BaseType.Egg: { BaseEgg egg = ConfigManager.Deserialize(data); Add(egg); break; } case BaseType.Item: { BaseItem item = ConfigManager.Deserialize(data); Add(item); break; } case BaseType.Fish: { BaseFish fish = ConfigManager.Deserialize(data); Add(fish); break; } case BaseType.Projectile: { BaseProjectile projectile = ConfigManager.Deserialize(data); Add(projectile); break; } case BaseType.Ragdoll: { BaseRagdoll ragdoll = ConfigManager.Deserialize(data); Add(ragdoll); break; } case BaseType.SpawnAbility: { BaseSpawnAbility spawnAbility = ConfigManager.Deserialize(data); Add(spawnAbility); break; } case BaseType.Visual: { BaseVisual visual = ConfigManager.Deserialize(data); Add(visual); break; } case BaseType.SpawnArea: { BaseSpawnArea area = ConfigManager.Deserialize(data); Add(area); break; } } } } public List
Load() { List
list = new List
(); if (humanoids != null) { foreach (BaseHumanoid value2 in humanoids.Values) { list.Add(value2); } } if (characters != null) { foreach (BaseCharacter value3 in characters.Values) { list.Add(value3); } } if (humans != null) { foreach (BaseHuman value4 in humans.Values) { list.Add(value4); } } if (eggs != null) { foreach (BaseEgg value5 in eggs.Values) { list.Add(value5); } } if (items != null) { foreach (BaseItem value6 in items.Values) { list.Add(value6); } } if (fishes != null) { foreach (BaseFish value7 in fishes.Values) { list.Add(value7); } } if (projectiles != null) { foreach (BaseProjectile value8 in projectiles.Values) { list.Add(value8); } } if (ragdolls != null) { foreach (BaseRagdoll value9 in ragdolls.Values) { list.Add(value9); } } if (spawnAbilities != null) { foreach (BaseSpawnAbility value10 in spawnAbilities.Values) { list.Add(value10); } } if (visuals != null) { foreach (BaseVisual value11 in visuals.Values) { list.Add(value11); } } if (translations != null) { foreach (KeyValuePair> translation in translations) { string key = translation.Key; Dictionary value = translation.Value; LocalizationManager.AddWords(key, value); } } if (SpawnAreas != null) { foreach (BaseSpawnArea value12 in SpawnAreas.Values) { list.Add(value12); } } if (SpawnDatas != null) { foreach (BaseSpawnData value13 in SpawnDatas.Values) { list.Add(value13); } } return list; } public void Add(BaseSpawnData spawnData) { if (SpawnDatas == null) { SpawnDatas = new Dictionary(); } SpawnDatas[spawnData.Prefab] = spawnData; } public void Add(BaseSpawnArea area) { if (SpawnAreas == null) { SpawnAreas = new Dictionary(); } SpawnAreas[area.Prefab] = area; } public void Add(BaseVisual visual) { if (visuals == null) { visuals = new Dictionary(); } visuals[visual.Prefab] = visual; } public void Add(BaseCreatureSpawner spawner) { if (CreatureSpawners == null) { CreatureSpawners = new Dictionary(); } CreatureSpawners[spawner.Prefab] = spawner; } public void Add(BaseSpawnAbility spawnAbility) { if (spawnAbilities == null) { spawnAbilities = new Dictionary(); } spawnAbilities[spawnAbility.Prefab] = spawnAbility; } public void Add(BaseHumanoid humanoid) { if (humanoids == null) { humanoids = new Dictionary(); } humanoids[humanoid.Prefab] = humanoid; } public void Add(BaseCharacter character) { if (characters == null) { characters = new Dictionary(); } characters[character.Prefab] = character; } public void Add(BaseHuman human) { if (humans == null) { humans = new Dictionary(); } humans[human.Prefab] = human; } public void Add(BaseFish fish) { if (fishes == null) { fishes = new Dictionary(); } fishes[fish.Prefab] = fish; } public void Add(BaseProjectile projectile) { if (projectiles == null) { projectiles = new Dictionary(); } projectiles[projectile.Prefab] = projectile; } public void Add(BaseRagdoll ragdoll) { if (ragdolls == null) { ragdolls = new Dictionary(); } ragdolls[ragdoll.Prefab] = ragdoll; } public void Add(BaseEgg egg) { if (eggs == null) { eggs = new Dictionary(); } eggs[egg.Prefab] = egg; } public void Add(BaseItem item) { if (items == null) { items = new Dictionary(); } items[item.Prefab] = item; } public void AddTranslations(string language, string[] lines) { if (lines.Length == 0) { return; } if (translations == null) { translations = new Dictionary>(); } if (!translations.TryGetValue(language, out var value)) { value = new Dictionary(); } foreach (string text in lines) { if (!string.IsNullOrEmpty(text) && !text.StartsWith("#")) { string[] array = text.Split(new char[1] { ':' }); if (array.Length >= 2) { string key = array[0].Trim(); string value2 = array[1].Trim(); value[key] = value2; } } } translations[language] = value; } public void Add(BaseAggregate other) { if (other.humanoids != null) { foreach (BaseHumanoid value2 in other.humanoids.Values) { Add(value2); } } if (other.characters != null) { foreach (BaseCharacter value3 in other.characters.Values) { Add(value3); } } if (other.humans != null) { foreach (BaseHuman value4 in other.humans.Values) { Add(value4); } } if (other.ragdolls != null) { foreach (BaseRagdoll value5 in other.ragdolls.Values) { Add(value5); } } if (other.items != null) { foreach (BaseItem value6 in other.items.Values) { Add(value6); } } if (other.eggs != null) { foreach (BaseEgg value7 in other.eggs.Values) { Add(value7); } } if (other.projectiles != null) { foreach (BaseProjectile value8 in other.projectiles.Values) { Add(value8); } } if (other.fishes != null) { foreach (BaseFish value9 in other.fishes.Values) { Add(value9); } } if (other.spawnAbilities != null) { foreach (BaseSpawnAbility value10 in other.spawnAbilities.Values) { Add(value10); } } if (other.translations != null) { if (translations == null) { translations = other.translations; } else { foreach (KeyValuePair> translation in other.translations) { if (translations.TryGetValue(translation.Key, out var value)) { foreach (KeyValuePair item in translation.Value) { value[item.Key] = item.Value; } } else { translations.Add(translation.Key, translation.Value); } } } } if (other.SpawnAreas != null) { if (SpawnAreas == null) { SpawnAreas = other.SpawnAreas; } else { foreach (BaseSpawnArea value11 in other.SpawnAreas.Values) { Add(value11); } } } if (other.SpawnDatas == null) { return; } if (SpawnDatas == null) { SpawnDatas = other.SpawnDatas; return; } foreach (BaseSpawnData value12 in other.SpawnDatas.Values) { Add(value12); } } } public enum BaseType { None, Humanoid, Character, Egg, Human, Item, Fish, Projectile, Ragdoll, SpawnAbility, Visual, CreatureSpawner, SpawnArea, SpawnData, All } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class FileManager { public const string ExportFolderName = "Export"; public const string ImportFolderName = "Import"; public static readonly string ExportFolder; public static readonly string ImportFolder; private static readonly ConfigEntry _fileWatcherEnabled; public static bool started; static FileManager() { ExportFolder = Path.Combine(ConfigManager.DirectoryPath, "Export"); ImportFolder = Path.Combine(ConfigManager.DirectoryPath, "Import"); _fileWatcherEnabled = ConfigManager.config("File Watcher", "Import", Toggle.On, "If on, YML files under Import folder will trigger to update when changed, created or renamed", synchronizedSetting: false); if (!Directory.Exists(ExportFolder)) { Directory.CreateDirectory(ExportFolder); } if (!Directory.Exists(ImportFolder)) { Directory.CreateDirectory(ImportFolder); } } private static bool IsFileWatcherEnabled() { return _fileWatcherEnabled.Value == Toggle.On; } public static List GetModFileNames() { return Directory.GetFiles(ImportFolder, "*.yml", SearchOption.AllDirectories).Select(Path.GetFileNameWithoutExtension).ToList(); } public static void Start() { if (started) { return; } string[] files = Directory.GetFiles(ImportFolder, "*.yml", SearchOption.AllDirectories); foreach (string text in files) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text); if (fileNameWithoutExtension.StartsWith("translations.")) { LocalizationManager.Register(text); continue; } string data = File.ReadAllText(text); try { Header header = ConfigManager.Deserialize
(data); switch (header.Type) { case BaseType.Character: { BaseCharacter baseCharacter = ConfigManager.Deserialize(data); LoadManager.modified.Add(baseCharacter); RegisterSpawnList(baseCharacter.SpawnData); LoadManager.files.Add(baseCharacter); break; } case BaseType.Humanoid: { BaseHumanoid baseHumanoid = ConfigManager.Deserialize(data); LoadManager.modified.Add(baseHumanoid); RegisterSpawnList(baseHumanoid.SpawnData); LoadManager.files.Add(baseHumanoid); break; } case BaseType.Human: { BaseHuman baseHuman = ConfigManager.Deserialize(data); LoadManager.modified.Add(baseHuman); RegisterSpawnList(baseHuman.SpawnData); LoadManager.files.Add(baseHuman); break; } case BaseType.Egg: { BaseEgg baseEgg = ConfigManager.Deserialize(data); LoadManager.modified.Add(baseEgg); LoadManager.files.Add(baseEgg); break; } case BaseType.Item: { BaseItem baseItem = ConfigManager.Deserialize(data); LoadManager.modified.Add(baseItem); LoadManager.files.Add(baseItem); break; } case BaseType.Fish: { BaseFish baseFish = ConfigManager.Deserialize(data); LoadManager.modified.Add(baseFish); LoadManager.files.Add(baseFish); break; } case BaseType.Projectile: { BaseProjectile baseProjectile = ConfigManager.Deserialize(data); LoadManager.modified.Add(baseProjectile); LoadManager.files.Add(baseProjectile); break; } case BaseType.Ragdoll: { BaseRagdoll baseRagdoll = ConfigManager.Deserialize(data); LoadManager.modified.Add(baseRagdoll); LoadManager.files.Add(baseRagdoll); break; } case BaseType.SpawnAbility: { BaseSpawnAbility baseSpawnAbility = ConfigManager.Deserialize(data); LoadManager.modified.Add(baseSpawnAbility); LoadManager.files.Add(baseSpawnAbility); break; } case BaseType.Visual: { BaseVisual baseVisual = ConfigManager.Deserialize(data); LoadManager.modified.Add(baseVisual); LoadManager.files.Add(baseVisual); break; } case BaseType.SpawnArea: { BaseSpawnArea baseSpawnArea = ConfigManager.Deserialize(data); LoadManager.modified.Add(baseSpawnArea); LoadManager.files.Add(baseSpawnArea); break; } case BaseType.All: { BaseAggregate baseAggregate = ConfigManager.Deserialize(data); LoadManager.modified.AddRange(baseAggregate.Load()); LoadManager.files.Add(baseAggregate); break; } case BaseType.SpawnData: { BaseSpawnData baseSpawnData = ConfigManager.Deserialize(data); LoadManager.modified.Add(baseSpawnData); LoadManager.files.Add(baseSpawnData); break; } case BaseType.CreatureSpawner: break; } } catch (Exception ex) { MonsterDBPlugin.LogWarning("Failed to deserialize: " + Path.GetFileName(text)); MonsterDBPlugin.LogDebug(ex.Message); } } MonsterDBPlugin.LogInfo($"Loaded {files.Length} files."); started = true; } private static void RegisterSpawnList([<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] SpawnDataRef[] list) { if (list != null) { foreach (SpawnDataRef data in list) { SpawnManager.Add(data); } } } public static void SetupFileWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(ImportFolder, "*.yml"); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private static void ReadConfigValues(object sender, FileSystemEventArgs e) { if (IsFileWatcherEnabled() && Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer()) { string fullPath = e.FullPath; Read(fullPath); } } public static void Read(string filePath) { if (!File.Exists(filePath)) { return; } string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath); if (fileNameWithoutExtension.StartsWith("translations.")) { LocalizationManager.UpdateWords(filePath); return; } string data = File.ReadAllText(filePath); try { Header header = ConfigManager.Deserialize
(data); switch (header.Type) { case BaseType.Humanoid: { BaseHumanoid baseHumanoid = ConfigManager.Deserialize(data); baseHumanoid.Update(); LoadManager.UpdateSync(); break; } case BaseType.Character: { BaseCharacter baseCharacter = ConfigManager.Deserialize(data); baseCharacter.Update(); LoadManager.UpdateSync(); break; } case BaseType.Human: { BaseHuman baseHuman = ConfigManager.Deserialize(data); baseHuman.Update(); LoadManager.UpdateSync(); break; } case BaseType.Egg: { BaseEgg baseEgg = ConfigManager.Deserialize(data); baseEgg.Update(); LoadManager.UpdateSync(); break; } case BaseType.Item: { BaseItem baseItem = ConfigManager.Deserialize(data); baseItem.Update(); LoadManager.UpdateSync(); break; } case BaseType.Fish: { BaseFish baseFish = ConfigManager.Deserialize(data); baseFish.Update(); LoadManager.UpdateSync(); break; } case BaseType.Projectile: { BaseProjectile baseProjectile = ConfigManager.Deserialize(data); baseProjectile.Update(); LoadManager.UpdateSync(); break; } case BaseType.Ragdoll: { BaseRagdoll baseRagdoll = ConfigManager.Deserialize(data); baseRagdoll.Update(); LoadManager.UpdateSync(); break; } case BaseType.SpawnAbility: { BaseSpawnAbility baseSpawnAbility = ConfigManager.Deserialize(data); baseSpawnAbility.Update(); LoadManager.UpdateSync(); break; } case BaseType.Visual: { BaseVisual baseVisual = ConfigManager.Deserialize(data); baseVisual.Update(); LoadManager.UpdateSync(); break; } case BaseType.SpawnArea: { BaseSpawnArea baseSpawnArea = ConfigManager.Deserialize(data); baseSpawnArea.Update(); LoadManager.UpdateSync(); break; } case BaseType.SpawnData: { BaseSpawnData baseSpawnData = ConfigManager.Deserialize(data); baseSpawnData.Update(); LoadManager.UpdateSync(); break; } case BaseType.CreatureSpawner: break; } } catch (Exception ex) { MonsterDBPlugin.LogWarning("Failure updating file: " + Path.GetFileName(filePath)); MonsterDBPlugin.LogWarning(ex.Message); MonsterDBPlugin.LogDebug(ex.StackTrace); } } public static void Export(string dirPath) { try { BaseAggregate baseAggregate = new BaseAggregate(); baseAggregate.Read(dirPath); string contents = ConfigManager.Serialize(baseAggregate); string path = Path.Combine(ExportFolder, "All.yml"); File.WriteAllText(path, contents); } catch { MonsterDBPlugin.LogWarning("Failed to aggregate files"); } } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class BaseEgg : BaseItem { [YamlMember(Order = 8, Description = "If field removed, will remove component")] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public EggGrowRef EggGrow; public override void Setup(GameObject prefab, bool isClone = false, string source = "") { SetupVersions(); SetupItem(prefab); SetupVisuals(prefab); Type = BaseType.Egg; Prefab = ((Object)prefab).name; ClonedFrom = source; IsCloned = isClone; EggGrow egg = default(EggGrow); if (prefab.TryGetComponent(ref egg)) { EggGrow = new EggGrowRef(egg); } } public override void CopyFields(Header original) { base.CopyFields(original); if (original is BaseEgg baseEgg) { if (baseEgg.EggGrow == null) { EggGrow = null; } if (EggGrow != null && baseEgg.EggGrow != null) { EggGrow.ResetTo(baseEgg.EggGrow); } } } public override void Update() { base.Update(); LoadManager.files.PrefabToUpdate = Prefab; LoadManager.files.Add(this); } protected override void SaveDefault(GameObject prefab) { if (EggManager.TrySave(prefab, out var egg, IsCloned, ClonedFrom)) { LoadManager.originalToModifiedList.Add(egg, this); } } protected override void UpdatePrefab(GameObject prefab) { UpdateEgg(prefab); base.UpdatePrefab(prefab); } private void UpdateEgg(GameObject prefab) { EggGrow val = prefab.GetComponent(); if ((Object)(object)val == (Object)null) { if (EggGrow != null && !string.IsNullOrEmpty(EggGrow.m_grownPrefab)) { val = prefab.AddComponent(); EggManager.RegisterHoverOverride(((Object)prefab).name); } } else if (EggGrow == null || string.IsNullOrEmpty(EggGrow.m_grownPrefab)) { val = null; prefab.Remove(); } if (!((Object)(object)val == (Object)null) && EggGrow != null) { EggGrow.UpdateFields(val, ((Object)prefab).name, log: true); } } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class EggGrowRef : Reference { public float? m_growTime; public string m_grownPrefab; public bool? m_tamed; public float? m_updateInterval; public bool? m_requireNearbyFire; public bool? m_requireUnderRoof; [YamlMember(Alias = "m_requireCoverPercentage")] public float? m_requireCoverPercentige; public EffectListRef m_hatchEffect; public string m_growingObject; public string m_notGrowingObject; public EggGrowRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public EggGrowRef(EggGrow egg) { Setup(egg); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] protected override void UpdateGameObject<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, string targetName, string goName, bool log) { if (targetField.Name == "m_growingObject" || targetField.Name == "m_notGrowingObject") { object obj = target; EggGrow val = (EggGrow)((obj is EggGrow) ? obj : null); if (val == null) { return; } if (string.IsNullOrEmpty(goName)) { targetField.SetValue(target, null); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": null"); } return; } Transform val2 = Utils.FindChild(((Component)val).transform, goName, (IterativeSearchType)0); if ((Object)(object)val2 != (Object)null) { targetField.SetValue(target, ((Component)val2).gameObject); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + ((Object)val2).name); } } } else { base.UpdateGameObject(target, targetField, targetName, goName, log); } } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class EggManager { private static readonly List newEggComponentPrefabs; private static readonly ConfigEntry _addPercentage; private static bool addPercentage => _addPercentage.Value == Toggle.On; public static void RegisterHoverOverride(string prefabName) { if (!newEggComponentPrefabs.Contains(prefabName)) { newEggComponentPrefabs.Add(prefabName); } } static EggManager() { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Expected O, but got Unknown //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Expected O, but got Unknown _addPercentage = ConfigManager.config("Eggs", "Growth Percentage", Toggle.On, "If on, will add growth percentage to hover text"); newEggComponentPrefabs = new List(); Harmony harmony = MonsterDBPlugin.harmony; harmony.Patch((MethodBase)AccessTools.Method(typeof(ItemDrop), "GetHoverText", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(EggManager), "Patch_ItemDrop_GetHoverText", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(EggGrow), "GetHoverText", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(EggManager), "Patch_EggGrow_GetHoverText", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(EggGrow), "UpdateEffects", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(EggManager), "Patch_EggGrow_UpdateEffects", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } [Obsolete] public static void WriteEggYML(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); return; } if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { args.Context.LogWarning("Invalid, missing ItemDrop component"); return; } string sourceName; bool isClone = CloneManager.IsClone(((Object)prefab).name, out sourceName); Write(prefab, isClone, sourceName, args.Context); } [Obsolete] public static List GetEggOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : PrefabManager.GetAllPrefabNames()); if (1 == 0) { } return result; } [Obsolete] public static void WriteAllEggYML(ConsoleEventArgs args) { List allPrefabs = PrefabManager.GetAllPrefabs(); for (int i = 0; i < allPrefabs.Count; i++) { GameObject prefab = allPrefabs[i]; Write(prefab, isClone: false, "", args.Context); } args.Context.AddString($"Exported {allPrefabs.Count} egg files"); } [Obsolete] public static void ReadEgg(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); return; } string filePath = Path.Combine(FileManager.ImportFolder, @string + ".yml"); Read(filePath); } [Obsolete] public static void ResetEgg(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid prefab"); return; } BaseEgg original = LoadManager.GetOriginal(@string); if (original == null) { args.Context.LogWarning("Original data not found"); return; } original.Update(); LoadManager.UpdateSync(); } [Obsolete] public static List GetResetOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : LoadManager.GetOriginalKeys()); if (1 == 0) { } return result; } [Obsolete] public static void CloneEgg(ConsoleEventArgs args) { string @string = args.GetString(2); string string2 = args.GetString(3); if (string.IsNullOrEmpty(@string) || string.IsNullOrEmpty(string2)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); } else if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { args.Context.LogWarning("Invalid prefab, missing ItemDrop component"); } else { TryClone(prefab, string2); } } public static bool TrySave(GameObject prefab, out BaseEgg egg, bool isClone = false, string source = "") { egg = LoadManager.GetOriginal(((Object)prefab).name); if (egg != null) { return true; } egg = new BaseEgg(); egg.Setup(prefab, isClone, source); LoadManager.originals.Add(((Object)prefab).name, egg); return true; } [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public static string Save(GameObject prefab, bool isClone = false, string clonedFrom = "") { if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { return null; } BaseEgg original = LoadManager.GetOriginal(((Object)prefab).name); if (original != null) { return ConfigManager.Serialize(original); } original = new BaseEgg(); original.Setup(prefab, isClone, clonedFrom); LoadManager.originals.Add(((Object)prefab).name, original); return ConfigManager.Serialize(original); } public static bool Write(GameObject prefab, bool isClone = false, string clonedFrom = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { string text = Path.Combine(FileManager.ExportFolder, ((Object)prefab).name + ".yml"); string text2 = Save(prefab, isClone, clonedFrom); if (string.IsNullOrEmpty(text2)) { return false; } File.WriteAllText(text, text2); MonsterDBPlugin.LogInfo("Saved " + ((Object)prefab).name + " to: " + text); context?.LogInfo("Exported Egg " + ((Object)prefab).name); context?.LogInfo(text.RemoveRootPath()); return true; } private static void Read(string filePath) { if (!File.Exists(filePath)) { return; } string data = File.ReadAllText(filePath); try { Header header = ConfigManager.Deserialize
(data); if (header.Type == BaseType.Egg) { BaseEgg baseEgg = ConfigManager.Deserialize(data); baseEgg.Update(); LoadManager.UpdateSync(); } } catch { MonsterDBPlugin.LogWarning("Failed to deserialize: " + Path.GetFileName(filePath)); } } public static bool TryClone(GameObject source, string cloneName, bool write = true, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (CloneManager.prefabs.ContainsKey(cloneName)) { context?.LogWarning("Clone prefab already exists"); return false; } if (!Object.op_Implicit((Object)(object)source.GetComponent())) { context?.LogWarning("Prefab missing ItemDrop component"); return false; } Clone clone = new Clone(source, cloneName); clone.OnCreated += delegate(GameObject p) { if (!Object.op_Implicit((Object)(object)p.GetComponent())) { p.AddComponent(); RegisterHoverOverride(((Object)p).name); } MonsterDBPlugin.LogDebug("Cloned " + ((Object)source).name + " as " + cloneName); if (write) { Write(p, isClone: true, ((Object)source).name, context); } }; clone.Create(); context?.LogInfo("Cloned " + ((Object)source).name + " as " + cloneName); return true; } private static bool IsNewEgg(ItemDrop item) { string prefabName = Utils.GetPrefabName(((Object)item).name); return newEggComponentPrefabs.Contains(prefabName); } private static void GetEggGrowth(EggGrow egg, out bool isGrowing, out double growPercentage) { float @float = egg.m_nview.GetZDO().GetFloat(ZDOVars.s_growStart, 0f); isGrowing = (double)@float > 0.0; growPercentage = 0.0; if (isGrowing) { double num = ZNet.instance.GetTimeSeconds() - (double)@float; growPercentage = Mathf.Clamp01((float)num / egg.m_growTime) * 100f; } } private static string GetEggHoverText(ItemDrop item, EggGrow eggGrow) { //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Invalid comparison between Unknown and I4 item.Load(); GetEggGrowth(eggGrow, out var isGrowing, out var growPercentage); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(item.m_itemData.m_shared.m_name); if (item.m_itemData.m_quality > 1) { stringBuilder.Append($"[{item.m_itemData.m_quality}]"); } if (item.m_itemData.m_stack > 1) { stringBuilder.Append($" x{item.m_itemData.m_stack}"); stringBuilder.Append(" $item_chicken_egg_stacked"); } else if (isGrowing) { string text = Localization.instance.Localize("$item_chicken_egg_warm"); text = text.Replace("(", string.Empty).Replace(")", string.Empty).Trim(); stringBuilder.Append(" (" + text); if (addPercentage) { stringBuilder.Append($" {growPercentage:0.0}%"); } stringBuilder.Append(")"); } else { stringBuilder.Append(" $item_chicken_egg_cold"); } if ((int)item.m_itemData.m_shared.m_itemType == 2 && item.IsPiece()) { string text2 = (item.m_itemData.m_shared.m_isDrink ? "$item_drink" : "$item_eat"); stringBuilder.Append("\n[$KEY_Use] " + text2); } else { stringBuilder.Append("\n[$KEY_Use] $inventory_pickup"); } return Localization.instance.Localize(stringBuilder.ToString()); } private static bool Patch_ItemDrop_GetHoverText(ItemDrop __instance, ref string __result) { EggGrow val = default(EggGrow); if (!((Component)__instance).TryGetComponent(ref val) || !IsNewEgg(__instance)) { return true; } if (!Object.op_Implicit((Object)(object)val.m_nview) || !val.m_nview.IsValid()) { return true; } __result = GetEggHoverText(__instance, val); return false; } private static bool Patch_EggGrow_GetHoverText(EggGrow __instance, ref string __result) { if (_addPercentage.Value == Toggle.Off) { return true; } if (!Object.op_Implicit((Object)(object)__instance.m_item)) { return true; } if (!Object.op_Implicit((Object)(object)__instance.m_nview) || !__instance.m_nview.IsValid()) { __result = __instance.m_item.GetHoverText(); return false; } __result = GetEggHoverText(__instance.m_item, __instance); return false; } private static void Patch_EggGrow_UpdateEffects(EggGrow __instance, float grow) { if (!IsNewEgg(__instance.m_item)) { return; } ParticleSystem component = ((Component)__instance).GetComponent(); if (!((Object)(object)component == (Object)null)) { if ((double)grow == 0.0) { component.Play(); } else { component.Stop(); } } } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class Faction { public string name = ""; public bool targetTamed = true; public bool targetTameables = true; public List allies = new List(); public void Setup() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(name)) { return; } FactionManager.GetFaction(name, this); MonsterDBPlugin.LogInfo("Loading faction: " + name); if (ConfigManager.ShouldLogDetails()) { MonsterDBPlugin.LogDebug($"[ Faction: {name} ] m_targetTamed: {targetTamed}, m_targetTameables: {targetTameables}"); MonsterDBPlugin.LogDebug("[ Faction: " + name + " ] m_allies: " + string.Join(", ", allies.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (Faction s) => ((object)(Faction)(ref s)).ToString()))); } } public bool IsEnemy(Character custom, Character other) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (allies.Contains(other.m_faction)) { return false; } bool flag = custom.IsTamed(); bool flag2 = other.IsTamed(); if (flag && flag2) { return false; } if (flag2) { return targetTamed; } if (Object.op_Implicit((Object)(object)((Component)other).GetComponent()) && !targetTameables) { return false; } return true; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class FactionManager { private static readonly Dictionary customFactions; private static readonly Dictionary factions; private const string FileName = "Factions.yml"; private static readonly string FilePath; private static string rawFile; private static readonly CustomSyncedValue sync; private static readonly ConfigEntry _fileWatcherEnabled; static FactionManager() { //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Expected O, but got Unknown //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Expected O, but got Unknown //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Expected O, but got Unknown //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Expected O, but got Unknown rawFile = ""; customFactions = new Dictionary(); factions = new Dictionary(); FilePath = Path.Combine(ConfigManager.DirectoryPath, "Factions.yml"); sync = new CustomSyncedValue(ConfigManager.ConfigSync, "MonsterDB.ServerSync.Factions", ""); sync.ValueChanged += OnSyncChange; _fileWatcherEnabled = ConfigManager.config("File Watcher", "Faction File", Toggle.On, "If on, Faction.yml changed, renamed or created will trigger update"); Harmony harmony = MonsterDBPlugin.harmony; harmony.Patch((MethodBase)AccessTools.Method(typeof(Enum), "GetValues", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(FactionManager), "Patch_Enum_GetValues", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(Enum), "GetNames", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(FactionManager), "Patch_Enum_GetNames", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(BaseAI), "IsEnemy", new Type[2] { typeof(Character), typeof(Character) }, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(FactionManager), "Patch_BaseAI_IsEnemy", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(Enum), "GetName", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(FactionManager), "Patch_Enum_GetName", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } private static bool IsFileWatcherEnabled() { return _fileWatcherEnabled.Value == Toggle.On; } public static void Start() { if (File.Exists(FilePath)) { Read(FilePath); } } public static void Init(ZNet net) { if (net.IsServer()) { UpdateSync(); SetupFileWatcher(); } } private static void UpdateSync() { if (Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer()) { sync.Value = rawFile; } } private static void OnSyncChange() { if (!Object.op_Implicit((Object)(object)ZNet.instance) || ZNet.instance.IsServer() || string.IsNullOrEmpty(sync.Value)) { return; } try { List list = ConfigManager.Deserialize>(sync.Value); customFactions.Clear(); factions.Clear(); for (int i = 0; i < list.Count; i++) { Faction faction = list[i]; faction.Setup(); } } catch { MonsterDBPlugin.LogWarning("Failed to deserialize server factions"); } } private static void SetupFileWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(ConfigManager.DirectoryPath, "Factions.yml"); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private static void ReadConfigValues(object sender, FileSystemEventArgs e) { if (IsFileWatcherEnabled()) { Read(FilePath); } } private static void Read(string filePath) { try { string data = File.ReadAllText(filePath); List list = ConfigManager.Deserialize>(data); foreach (Faction item in list) { item.Setup(); } rawFile = data; UpdateSync(); } catch { MonsterDBPlugin.LogWarning("Failed to deserialize factions: " + Path.GetFileName(filePath)); } } private static bool IsCustom(Faction faction) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return customFactions.ContainsKey(faction); } private static bool Patch_BaseAI_IsEnemy(Character a, Character b, ref bool __result) { //IL_0002: 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) if (!IsCustom(a.m_faction) && !IsCustom(b.m_faction)) { return true; } __result = IsEnemy(a, b); return false; } private static bool IsEnemy(Character a, Character b) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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) if (a.m_faction == b.m_faction) { return false; } string group = a.GetGroup(); string group2 = b.GetGroup(); if (group.Length > 0 && group == group2) { return false; } if (IsCustom(a.m_faction)) { return IsEnemyToCreatures(a, b); } if (IsCustom(b.m_faction)) { return IsEnemyToCreatures(b, a); } return true; } private static bool IsEnemyToCreatures(Character custom, Character other) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) if (!customFactions.TryGetValue(custom.m_faction, out var value)) { return true; } return value.IsEnemy(custom, other); } private static void Patch_Enum_GetValues(Type enumType, ref Array __result) { if (!(enumType != typeof(Faction)) && factions.Count != 0) { Faction[] array = (Faction[])(object)new Faction[__result.Length + factions.Count]; __result.CopyTo(array, 0); factions.Values.CopyTo(array, __result.Length); __result = array; } } private static void Patch_Enum_GetNames(Type enumType, ref string[] __result) { if (!(enumType != typeof(Faction)) && factions.Count != 0) { __result = CollectionExtensions.AddRangeToArray(__result, factions.Keys.ToArray()); } } private static bool Patch_Enum_GetName(Type enumType, object value, ref string __result) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) if (enumType != typeof(Faction)) { return true; } if (customFactions.TryGetValue((Faction)value, out var value2)) { __result = value2.name; return false; } return true; } public static Faction GetFaction(string name, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Faction data = null) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0078: 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_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) if (Enum.TryParse(name, ignoreCase: true, out Faction result)) { return result; } if (factions.TryGetValue(name, out result)) { return result; } Dictionary factionMap = GetFactionMap(); foreach (KeyValuePair item in factionMap) { if (item.Value == name) { result = item.Key; factions[name] = result; return result; } } int stableHashCode = StringExtensionMethods.GetStableHashCode(name); result = (Faction)stableHashCode; factions[name] = result; if (data == null && !customFactions.TryGetValue(result, out data)) { data = new Faction { name = name }; MonsterDBPlugin.LogInfo("Loading faction: " + name + " ( missing YML data, will be enemy to everyone! )"); } customFactions[result] = data; return result; } private static Dictionary GetFactionMap() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) Array values = Enum.GetValues(typeof(Faction)); string[] names = Enum.GetNames(typeof(Faction)); Dictionary dictionary = new Dictionary(); for (int i = 0; i < values.Length; i++) { dictionary[(Faction)values.GetValue(i)] = names[i]; } return dictionary; } } [Serializable] public class BaitSettingRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] public string m_bait = ""; public float m_chance; } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class BaseFish : BaseItem { [YamlMember(Order = 8, Description = "If field removed, will remove component")] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public FishRef Fish; public override void Setup(GameObject prefab, bool isClone = false, string source = "") { SetupVersions(); SetupVisuals(prefab); SetupItem(prefab); Type = BaseType.Fish; Prefab = ((Object)prefab).name; ClonedFrom = source; IsCloned = isClone; Fish fish = default(Fish); if (prefab.TryGetComponent(ref fish)) { Fish = new FishRef(fish); } } public override void CopyFields(Header original) { base.CopyFields(original); if (original is BaseFish baseFish) { if (baseFish.Fish == null) { Fish = null; } if (Fish != null && baseFish.Fish != null) { Fish.ResetTo(baseFish.Fish); } } } public override void Update() { base.Update(); LoadManager.files.PrefabToUpdate = Prefab; LoadManager.files.Add(this); } protected override void SaveDefault(GameObject prefab) { if (FishManager.TrySave(prefab, out var fish, IsCloned, ClonedFrom)) { LoadManager.originalToModifiedList.Add(fish, this); } } protected override void UpdatePrefab(GameObject prefab) { base.UpdatePrefab(prefab); UpdateFish(prefab); } private void UpdateFish(GameObject prefab) { Fish val = default(Fish); if (!prefab.TryGetComponent(ref val)) { if (Fish != null) { val = prefab.AddComponent(); } } else if (Fish == null) { prefab.Remove(); val = null; } if (!((Object)(object)val == (Object)null) && Fish != null) { Fish.UpdateFields(val, ((Object)prefab).name, log: true); } } } [Serializable] public class DropDataRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] public string m_item = ""; public int m_stackMin = 1; public int m_stackMax = 1; public float m_weight = 1f; public bool m_dontScale; public DropDataRef() { } public DropDataRef(DropData data) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) Setup(data); } public DropData ToDropData() { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) DropData result = default(DropData); result.m_item = PrefabManager.GetPrefab(m_item); result.m_weight = m_weight; result.m_dontScale = m_dontScale; result.m_stackMin = m_stackMin; result.m_stackMax = m_stackMax; return result; } } [Serializable] public class DropTableRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_drops; public int? m_dropMin; public int? m_dropMax; public float? m_dropChance; public bool? m_oneOfEach; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public DropTable ToDropTable(string targetName = "") { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown DropTable val = new DropTable(); UpdateFields(val, targetName, log: false); return val; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class FishManager { [Obsolete] public static void WriteFishYML(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if (!((Object)(object)prefab == (Object)null)) { if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { args.Context.LogWarning("Invalid, missing ItemDrop component"); } else { Write(prefab); } } } [Obsolete] public static List GetFishOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : PrefabManager.GetAllPrefabNames()); if (1 == 0) { } return result; } [Obsolete] public static void WriteAllFishYML(ConsoleEventArgs args) { List allPrefabs = PrefabManager.GetAllPrefabs(); foreach (GameObject item in allPrefabs) { Write(item); } } [Obsolete] public static void UpdateFishYML(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); return; } string filePath = Path.Combine(FileManager.ImportFolder, @string + ".yml"); Read(filePath); } [Obsolete] public static void ResetFish(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid prefab"); return; } BaseFish original = LoadManager.GetOriginal(@string); if (original == null) { args.Context.LogWarning("Original data not found"); return; } original.Update(); LoadManager.UpdateSync(); } [Obsolete] public static List GetResetFishOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : LoadManager.GetOriginalKeys()); if (1 == 0) { } return result; } [Obsolete] public static void CloneFish(ConsoleEventArgs args) { string @string = args.GetString(2); string string2 = args.GetString(3); if (string.IsNullOrEmpty(@string) || string.IsNullOrEmpty(string2)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); } else if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { args.Context.LogWarning("Invalid prefab, missing ItemDrop component"); } else { TryClone(prefab, string2); } } public static bool TrySave(GameObject prefab, out BaseFish fish, bool isClone = false, string source = "") { fish = LoadManager.GetOriginal(((Object)prefab).name); if (fish != null) { return true; } fish = new BaseFish(); fish.Setup(prefab, isClone, source); LoadManager.originals.Add(((Object)prefab).name, fish); return true; } [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public static string Save(GameObject prefab, bool isClone = false, string source = "") { if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { return null; } BaseFish original = LoadManager.GetOriginal(((Object)prefab).name); if (original != null) { return ConfigManager.Serialize(original); } BaseFish baseFish = new BaseFish(); baseFish.Setup(prefab, isClone, source); LoadManager.originals.Add(((Object)prefab).name, baseFish); return ConfigManager.Serialize(baseFish); } public static bool Write(GameObject prefab, bool isClone = false, string clonedFrom = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { string text = Path.Combine(FileManager.ExportFolder, ((Object)prefab).name + ".yml"); string text2 = Save(prefab, isClone, clonedFrom); if (string.IsNullOrEmpty(text2)) { return false; } File.WriteAllText(text, text2); MonsterDBPlugin.LogInfo("Saved " + ((Object)prefab).name + " to: " + text); context?.LogInfo("Exported Fish " + ((Object)prefab).name); context?.LogInfo(text.RemoveRootPath()); return true; } private static void Read(string filePath) { if (!File.Exists(filePath)) { return; } string data = File.ReadAllText(filePath); try { Header header = ConfigManager.Deserialize
(data); if (header.Type == BaseType.Fish) { BaseFish baseFish = ConfigManager.Deserialize(data); baseFish.Update(); LoadManager.UpdateSync(); } } catch { MonsterDBPlugin.LogWarning("Failed to deserialize: " + Path.GetFileName(filePath)); } } public static bool TryClone(GameObject source, string cloneName, bool write = true, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (CloneManager.prefabs.ContainsKey(cloneName)) { return false; } if (!Object.op_Implicit((Object)(object)source.GetComponent())) { return false; } Clone clone = new Clone(source, cloneName); clone.OnCreated += delegate(GameObject p) { MonsterDBPlugin.LogDebug("Cloned " + ((Object)source).name + " as " + cloneName); if (!Object.op_Implicit((Object)(object)p.GetComponent())) { p.AddComponent(); } if (write) { Write(p, isClone: true, ((Object)source).name, context); } }; clone.Create(); context?.LogInfo("Cloned " + ((Object)source).name + " as " + cloneName); return true; } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class FishRef : Reference { public string m_name; public float? m_swimRange; public float? m_minDepth; public float? m_maxDepth; public float? m_speed; public float? m_acceleration; public float? m_turnRate; public float? m_wpDurationMin; public float? m_wpDurationMax; public float? m_avoidSpeedScale; public float? m_avoidRange; public float? m_height; [YamlMember(Description = "Fishing")] public float? m_hookForce; public float? m_staminaUse; public float? m_escapeStaminaUse; public float? m_escapeMin; public float? m_escapeMax; public float? m_escapeWaitMin; public float? m_escapeWaitMax; public float? m_escapeMaxPerLevel; public float? m_baseHookChance; public int? m_pickupItemStackSize; public float? m_blockChangeDurationMin; public float? m_blockChangeDurationMax; public float? m_collisionFleeTimeout; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_baits; public DropTableRef m_extraDrops; [YamlMember(Description = "Jump")] public float? m_jumpSpeed; public float? m_jumpHeight; public float? m_jumpForwardStrength; public float? m_jumpHeightLand; public float? m_jumpChance; public float? m_jumpOnLandChance; public float? m_jumpOnLandDecay; public float? m_maxJumpDepthOffset; public float? m_jumpFrequencySeconds; public float? m_jumpOnLandRotation; public float? m_waveJumpMultiplier; public float? m_jumpMaxLevel; public EffectListRef m_jumpEffects; public FishRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public FishRef(Fish fish) { Setup(fish); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class BaseItem : Header { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 6)] public ItemDataSharedRef ItemData; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 7)] public VisualRef Visuals; [YamlMember(Order = 8)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public RecipeRef Recipe; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [YamlMember(Order = 9)] public ItemConversionRef[] Conversions; public override void Setup(GameObject prefab, bool isClone = false, string source = "") { base.Setup(prefab, isClone, source); Type = BaseType.Item; Prefab = ((Object)prefab).name; ClonedFrom = source; IsCloned = isClone; SetupItem(prefab); SetupVisuals(prefab); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public override VisualRef GetVisualData() { return Visuals; } public override void CopyFields(Header original) { base.CopyFields(original); if (original is BaseItem baseItem) { if (ItemData != null && baseItem.ItemData != null) { ItemData.ResetTo(baseItem.ItemData); } if (Visuals != null && baseItem.Visuals != null) { Visuals.ResetTo(baseItem.Visuals); } } } protected void SetupItem(GameObject prefab) { ItemDrop val = default(ItemDrop); if (prefab.TryGetComponent(ref val)) { ItemData = new ItemDataSharedRef(val.m_itemData.m_shared); SetupRecipe(val); SetupConversions(val); } } public void SetupConversions(ItemDrop item) { List list = new List(); List allPrefabs = PrefabManager.GetAllPrefabs(); Fermenter val2 = default(Fermenter); CookingStation val4 = default(CookingStation); Smelter val5 = default(Smelter); for (int i = 0; i < allPrefabs.Count; i++) { GameObject val = allPrefabs[i]; if (val.TryGetComponent(ref val2)) { for (int j = 0; j < val2.m_conversion.Count; j++) { ItemConversion val3 = val2.m_conversion[j]; if ((Object)(object)val3.m_from == (Object)(object)item || (Object)(object)val3.m_to == (Object)(object)item) { ItemConversionRef item2 = new ItemConversionRef { m_prefab = ((Object)val2).name, m_type = ConversionType.Fermenter, m_from = ((Object)val3.m_from).name, m_to = ((Object)val3.m_to).name, m_producedItems = val3.m_producedItems }; list.Add(item2); } } } if (val.TryGetComponent(ref val4)) { foreach (ItemConversion item5 in val4.m_conversion) { if ((Object)(object)item5.m_from == (Object)(object)item || (Object)(object)item5.m_to == (Object)(object)item) { ItemConversionRef item3 = new ItemConversionRef { m_type = ConversionType.CookingStation, m_prefab = ((Object)val4).name, m_from = ((Object)item5.m_from).name, m_to = ((Object)item5.m_to).name, m_cookTime = item5.m_cookTime }; list.Add(item3); } } } if (!val.TryGetComponent(ref val5)) { continue; } foreach (ItemConversion item6 in val5.m_conversion) { if ((Object)(object)item6.m_from == (Object)(object)item || (Object)(object)item6.m_to == (Object)(object)item) { ItemConversionRef item4 = new ItemConversionRef { m_type = ConversionType.Smelter, m_prefab = ((Object)val5).name, m_from = ((Object)item6.m_from).name, m_to = ((Object)item6.m_to).name }; list.Add(item4); } } } if (list.Any()) { Conversions = list.ToArray(); } } public void SetupRecipe(ItemDrop item) { if (RecipeManager.TryGetRecipeByItem(((Object)item).name, out var recipe)) { Recipe = new RecipeRef(recipe); } } protected void SetupVisuals(GameObject prefab) { Visuals = new VisualRef(prefab); } public override void Update() { GameObject prefab = PrefabManager.GetPrefab(Prefab); if (!((Object)(object)prefab == (Object)null)) { SaveDefault(prefab); UpdatePrefab(prefab); base.Update(); LoadManager.files.PrefabToUpdate = Prefab; LoadManager.files.Add(this); } } protected virtual void SaveDefault(GameObject prefab) { if (ItemManager.TrySave(prefab, out var item, IsCloned, ClonedFrom)) { LoadManager.originalToModifiedList.Add(item, this); } } protected virtual void UpdatePrefab(GameObject prefab) { UpdateItem(prefab); UpdateVisuals(prefab); UpdateRecipe(prefab); UpdateConversions(prefab); } protected void UpdateItem(GameObject prefab) { if (ItemData != null) { ItemDrop component = prefab.GetComponent(); if (!((Object)(object)component == (Object)null)) { ItemData.UpdateFields(component.m_itemData.m_shared, ((Object)prefab).name, log: true); } } } public void UpdateRecipe(GameObject prefab) { ItemDrop item = default(ItemDrop); if (Recipe == null || !prefab.TryGetComponent(ref item)) { return; } if (RecipeManager.TryGetRecipeByItem(((Object)prefab).name, out var recipe)) { Recipe.UpdateFields(recipe, ((Object)recipe).name, log: true); return; } recipe = ScriptableObject.CreateInstance(); ((Object)recipe).name = "Recipe_" + ((Object)prefab).name; Recipe.UpdateFields(recipe, ((Object)recipe).name, log: true); if ((Object)(object)recipe.m_item == (Object)null) { recipe.m_item = item; } recipe.Register(); } public void UpdateConversions(GameObject prefab) { if (Conversions == null) { return; } MonsterDBPlugin.LogInfo("[" + ((Object)prefab).name + "] updating conversions"); Fermenter val3 = default(Fermenter); Smelter val5 = default(Smelter); CookingStation val = default(CookingStation); for (int i = 0; i < Conversions.Length; i++) { ItemConversionRef itemConversionRef = Conversions[i]; if (itemConversionRef.m_prefab == null || itemConversionRef.m_from == null || itemConversionRef.m_to == null) { continue; } GameObject prefab2 = PrefabManager.GetPrefab(itemConversionRef.m_prefab); if ((Object)(object)prefab2 == (Object)null) { continue; } switch (itemConversionRef.m_type) { case ConversionType.Fermenter: { if (!prefab2.TryGetComponent(ref val3) || !itemConversionRef.TryToFermenterConversion(out var fermenterConversion)) { break; } ItemConversion val4 = val3.m_conversion.Find([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (ItemConversion x) => (Object)(object)x.m_from == (Object)(object)fermenterConversion.m_from && (Object)(object)x.m_to == (Object)(object)fermenterConversion.m_to); if (val4 != null) { val4.m_producedItems = fermenterConversion.m_producedItems; if (ConfigManager.ShouldLogDetails()) { MonsterDBPlugin.LogDebug($"[{((Object)val3).name}] modified conversion: {((Object)val4.m_from).name} produces {((Object)val4.m_to).name} x{val4.m_producedItems}"); } } else { val3.m_conversion.Add(fermenterConversion); if (ConfigManager.ShouldLogDetails()) { MonsterDBPlugin.LogDebug($"[{((Object)val3).name}] added conversion: {((Object)fermenterConversion.m_from).name} produces {((Object)fermenterConversion.m_to).name} x{fermenterConversion.m_producedItems}"); } } break; } case ConversionType.Smelter: { if (!prefab2.TryGetComponent(ref val5) || !itemConversionRef.TryToSmelterConversion(out var smelterConversion)) { break; } ItemConversion val6 = val5.m_conversion.Find([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (ItemConversion x) => (Object)(object)x.m_from == (Object)(object)smelterConversion.m_from && (Object)(object)x.m_to == (Object)(object)smelterConversion.m_to); if (val6 == null) { val5.m_conversion.Add(smelterConversion); if (ConfigManager.ShouldLogDetails()) { MonsterDBPlugin.LogDebug("[" + ((Object)val5).name + "] added conversion: " + ((Object)smelterConversion.m_from).name + " to " + ((Object)smelterConversion.m_to).name); } } break; } case ConversionType.CookingStation: { if (!prefab2.TryGetComponent(ref val) || !itemConversionRef.TryToCookingConversion(out var cookingConversion)) { break; } ItemConversion val2 = val.m_conversion.Find([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (ItemConversion x) => (Object)(object)x.m_from == (Object)(object)cookingConversion.m_from && (Object)(object)x.m_to == (Object)(object)cookingConversion.m_to); if (val2 != null) { val2.m_cookTime = cookingConversion.m_cookTime; if (ConfigManager.ShouldLogDetails()) { MonsterDBPlugin.LogDebug($"[{((Object)val).name}] modified conversion: {((Object)val2.m_from).name} to {((Object)val2.m_to).name} in {val2.m_cookTime}s"); } } else { val.m_conversion.Add(cookingConversion); if (ConfigManager.ShouldLogDetails()) { MonsterDBPlugin.LogDebug($"[{((Object)val).name}] added conversion: {((Object)cookingConversion.m_from).name} to {((Object)cookingConversion.m_to).name} in {cookingConversion.m_cookTime}s"); } } break; } } } } protected void UpdateVisuals(GameObject prefab) { if (Visuals != null) { Visuals.Update(prefab, isInstance: false, isItem: true); } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class ItemManager { [Obsolete] public static void WriteItemYML(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); } else if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { args.Context.LogWarning("Invalid, missing ItemDrop component"); } else { Write(prefab); } } [Obsolete] public static void UpdateItemYML(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); return; } string filePath = Path.Combine(FileManager.ImportFolder, @string + ".yml"); Read(filePath); } [Obsolete] public static void ResetItem(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid prefab"); return; } BaseItem original = LoadManager.GetOriginal(@string); if (original == null) { args.Context.LogWarning("Original data not found"); return; } original.Update(); LoadManager.files.Add(original); LoadManager.UpdateSync(); } [Obsolete] public static List GetResetItemOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : LoadManager.GetOriginalKeys()); if (1 == 0) { } return result; } [Obsolete] public static void CloneItem(ConsoleEventArgs args) { string @string = args.GetString(2); string string2 = args.GetString(3); if (string.IsNullOrEmpty(@string) || string.IsNullOrEmpty(string2)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); } else if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { args.Context.LogWarning("Invalid prefab, missing ItemDrop component"); } else { TryClone(prefab, string2, out var _, write: true, "", args.Context); } } [Obsolete] public static void SearchItem(ConsoleEventArgs args) { string @string = args.GetString(2); List list = PrefabManager.SearchCache(@string); for (int i = 0; i < list.Count; i++) { args.Context.AddString("- " + list[i]); } } [Obsolete] public static List GetSearchItemOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : PrefabManager.SearchCache("")); if (1 == 0) { } return result; } public static void CreateItem(ConsoleEventArgs args) { string @string = args.GetString(2); string string2 = args.GetString(3); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Specify prefab"); return; } if (string.IsNullOrEmpty(string2)) { args.Context.LogWarning("Specify new prefab name"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); return; } if (Object.op_Implicit((Object)(object)prefab.GetComponent())) { args.Context.LogWarning("Cannot convert creature into an item"); return; } GameObject clone; if (Object.op_Implicit((Object)(object)prefab.GetComponent())) { if (!TryClone(prefab, string2, out clone, write: true, "", args.Context)) { args.Context.LogWarning("Failed to clone item: " + ((Object)prefab).name); } return; } if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { args.Context.LogWarning("Invalid prefab, missing ZNetView"); return; } Collider componentInChildren = prefab.GetComponentInChildren(); if ((Object)(object)componentInChildren == (Object)null) { args.Context.LogWarning("Invalid prefab, missing colliders"); } else if (!TryCreateItem(prefab, string2, out clone, write: true, "", args.Context)) { args.Context.LogWarning("Failed to create item for " + ((Object)prefab).name); } } public static bool TrySave(GameObject prefab, out BaseItem item, bool isClone = false, string source = "") { item = LoadManager.GetOriginal(((Object)prefab).name); if (item != null) { return true; } if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { return false; } item = new BaseItem(); item.Setup(prefab, isClone, source); LoadManager.originals.Add(((Object)prefab).name, item); return true; } public static bool Write(GameObject prefab, bool isClone = false, string clonedFrom = "", string dirPath = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (string.IsNullOrEmpty(dirPath)) { dirPath = FileManager.ExportFolder; } string text = Path.Combine(dirPath, ((Object)prefab).name + ".yml"); if (!TrySave(prefab, out var item, isClone, clonedFrom)) { return false; } string contents = ConfigManager.Serialize(item); File.WriteAllText(text, contents); MonsterDBPlugin.LogInfo("Saved " + ((Object)prefab).name + " to: " + text); context?.LogInfo("Exported Item " + ((Object)prefab).name); context?.LogInfo(text.RemoveRootPath()); ItemDrop val = default(ItemDrop); if (prefab.TryGetComponent(ref val)) { SharedData shared = val.m_itemData.m_shared; if ((Object)(object)shared.m_attack.m_attackProjectile != (Object)null) { bool isClone2 = false; string source = ""; if (CloneManager.clones.TryGetValue(((Object)shared.m_attack.m_attackProjectile).name, out var value)) { isClone2 = true; source = value.SourceName; } ProjectileManager.Write(shared.m_attack.m_attackProjectile, isClone2, source, dirPath, context); } if ((Object)(object)shared.m_secondaryAttack.m_attackProjectile != (Object)null) { bool isClone3 = false; string source2 = ""; if (CloneManager.clones.TryGetValue(((Object)shared.m_secondaryAttack.m_attackProjectile).name, out var value2)) { isClone3 = true; source2 = value2.SourceName; } ProjectileManager.Write(shared.m_secondaryAttack.m_attackProjectile, isClone3, source2, dirPath, context); } } return true; } private static void Read(string filePath) { if (!File.Exists(filePath)) { return; } string data = File.ReadAllText(filePath); try { Header header = ConfigManager.Deserialize
(data); if (header.Type == BaseType.Item) { BaseItem baseItem = ConfigManager.Deserialize(data); baseItem.Update(); LoadManager.files.Add(baseItem); LoadManager.UpdateSync(); } } catch { MonsterDBPlugin.LogWarning("Failed to deserialize: " + Path.GetFileName(filePath)); } } public static bool TryClone(GameObject source, string cloneName, out GameObject clone, bool write = true, string dirPath = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (CloneManager.prefabs.TryGetValue(cloneName, out clone)) { return true; } if (!Object.op_Implicit((Object)(object)source.GetComponent())) { return false; } Clone clone2 = new Clone(source, cloneName); clone2.OnCreated += delegate(GameObject p) { ItemDrop component = p.GetComponent(); if ((Object)(object)component != (Object)null) { SharedData shared = component.m_itemData.m_shared; GameObject attackProjectile = shared.m_attack.m_attackProjectile; if ((Object)(object)attackProjectile != (Object)null) { string cloneName2 = "MDB_" + cloneName + "_" + ((Object)attackProjectile).name; if (ProjectileManager.TryClone(attackProjectile, cloneName2, out var clone3, write: false, dirPath, context)) { shared.m_attack.m_attackProjectile = clone3; } } } MonsterDBPlugin.LogDebug("Cloned " + ((Object)source).name + " as " + cloneName); if (write) { Write(p, isClone: true, ((Object)source).name, dirPath, context); } }; clone = clone2.Create(); context?.LogInfo("Cloned " + ((Object)source).name + " as " + cloneName); return (Object)(object)clone != (Object)null; } public static bool TryCreateItem(GameObject source, string cloneName, out GameObject clone, bool write = true, string dirPath = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (CloneManager.prefabs.TryGetValue(cloneName, out clone)) { return true; } if (Object.op_Implicit((Object)(object)source.GetComponent()) || !Object.op_Implicit((Object)(object)source.GetComponent())) { return false; } Clone clone2 = new Clone(source, cloneName); clone2.OnCreated += delegate(GameObject p) { //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_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Expected O, but got Unknown //IL_00f8: 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_0103: Expected O, but got Unknown //IL_0108: Expected O, but got Unknown //IL_010d: Expected O, but got Unknown MonoBehaviour[] components = p.GetComponents(); foreach (MonoBehaviour val in components) { if (!(val is ZNetView)) { Object.Destroy((Object)(object)val); } } ItemDrop val2 = p.AddComponent(); GameObject prefab = PrefabManager.GetPrefab("AsksvinEgg"); ItemDrop val3 = default(ItemDrop); if (!((Object)(object)prefab == (Object)null) && prefab.TryGetComponent(ref val3)) { Sprite[] icons = val3.m_itemData.m_shared.m_icons; Transform val4 = Utils.FindChild(prefab.transform, "Not Growing", (IterativeSearchType)0); if ((Object)(object)val4 != (Object)null) { Transform val5 = Object.Instantiate(val4, p.transform); ((Object)val5).name = "Not Growing"; } val2.m_itemData = new ItemData { m_shared = new SharedData { m_name = cloneName, m_icons = icons, m_attack = new Attack(), m_secondaryAttack = new Attack() } }; ZSyncTransform val6 = default(ZSyncTransform); if (!p.TryGetComponent(ref val6)) { val6 = p.AddComponent(); val6.m_syncPosition = true; val6.m_syncRotation = true; } Rigidbody val7 = default(Rigidbody); if (!p.TryGetComponent(ref val7)) { val7 = p.AddComponent(); val7.mass = 1f; val7.linearDamping = 0f; val7.angularDamping = 0.05f; val7.useGravity = true; val7.isKinematic = false; val7.interpolation = (RigidbodyInterpolation)0; val7.collisionDetectionMode = (CollisionDetectionMode)1; } Collider[] componentsInChildren = p.GetComponentsInChildren(); int layer = LayerMask.NameToLayer("item"); foreach (Collider val8 in componentsInChildren) { ((Component)val8).gameObject.layer = layer; } MonsterDBPlugin.LogDebug("Cloned " + ((Object)source).name + " as " + cloneName); if (write) { Write(p, isClone: true, ((Object)source).name, dirPath, context); } } }; clone = clone2.Create(); return (Object)(object)clone != (Object)null; } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class AttackRef : Reference { public AttackType? m_attackType; public string m_attackAnimation; public string m_chargeAnimationBool; public int? m_attackRandomAnimations; public int? m_attackChainLevels; public bool? m_loopingAttack; public bool? m_consumeItem; public bool? m_hitTerrain; public bool? m_isHomeItem; public float? m_attackStamina; public float? m_attackAdrenaline; public float? m_attackUseAdrenaline; public float? m_attackEitr; public float? m_attackHealth; public float? m_attackHealthPercentage; public bool? m_attackHealthLowBlockUse; public float? m_attackHealthReturnHit; public bool? m_attackKillsSelf; public float? m_speedFactor; public float? m_speedFactorRotation; public float? m_attackStartNoise; public float? m_attackHitNoise; public float? m_damageMultiplier; [YamlMember(Description = "For each missing health point, increase damage this much.")] public float? m_damageMultiplierPerMissingHP; [YamlMember(Description = "At 100% missing HP the damage will increase by this much, and gradually inbetween.")] public float? m_damageMultiplierByTotalHealthMissing; [YamlMember(Description = "For each missing health point, return one stamina point.")] public float? m_staminaReturnPerMissingHP; public float? m_forceMultiplier; public float? m_staggerMultiplier; public float? m_recoilPushback; public int? m_selfDamage; public string m_attackOriginJoint; public float? m_attackRange; public float? m_attackHeight; public float? m_attackHeightChar1; public float? m_attackHeightChar2; public float? m_attackOffset; public string m_spawnOnTrigger; public bool? m_toggleFlying; public bool? m_attach; public bool? m_cantUseInDungeon; [YamlMember(Description = "Loading")] public bool? m_requiresReload; public string m_reloadAnimation; public float? m_reloadTime; [YamlMember(Description = "Draw")] public bool? m_bowDraw; public float? m_drawDurationMin; public float? m_drawStaminaDrain; public float? m_drawEitrDrain; public string m_drawAnimationState; [YamlMember(Description = "Melee/AOE")] public float? m_attackAngle; public float? m_attackRayWidth; public float? m_attackRayWidthCharExtra; public float? m_maxYAngle; public bool? m_lowerDamagePerHit; [YamlMember(Alias = "m_hitPointType")] public HitPointType? m_hitPointtype; public bool? m_hitThroughWalls; public bool? m_multiHit; public bool? m_pickaxeSpecial; public float? m_lastChainDamageMultiplier; public DestructibleType? m_resetChainIfHit; public string m_spawnOnHit; public float? m_spawnOnHitChance; public float? m_raiseSkillAmount; public DestructibleType? m_skillHitType; public SkillType? m_specialHitSkill; [YamlMember(Description = "Projectile")] public string m_attackProjectile; public float? m_projectileVel; public float? m_projectileVelMin; [YamlMember(Description = "When not using Draw, randomize velocity between Velocity and Velocity Min")] public bool? m_randomVelocity; public float? m_projectileAccuracy; public float? m_projectileAccuracyMin; public bool? m_circularProjectileLaunch; public bool? m_distributeProjectilesAroundCircle; public bool? m_skillAccuracy; public bool? m_useCharacterFacing; public bool? m_useCharacterFacingYAim; public float? m_launchAngle; public int? m_projectiles; public int? m_projectileBursts; public float? m_burstInterval; public bool? m_destroyPreviousProjectile; public bool? m_perBurstResourceUsage; public bool? m_harvest; public float? m_harvestRadius; public float? m_harvestRadiusMaxLevel; [YamlMember(Description = "Attack Effects")] public EffectListRef m_hitEffect; public EffectListRef m_hitTerrainEffect; public EffectListRef m_startEffect; public EffectListRef m_triggerEffect; public EffectListRef m_trailStartEffect; public EffectListRef m_burstEffect; } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public sealed class ItemDataSharedRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] public string m_prefab = ""; [Condition(icon = true)] public string m_name; [Condition(icon = true)] public string m_subtitle; [Condition(icon = true)] public ItemType? m_itemType; [Condition(icon = true)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public string[] m_icons; [Condition(icon = true)] public ItemType? m_attachOverride; [Condition(icon = true)] public string m_description; [Condition(icon = true)] public int? m_maxStackSize; [Condition(icon = true)] public bool? m_autoStack; [Condition(icon = true)] public int? m_maxQuality; [Condition(icon = true)] public float? m_scaleByQuality; [Condition(icon = true)] public float? m_weight; [Condition(icon = true)] public float? m_scaleWeightByQuality; [Condition(icon = true)] public int? m_value; [Condition(icon = true)] public bool? m_teleportable; [Condition(icon = true)] public bool? m_questItem; [Condition(icon = true)] public float? m_equipDuration; [Condition(icon = true)] public int? m_variants; [YamlMember(Description = "Set Settings")] [Condition(icon = true)] public int? m_setSize; [Condition(icon = true)] public string m_setStatusEffect; [Condition(icon = true)] public string m_equipStatusEffect; [YamlMember(Description = "Modifiers")] [Condition(icon = true)] public float? m_eitrRegenModifier; [Condition(icon = true)] public float? m_movementModifier; [Condition(icon = true)] public float? m_homeItemsStaminaModifier; [Condition(icon = true)] public float? m_heatResistanceModifier; [Condition(icon = true)] public float? m_jumpStaminaModifier; [Condition(icon = true)] public float? m_attackStaminaModifier; [Condition(icon = true)] public float? m_blockStaminaModifier; [Condition(icon = true)] public float? m_dodgeStaminaModifier; [Condition(icon = true)] public float? m_swimStaminaModifier; [Condition(icon = true)] public float? m_sneakStaminaModifier; [Condition(icon = true)] public float? m_runStaminaModifier; [YamlMember(Description = "Food Settings")] [Condition(icon = true)] public float? m_food; [Condition(icon = true)] public float? m_foodStamina; [Condition(icon = true)] public float? m_foodEitr; [Condition(icon = true)] public float m_foodBurnTime; [Condition(icon = true)] public float? m_foodRegen; [Condition(icon = true)] public bool? m_isDrink; [Condition(icon = true)] [YamlMember(Description = "Armor Settings")] public string m_armorMaterial; [Condition(icon = true)] public HelmetHairType? m_helmetHideHair; [Condition(icon = true)] public HelmetHairType? m_helmetHideBeard; [Condition(icon = true)] public float? m_armor; [Condition(icon = true)] public float? m_armorPerLevel; [Condition(icon = true)] public List m_damageModifiers; [Condition(icon = true)] [YamlMember(Description = "Shield Settings")] public float? m_blockPower; [Condition(icon = true)] public float? m_blockPowerPerLevel; [Condition(icon = true)] public float? m_deflectionForce; [Condition(icon = true)] public float? m_deflectionForcePerLevel; [Condition(icon = true)] public float? m_timedBlockBonus; [Condition(icon = true)] public string m_perfectBlockStatusEffect; [Condition(icon = true)] public bool? m_buildBlockCharges; [Condition(icon = true)] public int? m_maxBlockCharges; [Condition(icon = true)] public float? m_blockChargeDecayTime; [Condition(icon = true)] public float? m_blockChargeBlockingDecayMult; [Condition(icon = true)] public EffectListRef m_blockChargeEffects; [Condition(icon = true)] public float? m_maxAdrenaline; [Condition(icon = true)] public string m_fullAdrenalineSE; [Condition(icon = true)] public float? m_blockAdrenaline; [Condition(icon = true)] public float? m_perfectBlockAdrenaline; [YamlMember(Description = "Weapon")] public AnimationState? m_animationState; [Condition(icon = true)] public SkillType? m_skillType; public int? m_toolTier; public DamageTypes? m_damages; public float? m_attackForce; public float? m_backstabBonus; public bool? m_dodgeable; public bool? m_blockable; [Condition] public bool? m_tamedOnly; public string m_attackStatusEffect; public float? m_attackStatusEffectChance; public string m_spawnOnHit; public string m_spawnOnHitTerrain; public string m_ammoType; public AttackRef m_attack; public AttackRef m_secondaryAttack; [Condition(icon = true)] public float? m_useDurability; [Condition(icon = true)] public bool? m_destroyBroken; [Condition(icon = true)] public bool? m_canBeRepaired; [Condition(icon = true)] public float? m_maxDurability; [Condition(icon = true)] public float? m_durabilityPerLevel; [Condition(icon = true)] public float m_useDurabilityDrain; [YamlMember(Description = "AI behaviour")] public float? m_aiAttackRange; public float? m_aiAttackRangeMin; public float? m_aiAttackInterval; public float? m_aiAttackMaxAngle; public bool? m_aiInvertAngleCheck; public bool? m_aiWhenFlying; public float? m_aiWhenFlyingAltitudeMin; public float? m_aiWhenFlyingAltitudeMax; public bool? m_aiWhenWalking; public bool? m_aiWhenSwiming; public bool? m_aiPrioritized; public bool? m_aiInDungeonOnly; public bool? m_aiInMistOnly; public float? m_aiMaxHealthPercentage; public float? m_aiMinHealthPercentage; public AiTarget? m_aiTargetType; [YamlMember(Description = "Item Effects")] public EffectListRef m_hitEffect; public EffectListRef m_hitTerrainEffect; public EffectListRef m_blockEffect; public EffectListRef m_startEffect; public EffectListRef m_holdStartEffect; public EffectListRef m_triggerEffect; public EffectListRef m_trailStartEffect; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] private static Dictionary _cachedArmorMaterials = new Dictionary(); public ItemDataSharedRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public ItemDataSharedRef(SharedData sharedData) { Setup(sharedData); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public override bool ShouldSetupField<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] V>(FieldInfo targetField, V source) { object obj = source; SharedData val = (SharedData)((obj is SharedData) ? obj : null); if (val != null) { return targetField.GetCustomAttribute()?.ShouldSetupField(val) ?? true; } return true; } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] protected override void UpdateMaterial<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, string materialName, string targetName, bool log) { if (_cachedArmorMaterials.TryGetValue(materialName, out var value)) { targetField.SetValue(target, value); } else { IEnumerable enumerable = from p in PrefabManager.GetAllPrefabs() select p.GetComponent().m_itemData.m_shared.m_armorMaterial into m where (Object)(object)m != (Object)null select m; foreach (Material item in enumerable) { _cachedArmorMaterials[((Object)item).name] = item; if (((Object)item).name == materialName) { targetField.SetValue(target, item); break; } } } object value2 = targetField.GetValue(target); string text = "null"; Material val = (Material)((value2 is Material) ? value2 : null); if (val != null) { text = ((Object)val).name; } if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + text); } } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class LocalizationManager { private const string FolderName = "Localizations"; private static readonly string FolderPath; private static Dictionary localizations; private static readonly CustomSyncedValue sync; private static readonly ConfigEntry _fileWatcherEnabled; static LocalizationManager() { //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Expected O, but got Unknown FolderPath = Path.Combine(ConfigManager.DirectoryPath, "Localizations"); localizations = new Dictionary(); sync = new CustomSyncedValue(ConfigManager.ConfigSync, "MonsterDB.ServerSync.Localization", ""); sync.ValueChanged += OnSyncChange; _fileWatcherEnabled = ConfigManager.config("File Watcher", "Localizations", Toggle.On, "If on, YML files under Localizations folder will trigger update on changed, created, or renamed", synchronizedSetting: false); Harmony harmony = MonsterDBPlugin.harmony; harmony.Patch((MethodBase)AccessTools.Method(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(LocalizationManager), "Patch_Localization_LoadCSV", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } private static bool IsFileWatcherEnabled() { return _fileWatcherEnabled.Value == Toggle.On; } private static List ReadAssemblyFile(string resourceName, string folder) { Assembly executingAssembly = Assembly.GetExecutingAssembly(); string name = "MonsterDB." + folder + "." + resourceName; using Stream stream = executingAssembly.GetManifestResourceStream(name); if (stream == null) { throw new FileNotFoundException("Embedded resource '" + resourceName + "' not found in assembly '" + executingAssembly.FullName + "'."); } using StreamReader streamReader = new StreamReader(stream); List list = new List(); while (!streamReader.EndOfStream) { list.Add(streamReader.ReadLine() ?? string.Empty); } return list; } public static void Start() { if (!Directory.Exists(FolderPath)) { Directory.CreateDirectory(FolderPath); } string[] files = Directory.GetFiles(FolderPath, "*.yml", SearchOption.AllDirectories); if (files.Length == 0) { string path = Path.Combine(FolderPath, "English.yml"); List list = ReadAssemblyFile("English.yml", "translations"); File.WriteAllLines(path, list); localizations["English"] = list.ToArray(); return; } foreach (string path2 in files) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path2); string[] collection = File.ReadAllLines(path2); List list2 = new List(); if (localizations.TryGetValue(fileNameWithoutExtension, out var value)) { list2.AddRange(value); list2.AddRange(collection); } else { list2.AddRange(collection); } localizations[fileNameWithoutExtension] = list2.ToArray(); MonsterDBPlugin.LogInfo("Loaded " + fileNameWithoutExtension + " localizations"); } } public static void Register(string filePath) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath); string[] array = fileNameWithoutExtension.Split(new char[1] { '.' }); if (array.Length == 2) { string key = array[1]; string[] collection = File.ReadAllLines(filePath); List list = new List(); if (localizations.TryGetValue(key, out var value)) { list.AddRange(value); list.AddRange(collection); } else { list.AddRange(collection); } localizations[key] = list.ToArray(); } } public static void Init(ZNet net) { if (net.IsServer()) { SetupFileWatcher(); UpdateSync(); } } private static void SetupFileWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(FolderPath, "*.yml"); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private static void Patch_Localization_LoadCSV(Localization __instance, string language) { if (localizations.TryGetValue(language, out var value)) { ParseLines(__instance, value); } } private static void ParseLines(Localization instance, string[] lines) { foreach (string text in lines) { if (!text.StartsWith("#") && !string.IsNullOrEmpty(text)) { string[] array = text.Split(new char[1] { ':' }); if (array.Length >= 2) { string text2 = array[0].Trim(); string text3 = array[1].Trim(); text3 = instance.StripCitations(text3); instance.AddWord(text2, text3); } } } } public static void UpdateWords(string filePath) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePath); string[] array = fileNameWithoutExtension.Split(new char[1] { '.' }); if (array.Length != 2) { return; } string key = array[1]; string[] array2 = File.ReadAllLines(filePath); Dictionary dictionary = new Dictionary(); if (localizations.TryGetValue(key, out var value)) { foreach (string text in value) { if (!string.IsNullOrEmpty(text) && !text.StartsWith("$")) { string[] array3 = text.Split(new char[1] { ':' }); if (array3.Length >= 2) { string key2 = array3[0].Trim(); string value2 = array3[1].Trim(); dictionary[key2] = value2; } } } } foreach (string text2 in array2) { if (!string.IsNullOrEmpty(text2) && !text2.StartsWith("$")) { string[] array4 = text2.Split(new char[1] { ':' }); if (array4.Length >= 2) { string key3 = array4[0].Trim(); string value3 = array4[1].Trim(); dictionary[key3] = value3; } } } string[] value4 = dictionary.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (KeyValuePair f) => string.Join(":", f.Key, f.Value)).ToArray(); localizations[key] = value4; Update(); } public static void AddWords(string language, Dictionary translations) { Dictionary dictionary = new Dictionary(); if (localizations.TryGetValue(language, out var value)) { foreach (string text in value) { if (!string.IsNullOrEmpty(text) && !text.StartsWith("$")) { string[] array = text.Split(new char[1] { ':' }); if (array.Length >= 2) { string key = array[0].Trim(); string value2 = array[1].Trim(); dictionary[key] = value2; } } } } foreach (KeyValuePair translation in translations) { dictionary[translation.Key] = translation.Value; } string[] value3 = dictionary.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (KeyValuePair f) => string.Join(":", f.Key, f.Value)).ToArray(); localizations[language] = value3; } public static void AddWord(string language, string key, string value, bool replace = true) { if (!localizations.TryGetValue(language, out var value2)) { localizations[language] = new string[1] { string.Join(":", key, value) }; } else { Dictionary dictionary = new Dictionary(); foreach (string text in value2) { if (!string.IsNullOrEmpty(text) && !text.StartsWith("#")) { string[] array = text.Split(new char[1] { ':' }); if (array.Length >= 2) { string key2 = array[0].Trim(); string value3 = array[1].Trim(); dictionary[key2] = value3; } } } if (replace) { dictionary[key] = value; } else if (!dictionary.ContainsKey(key)) { dictionary.Add(key, value); } string[] value4 = dictionary.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (KeyValuePair f) => string.Join(":", f.Key, f.Value)).ToArray(); localizations[language] = value4; } Update(); } private static void ReadConfigValues(object sender, FileSystemEventArgs e) { if (!IsFileWatcherEnabled() || !Object.op_Implicit((Object)(object)ZNet.instance) || !ZNet.instance.IsServer() || Localization.instance == null) { return; } string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(e.FullPath); string[] array = File.ReadAllLines(e.FullPath); Dictionary dictionary = new Dictionary(); if (localizations.TryGetValue(fileNameWithoutExtension, out var value)) { foreach (string text in value) { if (!string.IsNullOrEmpty(text) && !text.StartsWith("$")) { string[] array2 = text.Split(new char[1] { ':' }); if (array2.Length >= 2) { string key = array2[0].Trim(); string value2 = array2[1].Trim(); dictionary[key] = value2; } } } } foreach (string text2 in array) { if (!string.IsNullOrEmpty(text2) && !text2.StartsWith("$")) { string[] array3 = text2.Split(new char[1] { ':' }); if (array3.Length >= 2) { string key2 = array3[0].Trim(); string value3 = array3[1].Trim(); dictionary[key2] = value3; } } } string[] value4 = dictionary.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (KeyValuePair f) => string.Join(":", f.Key, f.Value)).ToArray(); localizations[fileNameWithoutExtension] = value4; Update(); } private static void Update() { UpdateSync(); if (Localization.instance != null) { string selectedLanguage = Localization.instance.GetSelectedLanguage(); if (localizations.TryGetValue(selectedLanguage, out var value)) { ParseLines(Localization.instance, value); Localization.instance.m_cache.EvictAll(); MonsterDBPlugin.LogDebug("Updated " + selectedLanguage + " localizations"); } } } private static void OnSyncChange() { if (!Object.op_Implicit((Object)(object)ZNet.instance) || ZNet.instance.IsServer() || string.IsNullOrEmpty(sync.Value)) { return; } try { Dictionary dictionary = ConfigManager.Deserialize>(sync.Value); localizations = dictionary; Update(); } catch { MonsterDBPlugin.LogWarning("Failed to deserialize server localization files"); } } private static void UpdateSync() { if (Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer()) { sync.Value = ConfigManager.Serialize(localizations); } } } public class Persistent : Attribute { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [PublicAPI] public static class PrefabManager { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] internal static ZNetScene _ZNetScene; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] internal static ObjectDB _ObjectDB; internal static readonly Dictionary _prefabs; internal static List PrefabsToRegister; static PrefabManager() { _prefabs = new Dictionary(); PrefabsToRegister = new List(); } public static void Start() { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_0098: Expected O, but got Unknown //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Expected O, but got Unknown //IL_00ee: Expected O, but got Unknown Harmony harmony = MonsterDBPlugin.harmony; harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PrefabManager), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNetScene), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PrefabManager), "Patch_ZNetScene_Awake", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LoadManager), "Start", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PrefabManager), "Patch_ObjectDB_Awake", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(RecipeManager), "MapRecipes", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static void AddToCache(GameObject go) { if (!((Object)(object)go == (Object)null) && !_prefabs.ContainsKey(((Object)go).name) && ((Object)go).GetInstanceID() >= 0) { _prefabs.Add(((Object)go).name, go); } } internal static List GetAllPrefabNames() { return _prefabs.Keys.ToList(); } internal static List GetAllPrefabNames<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>() where T : MonoBehaviour { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { return (from x in ZNetScene.instance.m_prefabs where (Object)(object)x != (Object)null where Object.op_Implicit((Object)(object)x.GetComponent()) select ((Object)x).name).ToList(); } if ((Object)(object)_ZNetScene != (Object)null) { return (from x in _ZNetScene.m_prefabs where (Object)(object)x != (Object)null where Object.op_Implicit((Object)(object)x.GetComponent()) select ((Object)x).name).ToList(); } return new List(); } internal static List GetAllPrefabs<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>() where T : MonoBehaviour { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { return (from x in ZNetScene.instance.m_prefabs where (Object)(object)x != (Object)null where Object.op_Implicit((Object)(object)x.GetComponent()) select x).ToList(); } if ((Object)(object)_ZNetScene != (Object)null) { return (from x in _ZNetScene.m_prefabs where (Object)(object)x != (Object)null where Object.op_Implicit((Object)(object)x.GetComponent()) select x).ToList(); } return new List(); } [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] internal static GameObject GetPrefab(string prefabName) { GameObject value; if ((Object)(object)ZNetScene.instance != (Object)null) { value = ZNetScene.instance.GetPrefab(prefabName); if ((Object)(object)value != (Object)null) { return value; } } if ((Object)(object)_ZNetScene != (Object)null) { value = _ZNetScene.m_prefabs.Find([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (GameObject p) => ((Object)p).name == prefabName); if ((Object)(object)value != (Object)null) { return value; } } if (CloneManager.prefabs.TryGetValue(prefabName, out value)) { return value; } if (AudioManager.clips.TryGetValue(prefabName, out var value2) && (Object)(object)value2.sfx != (Object)null) { return value2.sfx; } if (_prefabs.TryGetValue(prefabName, out value)) { return value; } CachePrefabs(); if (_prefabs.TryGetValue(prefabName, out value)) { return value; } MonsterDBPlugin.LogWarning("Prefab '" + prefabName + "' not found"); return null; } private static void CachePrefabs() { GameObject[] array = Resources.FindObjectsOfTypeAll(); foreach (GameObject val in array) { if (!((Object)(object)val == (Object)null) && ((Object)val).GetInstanceID() > 0 && !_prefabs.ContainsKey(((Object)val).name)) { _prefabs.Add(((Object)val).name, val); } } } public static List SearchCache<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>(string query) where T : MonoBehaviour { return (from x in _prefabs.Values where (Object)(object)x != (Object)null where Object.op_Implicit((Object)(object)x.GetComponent()) where ((Object)x).name.ToLower().Contains(query.ToLower()) select ((Object)x).name).ToList(); } [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public static StatusEffect GetStatusEffect(string name) { if (Object.op_Implicit((Object)(object)ObjectDB.instance)) { return ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode(name)); } if ((Object)(object)_ObjectDB != (Object)null) { return ((IEnumerable)_ObjectDB.m_StatusEffects).FirstOrDefault((Func)([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (StatusEffect x) => ((Object)x).name == name)); } return null; } public static void Register(this ZNetScene scene, GameObject prefab) { if (!scene.m_prefabs.Contains(prefab) && Object.op_Implicit((Object)(object)prefab.GetComponent())) { scene.m_prefabs.Add(prefab); scene.m_namedPrefabs[StringExtensionMethods.GetStableHashCode(((Object)prefab).name)] = prefab; } } public static void Register(this ObjectDB db, GameObject prefab) { if (!db.m_items.Contains(prefab) && Object.op_Implicit((Object)(object)prefab.GetComponent())) { db.m_items.Add(prefab); db.m_itemByHash[StringExtensionMethods.GetStableHashCode(((Object)prefab).name)] = prefab; } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public static void RegisterPrefab(GameObject prefab) { if (!((Object)(object)prefab == (Object)null)) { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { ZNetScene.instance.Register(prefab); } if (Object.op_Implicit((Object)(object)ObjectDB.instance)) { ObjectDB.instance.Register(prefab); } PrefabsToRegister.Add(prefab); } } [HarmonyPriority(700)] internal static void Patch_ZNetScene_Awake(ZNetScene __instance) { foreach (GameObject item in PrefabsToRegister) { if (!__instance.m_prefabs.Contains(item) && Object.op_Implicit((Object)(object)item.GetComponent())) { __instance.m_prefabs.Add(item); } } } internal static void Patch_ObjectDB_Awake(ObjectDB __instance) { foreach (GameObject item in PrefabsToRegister) { if (!__instance.m_items.Contains(item) && Object.op_Implicit((Object)(object)item.GetComponent())) { __instance.m_items.Add(item); } } } [HarmonyPriority(700)] internal static void Patch_FejdStartup(FejdStartup __instance) { _ZNetScene = __instance.m_objectDBPrefab.GetComponent(); _ObjectDB = __instance.m_objectDBPrefab.GetComponent(); RecipeManager.MapRecipes(_ObjectDB); ShaderRef.CacheShaders(); VultureOverride.Setup(); foreach (Clone value in CloneManager.clones.Values) { value.Create(); } ConfigManager.SetupWatcher(); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class BaseProjectile : Header { [YamlMember(Order = 6)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public ProjectileRef ProjectileData; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 7)] public TeleportAbilityRef TeleportAbility; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 8)] public TriggerSpawnAbilityRef TriggerSpawnAbility; [YamlMember(Order = 9)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public VisualRef Visuals; public override void Setup(GameObject prefab, bool isClone = false, string source = "") { base.Setup(prefab, isClone, source); Type = BaseType.Projectile; Prefab = ((Object)prefab).name; ClonedFrom = source; IsCloned = isClone; SetupProjectile(prefab); SetupTeleportAbility(prefab); SetupVisuals(prefab); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public override VisualRef GetVisualData() { return Visuals; } public override void CopyFields(Header original) { base.CopyFields(original); if (original is BaseProjectile baseProjectile) { if (ProjectileData != null && baseProjectile.ProjectileData != null) { ProjectileData.ResetTo(baseProjectile.ProjectileData); } if (TeleportAbility != null && baseProjectile.TeleportAbility != null) { TeleportAbility.ResetTo(baseProjectile.TeleportAbility); } if (TriggerSpawnAbility != null && baseProjectile.TriggerSpawnAbility != null) { TriggerSpawnAbility.ResetTo(baseProjectile.TriggerSpawnAbility); } if (Visuals != null && baseProjectile.Visuals != null) { Visuals.ResetTo(baseProjectile.Visuals); } } } protected virtual void SetupTeleportAbility(GameObject prefab) { TeleportAbility ability = default(TeleportAbility); if (prefab.TryGetComponent(ref ability)) { TeleportAbility = new TeleportAbilityRef(ability); } } protected virtual void SetupTriggerSpawnAbility(GameObject prefab) { TriggerSpawnAbility ability = default(TriggerSpawnAbility); if (prefab.TryGetComponent(ref ability)) { TriggerSpawnAbility = new TriggerSpawnAbilityRef(ability); } } protected virtual void SetupProjectile(GameObject prefab) { Projectile projectile = default(Projectile); if (prefab.TryGetComponent(ref projectile)) { ProjectileData = new ProjectileRef(projectile); } } protected virtual void SetupVisuals(GameObject prefab) { Visuals = new VisualRef(prefab); } public override void Update() { GameObject prefab = PrefabManager.GetPrefab(Prefab); if (!((Object)(object)prefab == (Object)null)) { if (ProjectileManager.TrySave(prefab, out var data, IsCloned, ClonedFrom)) { LoadManager.originalToModifiedList.Add(data, this); } UpdatePrefab(prefab); base.Update(); LoadManager.files.PrefabToUpdate = Prefab; LoadManager.files.Add(this); } } protected virtual void UpdatePrefab(GameObject prefab) { UpdateVisuals(prefab); UpdateProjectile(prefab); UpdateTeleportAbility(prefab); UpdateTriggerSpawnAbility(prefab); } protected void UpdateTriggerSpawnAbility(GameObject prefab) { TriggerSpawnAbility val = default(TriggerSpawnAbility); if (TriggerSpawnAbility != null && TriggerSpawnAbility.m_range.HasValue && prefab.TryGetComponent(ref val)) { val.m_range = TriggerSpawnAbility.m_range.Value; if (ConfigManager.ShouldLogDetails()) { MonsterDBPlugin.LogDebug($"[{((Object)prefab).name}] TriggerSpawnAbility.m_range: {val.m_range}"); } } } protected void UpdateTeleportAbility(GameObject prefab) { TeleportAbility ta = default(TeleportAbility); if (TeleportAbility != null && prefab.TryGetComponent(ref ta)) { TeleportAbility.Update(ta, ((Object)prefab).name); } } protected void UpdateProjectile(GameObject prefab) { Projectile target = default(Projectile); if (ProjectileData != null && prefab.TryGetComponent(ref target)) { ProjectileData.UpdateFields(target, ((Object)prefab).name, log: true); } } protected virtual void UpdateVisuals(GameObject prefab) { if (Visuals != null) { Visuals.Update(prefab, isInstance: false, isItem: false); } } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class ProjectileManager { [Obsolete] public static void WriteProjectileYML(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); } else if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { args.Context.LogWarning("Invalid, missing projectile component"); } else { Write(prefab, isClone: false, "", "", args.Context); } } [Obsolete] public static List GetProjectileOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : PrefabManager.GetAllPrefabNames()); if (1 == 0) { } return result; } [Obsolete] public static void CloneProjectile(ConsoleEventArgs args) { string @string = args.GetString(2); string string2 = args.GetString(3); if (string.IsNullOrEmpty(@string) || string.IsNullOrEmpty(string2)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); } else { TryClone(prefab, string2, out var _, write: true, "", args.Context); } } public static bool TrySave(GameObject prefab, out BaseProjectile data, bool isClone = false, string source = "") { data = LoadManager.GetOriginal(((Object)prefab).name); if (data != null) { return true; } data = new BaseProjectile(); data.Setup(prefab, isClone, source); return true; } public static bool Write(GameObject prefab, bool isClone = false, string source = "", string dirPath = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (!TrySave(prefab, out var data, isClone, source)) { return false; } if (string.IsNullOrEmpty(dirPath)) { dirPath = FileManager.ExportFolder; } string text = Path.Combine(dirPath, ((Object)prefab).name + ".yml"); string contents = ConfigManager.Serialize(data); File.WriteAllText(text, contents); MonsterDBPlugin.LogInfo("Saved " + ((Object)prefab).name + " to: " + text); context?.LogInfo("Exported Projectile " + ((Object)prefab).name); context?.LogInfo(text.RemoveRootPath()); Projectile val = default(Projectile); if (prefab.TryGetComponent(ref val) && (Object)(object)val.m_spawnOnHit != (Object)null && Object.op_Implicit((Object)(object)val.m_spawnOnHit.GetComponent())) { bool isClone2 = false; string source2 = ""; if (CloneManager.clones.TryGetValue(((Object)val.m_spawnOnHit).name, out var value)) { isClone2 = true; source2 = value.SourceName; } SpawnAbilityManager.Write(val.m_spawnOnHit, isClone2, source2, dirPath, context); } return true; } public static bool TryClone(GameObject source, string cloneName, out GameObject clone, bool write = true, string dirPath = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (CloneManager.prefabs.TryGetValue(cloneName, out clone)) { return true; } Clone clone2 = new Clone(source, cloneName); clone2.OnCreated += delegate(GameObject p) { Projectile val = default(Projectile); if (p.TryGetComponent(ref val) && (Object)(object)val.m_spawnOnHit != (Object)null && Object.op_Implicit((Object)(object)val.m_spawnOnHit.GetComponent())) { string cloneName2 = "MDB_" + cloneName + "_" + ((Object)val.m_spawnOnHit).name; if (SpawnAbilityManager.TryClone(val.m_spawnOnHit, cloneName2, out var clone3, write: false)) { val.m_spawnOnHit = clone3; } } MonsterDBPlugin.LogDebug("Cloned " + ((Object)source).name + " as " + cloneName); if (write) { Write(p, isClone: true, ((Object)source).name, dirPath, context); } }; clone = clone2.Create(); context?.LogInfo("Cloned " + ((Object)source).name + " as " + cloneName); return (Object)(object)clone != (Object)null; } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class ProjectileRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] public string m_prefab = ""; public ProjectileType? m_type; public DamageTypes? m_damage; public float? m_aoe; public bool? m_dodgeable; public bool? m_blockable; public float? m_adrenaline; public float? m_attackForce; public float? m_backstabBonus; public string m_statusEffect; public float? m_healthReturn; public float? m_ttl; public float? m_hitNoise; public EffectListRef m_hitEffects; public EffectListRef m_hitWaterEffects; [YamlMember(Description = "Bounce")] public bool? m_bounce; [Condition(bounce = true)] public bool? m_bounceOnWater; [Condition(bounce = true)] [YamlMember(Description = "0.0 - 1.0")] public float? m_bouncePower; [Condition(bounce = true)] public float? m_bounceRoughness; [Condition(bounce = true)] public int? m_maxBounces; [Condition(bounce = true)] public float? m_minBounceVel; [YamlMember(Description = "Spawn on Hit")] public bool? m_respawnItemOnHit; public bool? m_spawnOnTtl; public string m_spawnOnHit; [Condition(spawnOnHit = true)] [YamlMember(Description = "0.0 - 1.0")] public float? m_spawnOnHitChance; [Condition(spawnOnHit = true)] public int? m_spawnCount; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_randomSpawnOnHit; [Condition(randomSpawnOnHit = true)] public int? m_randomSpawnOnHitCount; [Condition(randomSpawnOnHit = true)] public bool? m_randomSpawnSkipLava; public bool? m_staticHitOnly; public bool? m_groundHitOnly; public Vector3Ref? m_spawnOffset; public bool? m_spawnRandomRotation; public bool? m_spawnFacingRotation; public EffectListRef m_spawnOnHitEffects; [YamlMember(Description = "Projectile Spawning")] public bool? m_spawnProjectileNewVelocity; public float? m_spawnProjectileMinVel; public float? m_spawnProjectileMaxVel; public float? m_spawnProjectileRandomDir; public bool? m_spawnProjectileHemisphereDir; public bool? m_projectilesInheritHitData; public bool? m_onlySpawnedProjectilesDealDamage; public bool? m_divideDamageBetweenProjectiles; public ProjectileRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public ProjectileRef(Projectile projectile) { Setup(projectile); m_prefab = ((Object)projectile).name; } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public override bool ShouldSetupField<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] V>(FieldInfo targetField, V source) { object obj = source; Projectile val = (Projectile)((obj is Projectile) ? obj : null); if (val == null) { return true; } return targetField.GetCustomAttribute()?.ShouldSetupField(val) ?? true; } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class TeleportAbilityRef : Reference { [YamlMember(Description = "Untagged, Respawn, Finish, Player, snappoint, StationUseArea, roof, minerock, antimist, SeekerQueenTeleportTarget")] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_targetTag = ""; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_message = ""; public float? m_maxTeleportRange = 100f; public TeleportAbilityRef() { } public TeleportAbilityRef(TeleportAbility ability) { Setup(ability); } public void Update(TeleportAbility ta, string targetName) { UpdateFields(ta, targetName, log: true); } } [Serializable] public class TriggerSpawnAbilityRef : Reference { [YamlMember(Description = "Triggers nearby spawners within range")] public float? m_range; public TriggerSpawnAbilityRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public TriggerSpawnAbilityRef(TriggerSpawnAbility ability) { m_range = ability.m_range; } } public class TriggerSpawnerRef { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public string[] m_creaturePrefabs; public int? m_maxLevel = 1; public int? m_minLevel = 1; public float? m_levelupChance = 10f; public float? m_spawnChance = 100f; public float? m_minSpawnInterval = 10f; public int? m_maxSpawned = 10; public float? m_maxExtraPerPlayer; public float? m_maxSpawnedRange = 30f; public bool? m_setHuntPlayer; public bool? m_setPatrolSpawnPoint; public bool? m_useSpawnerRotation; } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class BaseRagdoll : Header { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 6)] public RagdollRef Ragdoll; [YamlMember(Order = 7)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public VisualRef Visuals; public override void Setup(GameObject prefab, bool isClone = false, string source = "") { Ragdoll doll = default(Ragdoll); if (prefab.TryGetComponent(ref doll)) { base.Setup(prefab, isClone, source); Type = BaseType.Ragdoll; Ragdoll = new RagdollRef(doll); Visuals = new VisualRef(prefab); IsCloned = isClone; ClonedFrom = source; Prefab = ((Object)prefab).name; } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public override VisualRef GetVisualData() { return Visuals; } public override void CopyFields(Header original) { base.CopyFields(original); if (original is BaseRagdoll baseRagdoll) { if (Ragdoll != null && baseRagdoll.Ragdoll != null) { Ragdoll.ResetTo(baseRagdoll.Ragdoll); } if (Visuals != null && baseRagdoll.Visuals != null) { Visuals.ResetTo(baseRagdoll.Visuals); } } } public override void Update() { GameObject prefab = PrefabManager.GetPrefab(Prefab); if (!((Object)(object)prefab == (Object)null)) { UpdatePrefab(prefab); base.Update(); LoadManager.files.PrefabToUpdate = Prefab; LoadManager.files.Add(this); } } private void UpdatePrefab(GameObject prefab) { UpdateRagdoll(prefab); UpdateVisuals(prefab); } private void UpdateRagdoll(GameObject prefab) { Ragdoll target = default(Ragdoll); if (Ragdoll != null && prefab.TryGetComponent(ref target)) { Ragdoll.UpdateFields(target, ((Object)prefab).name, log: true); } } private void UpdateVisuals(GameObject prefab) { Visuals?.Update(prefab, isInstance: false, isItem: false); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class RagdollManager { private static bool TrySave(GameObject prefab, out BaseRagdoll ragdoll, bool isClone = false, string source = "") { ragdoll = LoadManager.GetOriginal(((Object)prefab).name); if (ragdoll != null) { return true; } if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { return false; } ragdoll = new BaseRagdoll(); ragdoll.Setup(prefab, isClone, source); LoadManager.originals.Add(((Object)prefab).name, ragdoll); return true; } public static void Write(GameObject prefab, bool isClone = false, string clonedFrom = "", string dirPath = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (string.IsNullOrEmpty(dirPath)) { dirPath = FileManager.ExportFolder; } string text = Path.Combine(dirPath, ((Object)prefab).name + ".yml"); if (TrySave(prefab, out var ragdoll, isClone, clonedFrom)) { string contents = ConfigManager.Serialize(ragdoll); File.WriteAllText(text, contents); MonsterDBPlugin.LogInfo("Saved " + ((Object)prefab).name + " to: " + text); context?.LogInfo("Exported " + ((Object)prefab).name); context?.LogInfo(text.RemoveRootPath()); } } private static void Read(string filePath) { if (!File.Exists(filePath)) { return; } string data = File.ReadAllText(filePath); try { Header header = ConfigManager.Deserialize
(data); if (header.Type == BaseType.Ragdoll) { BaseRagdoll baseRagdoll = ConfigManager.Deserialize(data); baseRagdoll.Update(); LoadManager.UpdateSync(); } } catch { MonsterDBPlugin.LogWarning("Failed to deserialize: " + Path.GetFileName(filePath)); } } public static bool TryClone(GameObject source, string cloneName, out GameObject clone, bool write = true, string dirPath = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (CloneManager.prefabs.TryGetValue(cloneName, out clone)) { context?.LogWarning(cloneName + " already exists"); return true; } Clone clone2 = new Clone(source, cloneName); clone2.OnCreated += delegate(GameObject p) { MonsterDBPlugin.LogDebug("Cloned " + ((Object)source).name + " as " + cloneName); if (write) { Write(p, isClone: true, ((Object)source).name, dirPath, context); } }; clone = clone2.Create(); context?.LogInfo("Cloned " + ((Object)source).name + " as " + cloneName); return (Object)(object)clone != (Object)null; } public static bool TryGetRagdoll(GameObject prefab, out GameObject output) { output = prefab; Character val = default(Character); if (!prefab.TryGetComponent(ref val)) { return false; } for (int i = 0; i < val.m_deathEffects.m_effectPrefabs.Length; i++) { EffectData val2 = val.m_deathEffects.m_effectPrefabs[i]; if (Object.op_Implicit((Object)(object)val2.m_prefab.GetComponent())) { output = val2.m_prefab; return true; } } return false; } } [Serializable] public class RagdollRef : Reference { public float? m_velMultiplier; public float? m_ttl; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public EffectListRef m_removeEffect; public bool? m_float; public float? m_floatOffset; public bool? m_dropItems; public RagdollRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public RagdollRef(Ragdoll doll) { Setup(doll); } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class RaidManager { public const string FolderName = "Raids"; private static readonly string FolderPath; private static Dictionary raids; private static readonly Dictionary defaultEnable; private static readonly ConfigEntry disableAll; private static readonly CustomSyncedValue sync; static RaidManager() { raids = new Dictionary(); defaultEnable = new Dictionary(); FolderPath = Path.Combine(ConfigManager.DirectoryPath, "Raids"); sync = new CustomSyncedValue(ConfigManager.ConfigSync, "MDB.ServerSync.Raids", ""); sync.ValueChanged += OnSyncChange; if (!Directory.Exists(FolderPath)) { Directory.CreateDirectory(FolderPath); } Read(); disableAll = ConfigManager.config("Raids", "Disable All", Toggle.Off, "If on, all raids are disabled"); disableAll.SettingChanged += OnDisableAllChanged; } [Obsolete] public static void WriteAllRaidYML(ConsoleEventArgs args) { if (!Object.op_Implicit((Object)(object)RandEventSystem.m_instance)) { args.Context.LogWarning("Random Event System not active"); return; } List events = RandEventSystem.instance.m_events; for (int i = 0; i < events.Count; i++) { RandomEvent raid = events[i]; Write(raid); } } public static void WriteRaidYML(Terminal context, string input) { if (!Object.op_Implicit((Object)(object)RandEventSystem.m_instance)) { context.LogWarning("Random Event System not active"); return; } if (string.IsNullOrEmpty(input)) { context.LogWarning("Invalid parameters"); return; } List events = RandEventSystem.instance.m_events; RandomEvent val = ((IEnumerable)events).FirstOrDefault((Func)([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (RandomEvent x) => string.Equals(x.m_name, input, StringComparison.CurrentCultureIgnoreCase))); if (val == null) { context.LogWarning("Failed to find raid: " + input); } else { Write(val); } } [Obsolete] public static void WriteRaidYML(ConsoleEventArgs args) { if (!Object.op_Implicit((Object)(object)RandEventSystem.m_instance)) { args.Context.LogWarning("Random Event System not active"); return; } string name = args.GetStringFrom(2); if (string.IsNullOrEmpty(name)) { args.Context.LogWarning("Invalid parameters"); return; } List events = RandEventSystem.instance.m_events; RandomEvent val = ((IEnumerable)events).FirstOrDefault((Func)([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (RandomEvent x) => string.Equals(x.m_name, name, StringComparison.CurrentCultureIgnoreCase))); if (val == null) { args.Context.LogWarning("Failed to find raid: " + name); } else { Write(val); } } [Obsolete] public static List GetRaidOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : GetRaidNames()); if (1 == 0) { } return result; } public static List GetRaidNames() { return Object.op_Implicit((Object)(object)RandEventSystem.instance) ? RandEventSystem.instance.m_events.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (RandomEvent x) => x.m_name).ToList() : new List(); } [Obsolete] public static void UpdateRaid(ConsoleEventArgs args) { Read(); Update(); args.Context.AddString("Updated all raids"); } public static void Start() { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown Harmony harmony = MonsterDBPlugin.harmony; harmony.Patch((MethodBase)AccessTools.Method(typeof(ZoneSystem), "SetupLocations", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(RaidManager), "Patch_ZoneSystem_SetupLocations", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static void Init(ZNet net) { if (net.IsServer()) { UpdateSync(); } } public static void Reset() { raids.Clear(); Read(); } private static void Write(RandomEvent raid) { RandomEventRef obj = new RandomEventRef(raid); string contents = ConfigManager.Serialize(obj); string text = raid.m_name; if (string.IsNullOrEmpty(text)) { text = "Untitled"; } string path = text + ".yml"; string path2 = Path.Combine(FolderPath, path); File.WriteAllText(path2, contents); } public static void Read() { string[] files = Directory.GetFiles(FolderPath, "*.yml"); foreach (string path in files) { string data = File.ReadAllText(path); try { RandomEventRef randomEventRef = ConfigManager.Deserialize(data); if (!string.IsNullOrEmpty(randomEventRef.m_name)) { raids[randomEventRef.m_name] = randomEventRef; } } catch { MonsterDBPlugin.LogWarning("Failed to deserialize raid: " + Path.GetFileName(path)); } } } public static void Update() { //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Expected O, but got Unknown if (!Object.op_Implicit((Object)(object)RandEventSystem.instance)) { return; } int num = 0; int num2 = 0; List list = new List(); for (int i = 0; i < RandEventSystem.instance.m_events.Count; i++) { RandomEvent val = RandEventSystem.instance.m_events[i]; if (!defaultEnable.ContainsKey(val.m_name)) { defaultEnable.Add(val.m_name, val.m_enabled); } val.m_enabled &= disableAll.Value == Toggle.Off; if (raids.TryGetValue(val.m_name, out var value)) { value.UpdateFields(val, val.m_name, log: true); list.Add(val.m_name); } if (val.m_enabled) { num++; } else { num2++; } } foreach (KeyValuePair raid in raids) { if (!list.Contains(raid.Key)) { RandomEvent val2 = new RandomEvent(); raid.Value.UpdateFields(val2, raid.Key, log: true); val2.m_enabled &= disableAll.Value == Toggle.Off; RandEventSystem.instance.m_events.Add(val2); if (val2.m_enabled) { num++; } else { num2++; } } } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append($"RaidManager: updated {raids.Count}, "); if (num > 0) { stringBuilder.Append($"enabled {num}, "); } if (num2 > 0) { stringBuilder.Append($"disabled {num2}, "); } stringBuilder.Append($"(total: {RandEventSystem.instance.m_events.Count})"); MonsterDBPlugin.LogInfo(stringBuilder.ToString()); } private static void UpdateSync() { if (Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer()) { sync.Value = ConfigManager.Serialize(raids); } } private static void OnSyncChange() { if (!Object.op_Implicit((Object)(object)ZNet.instance) || ZNet.instance.IsServer() || string.IsNullOrEmpty(sync.Value)) { return; } try { raids = ConfigManager.Deserialize>(sync.Value); Update(); } catch { MonsterDBPlugin.LogWarning("Failed to deserialize server raids"); } } private static void OnDisableAllChanged(object sender, EventArgs args) { int num = 0; int num2 = 0; for (int i = 0; i < RandEventSystem.instance.m_events.Count; i++) { RandomEvent val = RandEventSystem.instance.m_events[i]; if (!defaultEnable.TryGetValue(val.m_name, out var value)) { defaultEnable[val.m_name] = val.m_enabled; value = val.m_enabled; } val.m_enabled = value && disableAll.Value == Toggle.Off; if (val.m_enabled) { num++; } else { num2++; } } if (num > 0) { MonsterDBPlugin.LogInfo($"Enabled {num} raids"); } if (num2 > 0) { MonsterDBPlugin.LogInfo($"Disabled {num2} raids"); } } private static void Patch_ZoneSystem_SetupLocations() { Update(); } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class RandomEventRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] public string m_name = ""; public bool? m_enabled; public bool? m_random; public float? m_duration; public bool? m_nearBaseOnly; public bool? m_pauseIfNoPlayerInArea; public float? m_eventRange; public float? m_standaloneInterval; public float? m_standaloneChance; public float? m_spawnerDelay; public Biome? m_biome; [YamlMember(Description = "( Keys required to be TRUE )")] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_requiredGlobalKeys; [YamlMember(Description = "If PlayerEvents is set, instead only spawn this event at players know who at least one of each item on each list (or player key below).")] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_altRequiredKnownItems; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [YamlMember(Description = "If PlayerEvents is set, instead only spawn this event at players know who have ANY of these keys set (or any known items above).")] public List m_altRequiredPlayerKeysAny; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [YamlMember(Description = "If PlayerEvents is set, instead only spawn this event at players know who have ALL of these keys set (or any known items above).")] public List m_altRequiredPlayerKeysAll; [YamlMember(Description = "( Keys required to be FALSE )")] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_notRequiredGlobalKeys; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [YamlMember(Description = "If PlayerEvents is set, instead require ALL of the items to be unknown on this list for a player to be able to get that event. (And below not known player keys)")] public List m_altRequiredNotKnownItems; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [YamlMember(Description = "If PlayerEvents is set, instead require ALL of the playerkeys to be unknown on this list for a player to be able to get that event. (And above not known items)")] public List m_altNotRequiredPlayerKeys; public string m_startMessage; public string m_endMessage; public string m_forceMusic; public string m_forceEnvironment; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_spawn; public RandomEventRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public RandomEventRef(RandomEvent randomEvent) { Setup(randomEvent); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class RecipeManager { private static readonly Dictionary recipes; private static readonly Dictionary recipeByItem; private static readonly Dictionary recipeBySharedItemName; private static readonly List recipesToRegister; static RecipeManager() { recipes = new Dictionary(); recipeByItem = new Dictionary(); recipeBySharedItemName = new Dictionary(); recipesToRegister = new List(); } [HarmonyPriority(0)] public static void MapRecipes(ObjectDB __instance) { if ((Object)(object)__instance == (Object)null) { return; } for (int i = 0; i < recipesToRegister.Count; i++) { Recipe item = recipesToRegister[i]; if (!__instance.m_recipes.Contains(item)) { __instance.m_recipes.Add(item); } } for (int j = 0; j < __instance.m_recipes.Count; j++) { Recipe val = __instance.m_recipes[j]; if ((Object)(object)val.m_item == (Object)null) { MonsterDBPlugin.LogDebug("Mapping recipes, item is null: " + ((Object)val).name); continue; } recipes[((Object)val).name] = val; recipeByItem[((Object)val.m_item).name] = val; recipeBySharedItemName[val.m_item.m_itemData.m_shared.m_name] = val; } } public static bool TryGetRecipe(string name, out Recipe recipe) { return recipes.TryGetValue(name, out recipe); } public static bool TryGetRecipeByItem(string name, out Recipe recipe) { return recipeByItem.TryGetValue(name, out recipe); } public static bool TryGetRecipeBySharedName(string name, out Recipe recipe) { return recipeBySharedItemName.TryGetValue(name, out recipe); } public static void Register(this Recipe recipe) { if (!((Object)(object)recipe.m_item == (Object)null)) { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && !ObjectDB.instance.m_recipes.Contains(recipe)) { ObjectDB.instance.m_recipes.Add(recipe); } if ((Object)(object)PrefabManager._ObjectDB != (Object)null && !PrefabManager._ObjectDB.m_recipes.Contains(recipe)) { PrefabManager._ObjectDB.m_recipes.Add(recipe); } if (!recipesToRegister.Contains(recipe)) { recipesToRegister.Add(recipe); } recipes[((Object)recipe).name] = recipe; recipeByItem[((Object)recipe.m_item).name] = recipe; recipeBySharedItemName[recipe.m_item.m_itemData.m_shared.m_name] = recipe; } } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class RecipeRef : Reference { public string m_item; public int? m_amount = 1; public bool? m_enabled = true; public float? m_qualityResultAmountMultiplier = 1f; public int? m_listSortWeight = 100; public string m_craftingStation; public string m_repairStation; public int? m_minStationLevel = 1; public bool? m_requireOnlyOneIngredient; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public RequirementRef[] m_resources; public RecipeRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public RecipeRef(Recipe recipe) { ItemDrop item = recipe.m_item; m_item = ((item != null) ? ((Object)item).name : null); m_amount = recipe.m_amount; m_enabled = recipe.m_enabled; m_qualityResultAmountMultiplier = recipe.m_qualityResultAmountMultiplier; m_listSortWeight = recipe.m_listSortWeight; CraftingStation craftingStation = recipe.m_craftingStation; m_craftingStation = ((craftingStation != null) ? ((Object)craftingStation).name : null); CraftingStation repairStation = recipe.m_repairStation; m_repairStation = ((repairStation != null) ? ((Object)repairStation).name : null); m_minStationLevel = recipe.m_minStationLevel; m_requireOnlyOneIngredient = recipe.m_requireOnlyOneIngredient; m_resources = recipe.m_resources.ToRequirementRef(); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class RequirementRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_resItem; public int? m_amount; public int? m_extraAmountOnlyOneIngredient; public int? m_amountPerLevel; public bool? m_recover; public RequirementRef() { } public RequirementRef(Requirement requirement) { ItemDrop resItem = requirement.m_resItem; m_resItem = ((resItem != null) ? ((Object)resItem).name : null); m_amount = requirement.m_amount; m_extraAmountOnlyOneIngredient = requirement.m_extraAmountOnlyOneIngredient; m_amountPerLevel = requirement.m_amountPerLevel; m_recover = requirement.m_recover; } public bool TryGetPieceRequirement(out Requirement requirement) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown requirement = new Requirement(); if (m_resItem == null) { return false; } GameObject prefab = PrefabManager.GetPrefab(m_resItem); if ((Object)(object)prefab == (Object)null) { return false; } ItemDrop resItem = default(ItemDrop); if (!prefab.TryGetComponent(ref resItem)) { return false; } requirement.m_resItem = resItem; requirement.m_amount = m_amount.GetValueOrDefault(1); requirement.m_amountPerLevel = m_amountPerLevel.GetValueOrDefault(1); requirement.m_extraAmountOnlyOneIngredient = m_extraAmountOnlyOneIngredient.GetValueOrDefault(1); requirement.m_amountPerLevel = m_amountPerLevel.GetValueOrDefault(1); requirement.m_recover = m_recover.GetValueOrDefault(); return true; } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public abstract class Reference { public const BindingFlags FieldBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; public void ResetTo(Reference source) { if (source.GetType() != GetType()) { MonsterDBPlugin.LogWarning("[ResetTo] Type mismatch: target=" + GetType().Name + " != source=" + source.GetType().Name); return; } FieldInfo[] fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { object value = fieldInfo.GetValue(this); if (value == null) { continue; } object value2 = fieldInfo.GetValue(source); if (value2 == null) { continue; } if (value is Reference reference && value2 is Reference source2) { reference.ResetTo(source2); } else if (value is RendererRef[] array && value2 is RendererRef[] source3) { Dictionary<(string, string, int?), RendererRef> dictionary = (from x in source3 group x by (x.m_prefab, x.m_parent, x.m_index)).ToDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping<(string m_prefab, string m_parent, int? m_index), RendererRef> x) => x.Key, [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping<(string m_prefab, string m_parent, int? m_index), RendererRef> x) => x.First()); foreach (RendererRef rendererRef in array) { (string, string, int?) key = (rendererRef.m_prefab, rendererRef.m_parent, rendererRef.m_index); if (dictionary.TryGetValue(key, out var value3)) { rendererRef.ResetTo(value3); } } } else if (value is LightRef[] array2 && value2 is LightRef[] source4) { Dictionary<(string, string, int?), LightRef> dictionary2 = (from x in source4 group x by (x.m_prefab, x.m_parent, x.m_index)).ToDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping<(string m_prefab, string m_parent, int? m_index), LightRef> x) => x.Key, [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping<(string m_prefab, string m_parent, int? m_index), LightRef> x) => x.First()); foreach (LightRef lightRef in array2) { (string, string, int?) key2 = (lightRef.m_prefab, lightRef.m_parent, lightRef.m_index); if (dictionary2.TryGetValue(key2, out var value4)) { lightRef.ResetTo(value4); } } } else if (value is ParticleSystemRef[] array3 && value2 is ParticleSystemRef[] source5) { Dictionary<(string, string, int?), ParticleSystemRef> dictionary3 = (from x in source5 group x by (x.m_prefab, x.m_parent, x.m_index)).ToDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping<(string m_prefab, string m_parent, int? m_index), ParticleSystemRef> x) => x.Key, [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping<(string m_prefab, string m_parent, int? m_index), ParticleSystemRef> x) => x.First()); foreach (ParticleSystemRef particleSystemRef in array3) { (string, string, int?) key3 = (particleSystemRef.m_prefab, particleSystemRef.m_parent, particleSystemRef.m_index); if (dictionary3.TryGetValue(key3, out var value5)) { particleSystemRef.ResetTo(value5); } } } else { fieldInfo.SetValue(this, value2); } } } public int Clean(Reference target, string targetName, bool log) { int num = 0; if (target.GetType() != GetType()) { MonsterDBPlugin.LogWarning("[Clean] Type mismatch: target=" + target.GetType().Name + " != source=" + GetType().Name); return num; } if (string.IsNullOrEmpty(targetName)) { targetName = "Unknown"; } FieldInfo[] fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { object value = fieldInfo.GetValue(target); object value2 = fieldInfo.GetValue(this); if (value is TransformRef transformRef && value2 is TransformRef transformRef2) { if (!(transformRef.m_position == transformRef2.m_position) && transformRef.m_position.HasValue && transformRef2.m_position.HasValue && !transformRef.m_position.Value.x.Equals(transformRef2.m_position.Value.x) && !transformRef.m_position.Value.y.Equals(transformRef2.m_position.Value.y) && !transformRef.m_position.Value.z.Equals(transformRef2.m_position.Value.z)) { transformRef.m_position = null; num++; if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + fieldInfo.Name + ".m_position: [ CLEAN ]"); } } } else if (value is Reference target2 && value2 is Reference reference) { num += reference.Clean(target2, targetName, log); } else if (value2 != null && value != null && fieldInfo.GetCustomAttribute() == null && CleanField(target, fieldInfo, value2, value, targetName, log)) { num++; } } return num; } private bool CleanField(Reference target, FieldInfo field, object originalValue, object targetValue, string targetName, bool log) { //IL_03f3: Unknown result type (might be due to invalid IL or missing references) //IL_0413: Unknown result type (might be due to invalid IL or missing references) Type type = Nullable.GetUnderlyingType(field.FieldType) ?? field.FieldType; if (type.IsArray) { if (!(originalValue is Array array) || !(targetValue is Array array2)) { return false; } if (array.Length != array2.Length) { return false; } if (array.Length > 0) { if (array.GetValue(0) is Reference) { for (int i = 0; i < array.Length; i++) { Reference reference = array.GetValue(i) as Reference; Reference reference2 = array2.GetValue(i) as Reference; if (reference != null && reference2 != null) { reference.Clean(reference2, targetName, log); } } } else { bool flag = true; for (int j = 0; j < array.Length - 1; j++) { object value = array.GetValue(j); object value2 = array2.GetValue(j); if (value2 != value) { flag = false; break; } } if (flag) { field.SetValue(target, null); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + field.Name); } return true; } } } } else if (targetValue is EffectListRef effectListRef && originalValue is EffectListRef effectListRef2) { List list = effectListRef.m_effectPrefabs.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (EffectListRef.EffectDataRef t) => t.m_prefab).ToList(); List list2 = effectListRef2.m_effectPrefabs.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (EffectListRef.EffectDataRef m) => m.m_prefab).ToList(); if (list.Count != list2.Count) { return false; } bool flag2 = true; for (int k = 0; k < list.Count; k++) { string text = list[k]; string value3 = list2[k]; if (!text.Equals(value3)) { flag2 = false; break; } } if (flag2) { field.SetValue(target, null); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + field.Name); } return true; } } else if (targetValue is List list3 && originalValue is List list4) { if (list3.Count != list4.Count) { return false; } bool flag3 = true; for (int l = 0; l < list4.Count; l++) { StepEffectRef stepEffectRef = list3[l]; StepEffectRef stepEffectRef2 = list4[l]; if (stepEffectRef.m_effectPrefabs == null || stepEffectRef2.m_effectPrefabs == null || stepEffectRef.m_effectPrefabs.Length != stepEffectRef2.m_effectPrefabs.Length) { continue; } for (int n = 0; n < stepEffectRef2.m_effectPrefabs.Length; n++) { string text2 = stepEffectRef.m_effectPrefabs[n]; string value4 = stepEffectRef2.m_effectPrefabs[n]; if (!text2.Equals(value4)) { flag3 = false; break; } } if (!flag3) { break; } if (!stepEffectRef.m_name.Equals(stepEffectRef2.m_name) || !((object)(MotionType)(ref stepEffectRef.m_motionType)).Equals((object?)stepEffectRef2.m_motionType) || !((object)(GroundMaterial)(ref stepEffectRef.m_material)).Equals((object?)stepEffectRef2.m_material)) { flag3 = false; break; } } if (flag3) { field.SetValue(target, null); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + field.Name); } return true; } } else if (targetValue is List list5 && originalValue is List list6) { if (list5.Count != list6.Count) { return false; } bool flag4 = true; for (int num = 0; num < list6.Count; num++) { LevelSetupRef levelSetupRef = list6[num]; LevelSetupRef other = list6[num]; if (!levelSetupRef.Equals(other)) { flag4 = false; break; } } if (flag4) { field.SetValue(target, null); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + field.Name); } return true; } } else { if (targetValue.Equals(originalValue)) { field.SetValue(target, null); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + field.Name); } return true; } if (targetValue is float num2 && originalValue is float num3 && true && Mathf.Approximately(num2, num3)) { field.SetValue(target, null); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + field.Name); } return true; } } return false; } public virtual bool Equals<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>(T other) where T : Reference { return other == this; } public virtual bool IsNull() { FieldInfo[] fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { object value = fieldInfo.GetValue(this); if (value != null) { return false; } } return true; } public void Setup<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] V>(V source) { if (source == null) { return; } Dictionary dictionary = GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToSafeDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (FieldInfo f) => f.Name); FieldInfo[] fields = source.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { if (dictionary.TryGetValue(fieldInfo.Name, out var value) && ShouldSetupField(value, source)) { object value2 = fieldInfo.GetValue(source); if (value2 != null) { SetupField(fieldInfo, value, value2); } } } } protected virtual void SetupField(FieldInfo source, FieldInfo target, object value) { try { Type type = Nullable.GetUnderlyingType(target.FieldType) ?? target.FieldType; Type fieldType = source.FieldType; if (type.IsAssignableFrom(fieldType)) { target.SetValue(this, value); return; } GameObject val = (GameObject)((value is GameObject) ? value : null); ItemSet[] array2; RandomItem[] array3; if (val == null) { ItemDrop val2 = (ItemDrop)((value is ItemDrop) ? value : null); if (val2 == null) { Sprite val3 = (Sprite)((value is Sprite) ? value : null); if (val3 == null) { EffectList val4 = (EffectList)((value is EffectList) ? value : null); if (val4 == null) { GameObject[] array; if (value is Sprite[] icons) { if (type == typeof(string[])) { target.SetValue(this, icons.ToSpriteNameArray()); return; } array = value as GameObject[]; if (array == null) { goto IL_00c5; } } else { if (value is List ge) { if (type == typeof(List)) { target.SetValue(this, ge.ToGrowUpRefEntryList()); } return; } array = value as GameObject[]; if (array == null) { array2 = value as ItemSet[]; if (array2 != null) { goto IL_0322; } array3 = value as RandomItem[]; if (array3 == null) { StatusEffect val5 = (StatusEffect)((value is StatusEffect) ? value : null); if (val5 == null) { Attack val6 = (Attack)((value is Attack) ? value : null); if (val6 == null) { if (!(value is List items)) { if (!(value is List ls)) { if (!(value is List cd)) { if (!(value is List dropData)) { if (!(value is List baitSettings)) { if (!(value is List list)) { if (!(value is List sps)) { Material val7 = (Material)((value is Material) ? value : null); if (val7 == null) { if (!(value is List spawns)) { if (value is List effects && type == typeof(List)) { target.SetValue(this, effects.ToStepEffectRefList()); } } else if (type == typeof(List)) { target.SetValue(this, spawns.ToSpawnDataRefList()); } } else if (type == typeof(string)) { target.SetValue(this, ((Object)val7).name); } } else if (type == typeof(List)) { target.SetValue(this, sps.ToSpawnDataRefList()); } } else if (type == typeof(List)) { target.SetValue(this, list.ToRef()); } } else if (type == typeof(List)) { target.SetValue(this, baitSettings.ToBaitSettingsRefList()); } } else if (type == typeof(List)) { target.SetValue(this, dropData.ToDropDataRefList()); } } else if (type == typeof(List)) { target.SetValue(this, cd.ToRef()); } } else if (type == typeof(List)) { target.SetValue(this, ls.ToLevelSetupRefList()); } } else if (type == typeof(List)) { target.SetValue(this, items.ToItemNameList()); } } else if (type == typeof(AttackRef) && !string.IsNullOrEmpty(val6.m_attackAnimation)) { target.SetValue(this, val6.ToAttackRef()); } } else if (type == typeof(string)) { target.SetValue(this, ((Object)val5).name); } return; } goto IL_034d; } } if (!(type == typeof(string[]))) { goto IL_00c5; } target.SetValue(this, array.ToGameObjectNameArray()); return; } if (type == typeof(EffectListRef) && val4.m_effectPrefabs != null && val4.m_effectPrefabs.Length != 0) { target.SetValue(this, val4.ToEffectListRef()); } return; } if (type == typeof(string)) { target.SetValue(this, ((Object)val3).name); } return; } if (type == typeof(string)) { target.SetValue(this, ((Object)val2).name); } return; } if (type == typeof(string)) { target.SetValue(this, ((Object)val).name); } return; IL_0322: if (!(type == typeof(HumanoidRef.ItemSet[]))) { goto IL_00e9; } target.SetValue(this, array2.ToHumanoidRefItemSetArray()); return; IL_00c5: array2 = value as ItemSet[]; if (array2 == null) { goto IL_00e9; } goto IL_0322; IL_00e9: array3 = value as RandomItem[]; if (array3 == null) { return; } goto IL_034d; IL_034d: if (type == typeof(HumanoidRef.RandomItem[])) { target.SetValue(this, array3.ToHumanoidRefRandomItemArray()); } } catch (Exception ex) { MonsterDBPlugin.LogDebug(ex.Message); } } public virtual bool ShouldSetupField<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] V>(FieldInfo targetField, V source) { return true; } public virtual void UpdateFields<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, string targetName, bool log) { if (target == null) { return; } Type type = target.GetType(); Type type2 = GetType(); if (string.IsNullOrEmpty(targetName)) { targetName = "Unknown"; } if (log) { if (LoadManager.resetting) { MonsterDBPlugin.LogDebug("[" + targetName + "] Resetting " + type.FullName); } else { MonsterDBPlugin.LogDebug("[" + targetName + "] Updating " + type.FullName); } } log &= ConfigManager.ShouldLogDetails(); Dictionary dictionary = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToSafeDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (FieldInfo f) => f.Name); FieldInfo[] fields = type2.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { if (dictionary.TryGetValue(fieldInfo.Name, out var value)) { UpdateField(target, fieldInfo, value, targetName, log); } } } private void UpdateField<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo sourceField, FieldInfo targetField, string targetName, bool log) { object value = sourceField.GetValue(this); if (value != null) { Type fieldType = targetField.FieldType; Type c = Nullable.GetUnderlyingType(sourceField.FieldType) ?? sourceField.FieldType; if (string.IsNullOrEmpty(targetName)) { targetName = "Unknown"; } if (fieldType.IsAssignableFrom(c)) { UpdateAssignableType(target, targetField, fieldType, value, targetName, log); } else if (fieldType == typeof(GameObject) && value is string goName) { UpdateGameObject(target, targetField, targetName, goName, log); } else if (fieldType == typeof(Sprite[]) && value is string[] spriteNames) { UpdateSpriteArray(target, targetField, spriteNames, targetName, log); } else if (fieldType == typeof(Vector3) && value is Vector3Ref vector) { UpdateVector3(target, targetField, vector, targetName, log); } else if (fieldType == typeof(GameObject[]) && value is string[] goNames) { UpdateGameObjectArray(target, targetField, goNames, targetName, log); } else if (fieldType == typeof(ItemSet[]) && value is HumanoidRef.ItemSet[] sets) { UpdateItemSets(target, targetField, sets, targetName, log); } else if (fieldType == typeof(RandomItem[]) && value is HumanoidRef.RandomItem[] items) { UpdateRandomItems(target, targetField, items, targetName, log); } else if (fieldType == typeof(EffectList) && value is EffectListRef el) { UpdateEffectList(target, targetField, el, targetName, log); } else if (fieldType == typeof(StatusEffect) && value is string name) { UpdateStatusEffect(target, targetField, name, targetName, log); } else if (fieldType == typeof(Color) && value is string hex) { UpdateColor(target, targetField, hex, targetName, log); } else if (fieldType == typeof(List) && value is List dropRefs) { UpdateCharacterDrops(target, targetField, dropRefs, targetName, log); } else if (fieldType == typeof(List) && value is List itemNames) { UpdateItemList(target, targetField, itemNames, targetName, log); } else if (fieldType == typeof(List) && value is List entries) { UpdateGrownEntries(target, targetField, entries, targetName, log); } else if (fieldType == typeof(Sprite) && value is string spriteName) { UpdateSprite(target, targetField, spriteName, targetName, log); } else if (fieldType == typeof(List) && value is List dropData) { UpdateDropTable(target, targetField, dropData, targetName, log); } else if (fieldType == typeof(List) && value is List baitSettings) { UpdateFishBaits(target, targetField, baitSettings, targetName, log); } else if (fieldType == typeof(List) && value is List rv) { UpdateRandomAnimations(target, targetField, rv, targetName, log); } else if (fieldType == typeof(Attack) && value is AttackRef attackRef) { UpdateAttack(target, targetField, attackRef, targetName, log); } else if (fieldType == typeof(Aoe) && value is AoeRef aoeRef) { UpdateAoe(target, targetField, aoeRef, targetName, log); } else if (fieldType == typeof(ItemDrop) && value is string name2) { UpdateItem(target, targetField, name2, targetName, log); } else if (fieldType == typeof(List) && value is List r) { UpdateSpawnDataList(target, targetField, r, targetName, log); } else if (fieldType == typeof(DropTable) && value is DropTableRef dt) { UpdateDropTable(target, targetField, dt, targetName, log); } else if (fieldType == typeof(Material) && value is string materialName) { UpdateMaterial(target, targetField, materialName, targetName, log); } else if (fieldType == typeof(List) && value is List spawns) { UpdateSpawnDataList(target, targetField, spawns, targetName, log); } else if (fieldType == typeof(Requirement[]) && value is RequirementRef[] requirements) { UpdateRequirements(target, targetField, requirements, targetName, log); } else if (fieldType == typeof(CraftingStation) && value is string name3) { UpdateCraftingStation(target, targetField, name3, targetName, log); } else if (fieldType == typeof(List) && value is List effects) { UpdateStepEffect(target, targetField, effects, targetName, log); } } } protected virtual void UpdateAssignableType<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, Type targetType, object value, string targetName, bool log) { //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) object obj = target; Character val = (Character)((obj is Character) ? obj : null); if (val != null && ((Object)val).name.Contains("(Clone)") && targetField.Name == "m_boss") { MonsterDBPlugin.LogDebug("Skipping m_boss, prefab is an instance"); return; } targetField.SetValue(target, value); if (!log) { return; } if (targetType.IsArray) { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: {targetType.Name}[{((Array)value).Length}]"); } else if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(List<>)) { Type type = targetType.GetGenericArguments()[0]; int count = ((ICollection)value).Count; MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: {type.Name}[{count}]"); } else if (targetType == typeof(DamageModifiers)) { DamageModifiers modifiers = (DamageModifiers)value; FieldInfo[] fields = ((object)modifiers).GetType().GetFields(); IEnumerable values = fields.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (FieldInfo f) => $"{f.Name}={f.GetValue(modifiers)}"); MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + string.Join(", ", values)); } else { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: {value}"); } } protected virtual void UpdateMaterial<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, string materialName, string targetName, bool log) { Material material; if (string.IsNullOrEmpty(materialName)) { targetField.SetValue(target, null); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": null"); } } else if (MaterialManager.TryGetMaterial(materialName, out material)) { targetField.SetValue(target, material); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + ((Object)material).name); } } else { MonsterDBPlugin.LogWarning("Failed to find material: " + materialName); } } public static void UpdateCraftingStation<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, string name, string targetName, bool log) { GameObject prefab = PrefabManager.GetPrefab(name); if ((Object)(object)prefab == (Object)null) { return; } CraftingStation value = default(CraftingStation); if (!prefab.TryGetComponent(ref value)) { MonsterDBPlugin.LogWarning("[" + targetName + "] " + targetField.Name + ": " + name + " missing CraftingStation component"); return; } targetField.SetValue(target, value); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + name); } } public void UpdateStepEffect<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, List effects, string targetName, bool log) { if (!(targetField.GetValue(target) is List defaultValues)) { return; } List list = effects.ToFootStepEffects(defaultValues); targetField.SetValue(target, list); if (!log) { return; } MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: FootStep.StepEffect[{list.Count}]"); for (int i = 0; i < list.Count; i++) { StepEffect val = list[i]; string text = string.Join(", ", val.m_effectPrefabs.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (GameObject e) => ((Object)e).name)); MonsterDBPlugin.LogDebug("[" + targetName + "][" + targetField.Name + "] " + val.m_name + ": " + text); } } protected void UpdateRequirements<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, RequirementRef[] requirements, string targetName, bool log) { Requirement[] array = requirements.ToPieceRequirements(); targetField.SetValue(target, array); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: Piece.Requirements[{array.Length}]"); } } protected virtual void UpdateDropTable<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, DropTableRef dt, string targetName, bool log) { DropTable value = dt.ToDropTable(targetName); targetField.SetValue(target, value); } protected virtual void UpdateGameObject<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, string targetName, string goName, bool log) { if (string.IsNullOrEmpty(goName)) { targetField.SetValue(target, null); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": null"); } return; } GameObject prefab = PrefabManager.GetPrefab(goName); if ((Object)(object)prefab != (Object)null) { targetField.SetValue(target, prefab); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + ((Object)prefab).name); } } } private void UpdateSpawnDataList<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, List r, string targetName, bool log) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown log &= ConfigManager.ShouldLogDetails(); if (string.IsNullOrEmpty(targetName)) { targetName = "Unknown"; } List list = new List(); for (int i = 0; i < r.Count; i++) { SpawnDataRef spawnDataRef = r[i]; SpawnData val = new SpawnData(); spawnDataRef.UpdateFields(val, spawnDataRef.m_name, log: false); if (!((Object)(object)val.m_prefab == (Object)null)) { list.Add(val); } } targetField.SetValue(target, list); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: SpawnSystem.SpawnData[{list.Count}]"); } } private void UpdateSpriteArray<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, string[] spriteNames, string targetName, bool log) { Sprite[] array = spriteNames.ToSpriteArray(); if (array.Length == 0) { return; } if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + string.Join(", ", array.Select([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (Sprite x) => ((Object)x).name))); } targetField.SetValue(target, array); } private void UpdateSpawnDataList<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, List spawns, string targetName, bool log) { List value = spawns.ToSpawnAreaSpawnDataList(); targetField.SetValue(target, value); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: SpawnArea.SpawnData[{spawns.Count}]"); } } private void UpdateVector3<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, Vector3Ref vector, string targetName, bool log) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + vector.ToString()); } targetField.SetValue(target, vector.ToVector3()); } private void UpdateGameObjectArray<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, string[] goNames, string targetName, bool log) { GameObject[] array = goNames.ToGameObjectArray(); targetField.SetValue(target, array); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: GameObject[{array.Length}]"); } } private void UpdateItemSets<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, HumanoidRef.ItemSet[] sets, string targetName, bool log) { ItemSet[] array = sets.ToHumanoidItemSetArray(); targetField.SetValue(target, array); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: ItemSet[{array.Length}]"); } } private void UpdateRandomItems<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, HumanoidRef.RandomItem[] items, string targetName, bool log) { RandomItem[] array = items.ToHumanoidRandomItemArray(); targetField.SetValue(target, array); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: RandomItem[{array.Length}]"); } } private void UpdateEffectList<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, EffectListRef el, string targetName, bool log) { EffectList effects = el.Effects; targetField.SetValue(target, effects); if (effects.m_effectPrefabs != null && log) { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: EffectList[{effects.m_effectPrefabs.Length}]"); } } private void UpdateStatusEffect<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, string name, string targetName, bool log) { StatusEffect statusEffect = PrefabManager.GetStatusEffect(name); targetField.SetValue(target, statusEffect); if ((Object)(object)statusEffect != (Object)null && log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + ((Object)statusEffect).name); } } private void UpdateColor<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, string hex, string targetName, bool log) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) object value = targetField.GetValue(target); if (!(value is Color)) { return; } Color defaultValue = (Color)value; if (true) { Color val = hex.FromHexOrRGBA(defaultValue); targetField.SetValue(target, val); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + ((object)(Color)(ref val)).ToString()); } } } private void UpdateCharacterDrops<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, List dropRefs, string targetName, bool log) { List list = dropRefs.FromRef(); targetField.SetValue(target, list); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: CharacterDrop[{list.Count}]"); } } private void UpdateItemList<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, List itemNames, string targetName, bool log) { List list = itemNames.ToItemDropList(); targetField.SetValue(target, list); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: ItemDrop[{list.Count}]"); } } private void UpdateGrownEntries<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, List entries, string targetName, bool log) { List list = entries.FromRef(); targetField.SetValue(target, list); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: GrownEntry[{list.Count}]"); } } private void UpdateSprite<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, string spriteName, string targetName, bool log) { object value = targetField.GetValue(target); Sprite defaultValue = (Sprite)((value is Sprite) ? value : null); Sprite sprite = TextureManager.GetSprite(spriteName, defaultValue); if ((Object)(object)sprite != (Object)null) { targetField.SetValue(target, sprite); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + ((Object)sprite).name); } } } private void UpdateDropTable<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, List dropData, string targetName, bool log) { List list = dropData.ToDropDataList(); targetField.SetValue(target, list); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: DropTable[{list.Count}]"); } } private void UpdateFishBaits<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, List baitSettings, string targetName, bool log) { List list = baitSettings.ToBaitSettingsList(); targetField.SetValue(target, list); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: BaitSetting[{list.Count}]"); } } private void UpdateRandomAnimations<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, List rv, string targetName, bool log) { List list = rv.FromRef(); targetField.SetValue(target, list); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}] {targetField.Name}: RandomAnimation[{list.Count}]"); } } private void UpdateAttack<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, AttackRef attackRef, string targetName, bool log) { object value = targetField.GetValue(target); Attack val = (Attack)((value is Attack) ? value : null); if (val != null) { attackRef.UpdateFields(val, targetName, log); } } private void UpdateAoe<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, AoeRef aoeRef, string targetName, bool log) { object value = targetField.GetValue(target); Aoe val = (Aoe)((value is Aoe) ? value : null); if (val != null) { aoeRef.UpdateFields(val, targetName, log); } } private void UpdateItem<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] T>(T target, FieldInfo targetField, string name, string targetName, bool log) { GameObject prefab = PrefabManager.GetPrefab(name); ItemDrop value = default(ItemDrop); if ((Object)(object)prefab != (Object)null && prefab.TryGetComponent(ref value)) { targetField.SetValue(target, value); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "] " + targetField.Name + ": " + name); } } } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class BaseSpawnAbility : Header { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 6)] public SpawnAbilityRef SpawnAbility; [YamlMember(Order = 7)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public VisualRef Visuals; public override void Setup(GameObject prefab, bool isClone = false, string source = "") { base.Setup(prefab, isClone, source); Type = BaseType.SpawnAbility; Prefab = ((Object)prefab).name; IsCloned = isClone; ClonedFrom = source; Visuals = new VisualRef(prefab); SetupSpawnAbility(prefab); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public override VisualRef GetVisualData() { return Visuals; } public override void CopyFields(Header original) { base.CopyFields(original); if (original is BaseSpawnAbility baseSpawnAbility) { if (SpawnAbility != null && baseSpawnAbility.SpawnAbility != null) { SpawnAbility.ResetTo(baseSpawnAbility.SpawnAbility); } if (Visuals != null && baseSpawnAbility.Visuals != null) { Visuals.ResetTo(baseSpawnAbility.Visuals); } } } private void SetupSpawnAbility(GameObject prefab) { SpawnAbility ability = default(SpawnAbility); if (prefab.TryGetComponent(ref ability)) { SpawnAbility = new SpawnAbilityRef(ability); } } public override void Update() { GameObject prefab = PrefabManager.GetPrefab(Prefab); if (!((Object)(object)prefab == (Object)null)) { UpdatePrefab(prefab); base.Update(); LoadManager.files.PrefabToUpdate = Prefab; LoadManager.files.Add(this); } } private void UpdatePrefab(GameObject prefab) { UpdateVisuals(prefab); UpdateSpawnAbility(prefab); } private void UpdateSpawnAbility(GameObject prefab) { SpawnAbility target = default(SpawnAbility); if (SpawnAbility != null && prefab.TryGetComponent(ref target)) { SpawnAbility.UpdateFields(target, ((Object)prefab).name, log: true); } } protected virtual void UpdateVisuals(GameObject prefab) { Visuals?.Update(prefab, isInstance: false, isItem: false); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class SpawnAbilityRef : Reference { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public string[] m_spawnPrefab; public string m_maxSummonReached = "$hud_maxsummonsreached"; public bool? m_spawnOnAwake; public bool? m_alertSpawnedCreature = true; public bool? m_passiveAggressive; public bool? m_spawnAtTarget = true; public int? m_minToSpawn = 1; public int? m_maxToSpawn = 1; public int? m_maxSpawned = 3; public float? m_spawnRadius = 3f; public bool? m_circleSpawn; public bool? m_snapToTerrain = true; [YamlMember(Description = "Used to give random Y rotations to things like AOEs that aren't circular")] public bool? m_randomYRotation; public float? m_spawnGroundOffset; public int? m_getSolidHeightMargin = 1000; public float? m_initialSpawnDelay; public float? m_spawnDelay; public float? m_preSpawnDelay; public bool? m_commandOnSpawn; public bool? m_wakeUpAnimation; public SkillType? m_copySkill; public float? m_copySkillToRandomFactor; public bool? m_setMaxInstancesFromWeaponLevel; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_levelUpSettings; public TargetType? m_targetType; public AgentType? m_targetWhenPathfindingType = (AgentType)1; public float? m_maxTargetRange = 40f; public EffectListRef m_spawnEffects; public EffectListRef m_preSpawnEffects; [YamlMember(Description = "Used for the troll summoning staff, to spawn an AOE that's friendly to the spawned creature.")] public string m_aoePrefab; [YamlMember(Description = "Projectile")] public float? m_projectileVelocity = 10f; public float? m_projectileVelocityMax; public float? m_projectileAccuracy = 10f; public bool? m_randomDirection; public float? m_randomAngleMin; public float? m_randomAngleMax; public SpawnAbilityRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public SpawnAbilityRef(SpawnAbility ability) { Setup(ability); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class SpawnAbilityManager { [Obsolete] public static void WriteSpawnAbilityYML(ConsoleEventArgs args) { string text = args[2]; if (string.IsNullOrEmpty(text)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(text); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + text); return; } if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { args.Context.LogWarning("Invalid prefab, missing SpawnAbility component"); return; } string sourceName; bool isClone = CloneManager.IsClone(((Object)prefab).name, out sourceName); Write(prefab, isClone, sourceName); } [Obsolete] public static List GetSpawnAbilityOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : PrefabManager.GetAllPrefabNames()); if (1 == 0) { } return result; } [Obsolete] public static void CloneSpawnAbility(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); return; } string string2 = args.GetString(3); if (string.IsNullOrEmpty(string2)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); } else if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { args.Context.LogWarning("Invalid prefab, missing SpawnAbility component"); } else { TryClone(prefab, string2, out var _, write: true, "", args.Context); } } public static bool Write(GameObject prefab, bool isClone = false, string source = "", string dirPath = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (string.IsNullOrEmpty(dirPath)) { dirPath = FileManager.ExportFolder; } string text = Path.Combine(dirPath, ((Object)prefab).name + ".yml"); BaseSpawnAbility baseSpawnAbility = new BaseSpawnAbility(); baseSpawnAbility.Setup(prefab, isClone, source); string contents = ConfigManager.Serialize(baseSpawnAbility); File.WriteAllText(text, contents); context?.LogInfo("Exported Spawn Ability " + ((Object)prefab).name); context?.LogInfo(text.RemoveRootPath()); return true; } public static bool TryClone(GameObject prefab, string cloneName, out GameObject clone, bool write = true, string dirPath = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (string.IsNullOrEmpty(dirPath)) { dirPath = FileManager.ExportFolder; } if (CloneManager.prefabs.TryGetValue(cloneName, out clone)) { return true; } Clone clone2 = new Clone(prefab, cloneName); clone2.OnCreated += delegate(GameObject p) { if (write) { Write(p, isClone: true, ((Object)prefab).name, dirPath, context); } MonsterDBPlugin.LogDebug("Cloned " + ((Object)prefab).name + " as " + cloneName); }; clone = clone2.Create(); context?.LogInfo("Cloned " + ((Object)prefab).name + " as " + cloneName); return (Object)(object)clone != (Object)null; } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class BaseSpawnArea : Header { [YamlMember(Order = 6, Description = "If removed, will remove component")] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public SpawnAreaRef SpawnArea; [YamlMember(Order = 7)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public DestructibleRef Destructible; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 8)] public VisualRef Visuals; public override void Setup(GameObject prefab, bool isClone = false, string source = "") { base.Setup(prefab, isClone, source); Type = BaseType.SpawnArea; Prefab = ((Object)prefab).name; IsCloned = isClone; ClonedFrom = source; Visuals = new VisualRef(prefab); SetupSpawnArea(prefab); SetupDestructible(prefab); } public override void CopyFields(Header original) { base.CopyFields(original); if (original is BaseSpawnArea baseSpawnArea) { if (SpawnArea != null && baseSpawnArea.SpawnArea != null) { SpawnArea.ResetTo(baseSpawnArea.SpawnArea); } if (Visuals != null && baseSpawnArea.Visuals != null) { Visuals.ResetTo(baseSpawnArea.Visuals); } if (Destructible != null && baseSpawnArea.Destructible != null) { Destructible.ResetTo(baseSpawnArea.Destructible); } } } public override void Update() { GameObject prefab = PrefabManager.GetPrefab(Prefab); if (!((Object)(object)prefab == (Object)null)) { SpawnAreaManager.Save(prefab, IsCloned, ClonedFrom); UpdatePrefab(prefab); base.Update(); LoadManager.files.PrefabToUpdate = Prefab; LoadManager.files.Add(this); } } private void UpdatePrefab(GameObject prefab) { UpdateVisuals(prefab); UpdateSpawnArea(prefab); UpdateDestructible(prefab); } private void UpdateSpawnArea(GameObject prefab) { if (SpawnArea != null) { SpawnArea target = default(SpawnArea); if (!prefab.TryGetComponent(ref target)) { target = prefab.AddComponent(); } SpawnArea.UpdateFields(target, ((Object)prefab).name, log: true); } else { prefab.Remove(); } } private void UpdateDestructible(GameObject prefab) { Destructible target = default(Destructible); if (Destructible != null && prefab.TryGetComponent(ref target)) { Destructible.UpdateFields(target, ((Object)prefab).name, log: true); } } private void UpdateVisuals(GameObject prefab) { if (Visuals != null) { Visuals.Update(prefab, isInstance: false, isItem: false); } } private void SetupSpawnArea(GameObject prefab) { SpawnArea component = default(SpawnArea); if (prefab.TryGetComponent(ref component)) { SpawnArea = new SpawnAreaRef(component); } } private void SetupDestructible(GameObject prefab) { Destructible component = default(Destructible); if (prefab.TryGetComponent(ref component)) { Destructible = new DestructibleRef(component); } } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class DestructibleRef : Reference { public DestructibleType? m_destructibleType = (DestructibleType)1; public float? m_health = 1f; public DamageModifiers? m_damages; [YamlMember(Alias = "m_minDamageThreshold")] public float? m_minDamageTreshold; public int? m_minToolTier; public float? m_hitNoise; public float? m_destroyNoise; public bool? m_triggerPrivateArea; public float? m_ttl; public string m_spawnWhenDestroyed; [YamlMember(Description = "Effects")] public EffectListRef m_destroyedEffect; public EffectListRef m_hitEffect; public bool? m_autoCreateFragments; public DestructibleRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public DestructibleRef(Destructible component) { Setup(component); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class SpawnAreaManager { [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public static string Save(GameObject prefab, bool isClone = false, string source = "") { BaseSpawnArea original = LoadManager.GetOriginal(((Object)prefab).name); if (original != null) { return ConfigManager.Serialize(original); } BaseSpawnArea baseSpawnArea = new BaseSpawnArea(); baseSpawnArea.Setup(prefab, isClone, source); LoadManager.originals.Add(((Object)prefab).name, baseSpawnArea); return ConfigManager.Serialize(baseSpawnArea); } public static void Read(string filePath) { if (!File.Exists(filePath)) { return; } string data = File.ReadAllText(filePath); try { Header header = ConfigManager.Deserialize
(data); if (header.Type == BaseType.SpawnArea) { BaseSpawnArea baseSpawnArea = ConfigManager.Deserialize(data); baseSpawnArea.Update(); LoadManager.UpdateSync(); } } catch { MonsterDBPlugin.LogWarning("Failed to deserialize: " + Path.GetFileName(filePath)); } } public static bool Write(GameObject prefab, bool isClone = false, string source = "", string dirPath = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (string.IsNullOrEmpty(dirPath)) { dirPath = FileManager.ExportFolder; } string text = Path.Combine(dirPath, ((Object)prefab).name + ".yml"); BaseSpawnArea baseSpawnArea = new BaseSpawnArea(); baseSpawnArea.Setup(prefab, isClone, source); string contents = ConfigManager.Serialize(baseSpawnArea); File.WriteAllText(text, contents); context?.LogInfo("Exported Spawn Area " + ((Object)prefab).name); context?.LogInfo(text.RemoveRootPath()); return true; } public static bool TryClone(GameObject source, string cloneName, bool write = true, [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (CloneManager.prefabs.ContainsKey(cloneName)) { context?.LogWarning("Clone " + cloneName + " already exists"); return false; } Clone clone = new Clone(source, cloneName); clone.OnCreated += delegate(GameObject p) { MonsterDBPlugin.LogDebug("Cloned " + ((Object)source).name + " as " + cloneName); if (!Object.op_Implicit((Object)(object)p.GetComponent())) { p.AddComponent(); } if (write) { Write(p, isClone: true, ((Object)source).name, "", context); } }; clone.Create(); context?.LogInfo("Cloned " + ((Object)source).name + " as " + cloneName); return true; } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class SpawnAreaRef : Reference { [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class SpawnDataRef : Reference { public string m_prefab = ""; public float m_weight; public int m_maxLevel = 1; public int m_minLevel = 1; public SpawnDataRef() { } public SpawnDataRef(SpawnData data) { Setup(data); } public SpawnData ToSpawnData() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown if (string.IsNullOrEmpty(m_prefab)) { return new SpawnData(); } return new SpawnData { m_prefab = PrefabManager.GetPrefab(m_prefab), m_weight = m_weight, m_maxLevel = m_maxLevel, m_minLevel = m_minLevel }; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_prefabs; [YamlMember(Alias = "m_levelUpChance")] public float? m_levelupChance = 15f; public float? m_spawnIntervalSec = 30f; public float? m_triggerDistance = 256f; public bool? m_setPatrolSpawnPoint = true; public float? m_spawnRadius = 2f; public float? m_nearRadius = 10f; public float? m_farRadius = 1000f; public int? m_maxNear = 3; public int? m_maxTotal = 20; public bool? m_onGroundOnly; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public EffectListRef m_spawnEffects; public SpawnAreaRef() { } public SpawnAreaRef(SpawnArea component) { Setup(component); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class BaseSpawnData : Header { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 6)] public SpawnDataRef SpawnData; public void SetupData(SpawnData data) { SetupVersions(); Type = BaseType.SpawnData; Prefab = data.m_name; SpawnData = new SpawnDataRef(data); } public override void Update() { if (SpawnData != null) { if (SpawnManager.TryGetSpawnData(Prefab, out var data)) { SpawnData.UpdateFields(data, data.m_name, log: true); MonsterDBPlugin.LogInfo("Updated SpawnData: " + Prefab); } else { SpawnManager.QueueUpdate(this); MonsterDBPlugin.LogInfo("Queued Update SpawnData: " + Prefab); } if (!LoadManager.modified.ContainsKey(Prefab)) { LoadManager.modified.Add(this); } } } public void UpdateData(SpawnData data) { if (SpawnData != null) { SpawnData.UpdateFields(data, data.m_name, log: true); base.Update(); } } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class SpawnDataRef : Reference { public string m_name = ""; public bool m_enabled = true; public bool m_devDisabled; public string m_prefab = ""; [YamlMember(DefaultValuesHandling = DefaultValuesHandling.Preserve)] public Biome m_biome = (Biome)0; [YamlMember(Description = "Edge, Median, Everything")] public BiomeArea m_biomeArea = (BiomeArea)3; public int m_maxSpawned = 1; public float m_spawnInterval = 4f; public float m_spawnChance = 100f; public float m_spawnDistance = 10f; public float m_spawnRadiusMin; public float m_spawnRadiusMax; public string m_requiredGlobalKey = ""; public List m_requiredEnvironments = new List(); public int m_groupSizeMin = 1; public int m_groupSizeMax = 1; public float m_groupRadius = 3f; public bool m_spawnAtNight = true; public bool m_spawnAtDay = true; public float m_minAltitude = -1000f; public float m_maxAltitude = 1000f; public float m_minTilt; public float m_maxTilt = 35f; public bool m_inForest = true; public bool m_outsideForest = true; public bool m_inLava; public bool m_outsideLava = true; public bool m_canSpawnCloseToPlayer; public bool m_insidePlayerBase; public float m_minOceanDepth; public float m_maxOceanDepth; public bool m_huntPlayer; public float m_groundOffset = 0.5f; public float m_groundOffsetRandom; public float m_minDistanceFromCenter; public float m_maxDistanceFromCenter; public int m_maxLevel = 1; public int m_minLevel = 1; public float m_levelUpMinCenterDistance; public float m_overrideLevelupChance = -1f; public bool m_foldout; public SpawnDataRef() { }//IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) public SpawnDataRef(SpawnData data) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) Setup(data); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class SpawnManager { private static readonly SpawnSystemList SpawnList; private static Dictionary spawnRefs; private static readonly CustomSyncedValue sync; private static readonly Dictionary CachedSpawnData; private static readonly Dictionary updateList; static SpawnManager() { spawnRefs = new Dictionary(); CachedSpawnData = new Dictionary(); updateList = new Dictionary(); sync = new CustomSyncedValue(ConfigManager.ConfigSync, "MDB.ServerSync.SpawnList"); SpawnList = ((Component)MonsterDBPlugin.instance).gameObject.AddComponent(); sync.ValueChanged += OnSyncChange; } public static void Add(SpawnDataRef data) { spawnRefs[data.m_name] = data; } public static void QueueUpdate(BaseSpawnData data) { updateList[data.Prefab] = data; } public static List GetCachedSpawnDataIds() { return CachedSpawnData.Keys.ToList(); } public static bool TryGetSpawnData(string id, out SpawnData data) { return CachedSpawnData.TryGetValue(id, out data); } public static bool Export(string spawnerId, out string filepath) { filepath = ""; if (!CachedSpawnData.TryGetValue(spawnerId, out var value)) { return false; } BaseSpawnData baseSpawnData = new BaseSpawnData(); baseSpawnData.SetupData(value); string contents = ConfigManager.Serialize(baseSpawnData); filepath = Path.Combine(FileManager.ExportFolder, baseSpawnData.Prefab + ".yml"); File.WriteAllText(filepath, contents); return true; } public static void Start() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown foreach (SpawnDataRef value in spawnRefs.Values) { SpawnData val = new SpawnData(); value.UpdateFields(val, value.m_name, log: false); SpawnList.m_spawners.Add(val); } MonsterDBPlugin.LogInfo($"Loaded {spawnRefs.Count} spawn files"); } public static void Clear() { SpawnList.m_spawners.Clear(); spawnRefs.Clear(); } public static void Init(ZNet net) { if (net.IsServer()) { UpdateSync(); } } private static void UpdateSync() { if (Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer()) { string value = ConfigManager.Serialize(spawnRefs); sync.Value = value; } } private static void OnSyncChange() { //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Expected O, but got Unknown if (!Object.op_Implicit((Object)(object)ZNet.instance) || ZNet.instance.IsServer() || string.IsNullOrEmpty(sync.Value)) { return; } Dictionary dictionary = ConfigManager.Deserialize>(sync.Value); spawnRefs = dictionary; SpawnList.m_spawners.Clear(); foreach (KeyValuePair spawnRef in spawnRefs) { SpawnData val = new SpawnData(); spawnRef.Value.UpdateFields(val, spawnRef.Key, log: false); SpawnList.m_spawners.Add(val); } } public static void Update(SpawnDataRef info) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown SpawnList.m_spawners.RemoveAll([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (SpawnData x) => x.m_name == info.m_name); spawnRefs[info.m_name] = info; SpawnData val = new SpawnData(); info.UpdateFields(val, info.m_name, log: false); SpawnList.m_spawners.Add(val); UpdateSync(); MonsterDBPlugin.LogInfo("Updated Spawn Data: " + info.m_name); } public static void Setup() { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown Harmony harmony = MonsterDBPlugin.harmony; harmony.Patch((MethodBase)AccessTools.Method(typeof(SpawnSystem), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(SpawnManager), "Patch_SpawnSystem_Awake", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static void Patch_SpawnSystem_Awake(SpawnSystem __instance) { ValidateSpawns(); __instance.m_spawnLists.Add(SpawnList); CacheAndUpdateSpawners(__instance); } private static void CacheAndUpdateSpawners(SpawnSystem __instance) { List spawnLists = __instance.m_spawnLists; for (int i = 0; i < spawnLists.Count; i++) { SpawnSystemList val = spawnLists[i]; List spawners = val.m_spawners; for (int j = 0; j < spawners.Count; j++) { SpawnData val2 = spawners[j]; CachedSpawnData[val2.m_name] = val2; if (updateList.TryGetValue(val2.m_name, out var value)) { value.UpdateData(val2); } } } } private static void ValidateSpawns() { for (int i = 0; i < SpawnList.m_spawners.Count; i++) { SpawnData val = SpawnList.m_spawners[i]; if (val.m_enabled && (Object)(object)val.m_prefab == (Object)null) { MonsterDBPlugin.LogWarning(val.m_name + " prefab is null, disabling"); val.m_enabled = false; } } } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class Header { [YamlMember(Order = 0)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string GameVersion; [YamlMember(Order = 1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string ModVersion; [YamlMember(Order = 2)] public BaseType Type; [YamlMember(Order = 3)] public string Prefab = ""; [YamlMember(Order = 4)] public string ClonedFrom = ""; [YamlMember(Order = 5)] public bool IsCloned; public virtual void Setup(GameObject prefab, bool isClone = false, string source = "") { SetupVersions(); } protected void SetupVersions() { GameVersion = Version.GetVersionString(false); ModVersion = "0.3.5"; } public virtual void Update() { MonsterDBPlugin.LogInfo(LoadManager.resetting ? ("Reset " + Prefab) : ("Updated " + Prefab)); if (!LoadManager.modified.ContainsKey(Prefab)) { LoadManager.modified.Add(this); } } public virtual void CopyFields(Header original) { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public virtual VisualRef GetVisualData() { return null; } public virtual bool Clean() { if (!LoadManager.TryGetOriginal
(Prefab, out var output)) { return false; } if (output.GetType() != GetType()) { return false; } int num = 0; FieldInfo[] fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { object value = fieldInfo.GetValue(this); object value2 = fieldInfo.GetValue(output); if (value is Reference target && value2 is Reference reference) { num += reference.Clean(target, Prefab, log: true); } } MonsterDBPlugin.LogInfo($"[{Prefab}] cleaned {num} fields"); return num > 0; } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 0, 1, 1 })] public class NameToHeader : Dictionary { public void Add(Header header) { base[header.Prefab] = header; } public void AddRange(List
headers) { for (int i = 0; i < headers.Count; i++) { Header header = headers[i]; Add(header); } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 0, 1, 1, 1 })] public class HeaderToHeader : Dictionary> { public void Add(Header key, Header value) { if (!ContainsKey(key)) { base[key] = new List
(); } if (!base[key].Contains(value)) { base[key].Add(value); } } public bool TryGetKey(Header value, out Header key) { using (Enumerator enumerator = GetEnumerator()) { while (enumerator.MoveNext()) { KeyValuePair> current = enumerator.Current; if (!current.Value.Contains(value)) { continue; } key = current.Key; return true; } } key = null; return false; } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class LoadManager { public static readonly NameToHeader originals; public static readonly NameToHeader modified; public static readonly HeaderToHeader originalToModifiedList; private static readonly CustomSyncedValue sync; public static BaseAggregate files; public static bool resetting; static LoadManager() { //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Expected O, but got Unknown originals = new NameToHeader(); modified = new NameToHeader(); originalToModifiedList = new HeaderToHeader(); files = new BaseAggregate(); sync = new CustomSyncedValue(ConfigManager.ConfigSync, "MDB.ServerSync.Files", ""); sync.ValueChanged += OnSyncChange; Harmony harmony = MonsterDBPlugin.harmony; harmony.Patch((MethodBase)AccessTools.Method(typeof(Game), "Logout", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(LoadManager), "Patch_Game_Logout", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(FejdStartup), "OnStartGame", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(FileManager), "Start", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static void ReloadAll(ConsoleEventArgs args) { Reload(); args.Context.AddString("Reloaded all files"); } private static void Reload() { ResetAll
(); modified.Clear(); SpawnManager.Clear(); CloneManager.Clear(); FileManager.started = false; FileManager.Start(); LoadClones(); Load(); } private static void Patch_Game_Logout() { files = new BaseAggregate(); ResetAll
(); modified.Clear(); SpawnManager.Clear(); CloneManager.Clear(); RaidManager.Reset(); FileManager.started = false; } [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public static T GetOriginal<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>(string prefabName) where T : Header { Header value; return originals.TryGetValue(prefabName, out value) ? (value as T) : null; } public static List GetOriginalKeys<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>() where T : Header { return (from x in originals where x.Value is T select x.Key).ToList(); } public static List GetOriginals<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>() where T : Header { return (from x in originals where x.Value is T select x.Value as T).ToList(); } public static bool TryGetOriginal<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>(string prefabName, out T output) where T : Header { output = null; if (!originals.TryGetValue(prefabName, out var value)) { return false; } if (!(value is T val)) { return false; } output = val; return true; } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] public static void ResetAll() where T : Header { if (modified.Count <= 0 || originals.Count <= 0) { return; } resetting = true; foreach (Header value2 in modified.Values) { if (value2 is T && originals.TryGetValue(value2.Prefab, out var value)) { value2.CopyFields(value); value2.Update(); } } resetting = false; } public static bool Reset<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>(string prefabName) where T : Header { if (!TryGetOriginal(prefabName, out var output)) { return false; } if (!modified.TryGetValue(prefabName, out var value)) { return false; } if (value == null) { return false; } value.CopyFields(output); value.Update(); return true; } public static void UpdateSync() { if (Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer()) { sync.Value = ConfigManager.Serialize(files, full: false); } } private static void OnSyncChange() { if (!Object.op_Implicit((Object)(object)ZNet.instance) || ZNet.instance.IsServer() || string.IsNullOrEmpty(sync.Value)) { return; } try { BaseAggregate baseAggregate = ConfigManager.Deserialize(sync.Value); Header header; if (string.IsNullOrEmpty(baseAggregate.PrefabToUpdate)) { ResetAll
(); modified.Clear(); modified.AddRange(baseAggregate.Load()); LoadClones(); Load(); } else if (baseAggregate.GetPrefabToUpdate(out header)) { header.Update(); } if (baseAggregate.translations == null) { return; } foreach (KeyValuePair> translation in baseAggregate.translations) { LocalizationManager.AddWords(translation.Key, translation.Value); } } catch { MonsterDBPlugin.LogWarning("Failed to deserialize server files"); } } private static void LoadClones() { Dictionary dictionary = new Dictionary(); List
list = modified.Values.ToList(); for (int i = 0; i < list.Count; i++) { Header header = list[i]; if (!header.IsCloned) { continue; } GameObject prefab = PrefabManager.GetPrefab(header.ClonedFrom); if ((Object)(object)prefab == (Object)null) { continue; } if (dictionary.ContainsKey(header.Type)) { BaseType type = header.Type; int value = dictionary[type] + 1; dictionary[type] = value; } else { dictionary[header.Type] = 1; } GameObject clone; switch (header.Type) { case BaseType.Human: CreatureManager.Clone(prefab, header.Prefab, write: false); break; case BaseType.Humanoid: CreatureManager.Clone(prefab, header.Prefab, write: false); break; case BaseType.Character: CreatureManager.Clone(prefab, header.Prefab, write: false); break; case BaseType.Egg: if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { ItemManager.TryCreateItem(prefab, header.Prefab, out clone, write: false); } else { EggManager.TryClone(prefab, header.Prefab, write: false); } break; case BaseType.Item: if (!Object.op_Implicit((Object)(object)prefab.GetComponent())) { ItemManager.TryCreateItem(prefab, header.Prefab, out clone, write: false); } else { ItemManager.TryClone(prefab, header.Prefab, out clone, write: false); } break; case BaseType.Fish: FishManager.TryClone(prefab, header.Prefab, write: false); break; case BaseType.Projectile: ProjectileManager.TryClone(prefab, header.Prefab, out clone, write: false); break; case BaseType.Ragdoll: RagdollManager.TryClone(prefab, header.Prefab, out clone, write: false); break; case BaseType.SpawnAbility: SpawnAbilityManager.TryClone(prefab, header.Prefab, out clone, write: false); break; case BaseType.Visual: VisualManager.TryClone(prefab, header.Prefab, out clone, write: false); break; case BaseType.CreatureSpawner: CreatureSpawnerManager.TryClone(prefab, header.Prefab, write: false); break; case BaseType.SpawnArea: SpawnAreaManager.TryClone(prefab, header.Prefab, write: false); break; } } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("Loading clones: "); foreach (KeyValuePair item in dictionary) { stringBuilder.Append($"{item.Value} {item.Key}, "); } stringBuilder.Append($"(total: {dictionary.Sum([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (KeyValuePair x) => x.Value)})"); MonsterDBPlugin.LogInfo(stringBuilder.ToString()); } private static void Load() { List
list = (from x in modified.Values orderby x.Type != BaseType.SpawnAbility, x.Type != BaseType.Projectile, x.Type != BaseType.Item select x).ToList(); Dictionary dictionary = new Dictionary(); for (int i = 0; i < list.Count; i++) { Header header = list[i]; if (header.Type != 0) { header.Update(); if (dictionary.ContainsKey(header.Type)) { BaseType type = header.Type; int value = dictionary[type] + 1; dictionary[type] = value; } else { dictionary[header.Type] = 1; } } } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("Modified: "); foreach (KeyValuePair item in dictionary) { stringBuilder.Append($"{item.Value} {item.Key}, "); } stringBuilder.Append($"(total: {dictionary.Sum([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (KeyValuePair x) => x.Value)})"); MonsterDBPlugin.LogInfo(stringBuilder.ToString()); } public static void Init(ZNet net) { if (net.IsServer()) { UpdateSync(); FileManager.SetupFileWatcher(); } } [HarmonyPriority(0)] public static void Start() { LoadClones(); Load(); SpawnManager.Start(); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class Snapshot { private const int layer = 3; public static void Run(ConsoleEventArgs args) { //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Specify prefab"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); return; } float @float = args.GetFloat(3, 1.3f); float float2 = args.GetFloat(4); float float3 = args.GetFloat(5, 180f); float float4 = args.GetFloat(6); Quaternion value = Quaternion.Euler(float2, float3, float4); if (TryCreate(prefab, out var icon, @float, value)) { ((Object)icon).name = ((Object)prefab).name + "_icon"; byte[] bytes = ImageConversion.EncodeToPNG(icon.texture); string text = Path.Combine(FileManager.ExportFolder, ((Object)icon).name + ".png"); File.WriteAllBytes(text, bytes); args.Context.LogInfo("Exported PNG for " + ((Object)prefab).name); args.Context.LogInfo(text.RemoveRootPath()); TextureManager.RegisterNewIcon(icon); } else { args.Context.LogWarning("Failed to export PNG for " + ((Object)prefab).name); } } private static void CleanupVisual(GameObject visual) { Transform[] componentsInChildren = visual.GetComponentsInChildren(); foreach (Transform val in componentsInChildren) { ((Component)val).gameObject.layer = 3; } ParticleSystem[] componentsInChildren2 = visual.GetComponentsInChildren(); foreach (ParticleSystem val2 in componentsInChildren2) { val2.Stop(); } } private static bool TryCreate(GameObject prefab, out Sprite icon, float lightIntensity = 1.3f, Quaternion? cameraRotation = null) { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0092: 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_00be: 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_012a: 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_0181: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_020b: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_024b: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0252: 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_025e: 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_026e: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_0272: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_02e4: Unknown result type (might be due to invalid IL or missing references) //IL_0329: Unknown result type (might be due to invalid IL or missing references) //IL_033a: Unknown result type (might be due to invalid IL or missing references) //IL_033f: Unknown result type (might be due to invalid IL or missing references) //IL_0376: Unknown result type (might be due to invalid IL or missing references) //IL_037d: Expected O, but got Unknown //IL_039b: Unknown result type (might be due to invalid IL or missing references) //IL_03d7: Unknown result type (might be due to invalid IL or missing references) //IL_03dc: Unknown result type (might be due to invalid IL or missing references) //IL_03e6: Unknown result type (might be due to invalid IL or missing references) icon = null; if ((Object)(object)prefab == (Object)null) { return false; } if (!prefab.GetComponentsInChildren().Any() && !prefab.GetComponentsInChildren().Any()) { return false; } Camera component = new GameObject("CameraIcon", new Type[1] { typeof(Camera) }).GetComponent(); component.backgroundColor = Color.clear; component.clearFlags = (CameraClearFlags)2; ((Component)component).transform.position = new Vector3(10000f, 10000f, 10000f); ((Component)component).transform.rotation = (Quaternion)(((??)cameraRotation) ?? Quaternion.Euler(0f, 180f, 0f)); component.fieldOfView = 0.5f; component.farClipPlane = 100000f; component.cullingMask = 8; Light component2 = new GameObject("LightIcon", new Type[1] { typeof(Light) }).GetComponent(); ((Component)component2).transform.position = new Vector3(10000f, 10000f, 10000f); ((Component)component2).transform.rotation = Quaternion.Euler(5f, 180f, 5f); component2.type = (LightType)1; component2.cullingMask = 8; component2.intensity = lightIntensity; GameObject val = Object.Instantiate(prefab); CleanupVisual(val); val.transform.position = Vector3.zero; val.transform.rotation = new Quaternion(0f, 180f, 0f, 0f); ((Object)val).name = ((Object)prefab).name; Renderer[] array; if (!Object.op_Implicit((Object)(object)val.GetComponent())) { Renderer[] componentsInChildren = (Renderer[])(object)val.GetComponentsInChildren(); array = componentsInChildren; } else { array = val.GetComponentsInChildren(); } Renderer[] source = array; Vector3 val2 = source.Aggregate(Vector3.positiveInfinity, [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (Vector3 cur, Renderer renderer) => { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) Bounds bounds2 = renderer.bounds; return Vector3.Min(cur, ((Bounds)(ref bounds2)).min); }); Vector3 val3 = source.Aggregate(Vector3.negativeInfinity, [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (Vector3 cur, Renderer renderer) => { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) Bounds bounds = renderer.bounds; return Vector3.Max(cur, ((Bounds)(ref bounds)).max); }); val.transform.position = new Vector3(10000f, 10000f, 10000f) - (val2 + val3) / 2f; Vector3 val4 = val3 - val2; TimedDestruction val5 = val.AddComponent(); val5.Trigger(1f); Rect val6 = default(Rect); ((Rect)(ref val6))..ctor(0f, 0f, 128f, 128f); component.targetTexture = RenderTexture.GetTemporary((int)((Rect)(ref val6)).width, (int)((Rect)(ref val6)).height); component.aspect = 1f; component.fieldOfView = 20f; float num = Mathf.Max(val4.x, val4.y) + 0.1f; float num2 = num / Mathf.Tan(component.fieldOfView * ((float)Math.PI / 180f)) * 1.1f; ((Component)component).transform.position = new Vector3(10000f, 10000f, 10000f) + new Vector3(0f, 0f, num2); component.Render(); RenderTexture active = RenderTexture.active; RenderTexture.active = component.targetTexture; Texture2D val7 = new Texture2D((int)((Rect)(ref val6)).width, (int)((Rect)(ref val6)).height, (TextureFormat)4, false); val7.ReadPixels(new Rect(0f, 0f, (float)(int)((Rect)(ref val6)).width, (float)(int)((Rect)(ref val6)).height), 0, 0); val7.Apply(); RenderTexture.active = active; icon = Sprite.Create(val7, new Rect(0f, 0f, (float)(int)((Rect)(ref val6)).width, (float)(int)((Rect)(ref val6)).height), Vector2.one / 2f); ((Component)component2).gameObject.SetActive(false); component.targetTexture.Release(); ((Component)component).gameObject.SetActive(false); val.SetActive(false); if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { ZNetScene.instance.Destroy(val); } else { Object.DestroyImmediate((Object)(object)val); } Object.Destroy((Object)(object)component); Object.Destroy((Object)(object)component2); Object.Destroy((Object)(object)((Component)component).gameObject); Object.Destroy((Object)(object)((Component)component2).gameObject); return true; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class TexturePackage { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] private class ChunkBuffer { public string TransferId = ""; public int TotalChunks; public byte[][] Chunks; public int Received; public int ReceivedBytes; public int LastLoggedPercent = -1; public void Add(int index, byte[] chunk) { if (Chunks[index] == null) { Chunks[index] = chunk; Received++; ReceivedBytes += chunk.Length; } } public void Assemble() { //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown int num = 0; for (int i = 0; i < TotalChunks; i++) { num += Chunks[i].Length; } byte[] array = new byte[num]; int num2 = 0; for (int j = 0; j < TotalChunks; j++) { byte[] array2 = Chunks[j]; Buffer.BlockCopy(array2, 0, array, num2, array2.Length); num2 += array2.Length; } _chunkBuffers.Remove(TransferId); ZPackage val = new ZPackage(array); ZPackage val2 = val.ReadCompressedPackage(); int num3 = val2.ReadInt(); for (int k = 0; k < num3; k++) { string fileName = val2.ReadString(); byte[] bytes = val2.ReadByteArray(); TextureData textureData = new TextureData(fileName, bytes); TextureManager.Add(textureData); textureData.Write(); } MonsterDBPlugin.LogInfo($"TexturePack completed: {TotalChunks} chunks, " + $"{(float)ReceivedBytes / 1024f:F1} KB received"); } } private const int MAX_COMPRESSED_CHUNK_SIZE = 65536; private static readonly Dictionary _chunkBuffers; static TexturePackage() { _chunkBuffers = new Dictionary(); } public static void Setup() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown Harmony harmony = MonsterDBPlugin.harmony; harmony.Patch((MethodBase)AccessTools.Method(typeof(ZNet), "OnNewConnection", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(TexturePackage), "Patch_ZNet_OnNewConnection", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } private static void Patch_ZNet_OnNewConnection(ZNet __instance, ZNetPeer peer) { peer.m_rpc.Register("RPC_ReceiveTextureNames", (Action)RPC_ReceiveTextureNames); peer.m_rpc.Register("RPC_ReceiveTexturesCompressed", (Action)RPC_ReceiveTexturesCompressed); peer.m_rpc.Register("RPC_ReceiveTextureChunk", (Action)RPC_ReceiveTextureChunk); if (!__instance.IsServer()) { SendTextureNames(peer.m_rpc); } } public static void SendTextureNames(ZRpc rpc) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown Dictionary textureData = TextureManager.GetTextureData(); ZPackage val = new ZPackage(); val.Write(textureData.Count); foreach (string key in textureData.Keys) { val.Write(key); } rpc.Invoke("RPC_ReceiveTextureNames", new object[1] { val }); } private static void RPC_ReceiveTextureNames(ZRpc rpc, ZPackage pkg) { List list = new List(); int num = pkg.ReadInt(); for (int i = 0; i < num; i++) { string item = pkg.ReadString(); list.Add(item); } SendTextures(rpc, list); } private static void RPC_ReceiveTexturesCompressed(ZRpc rpc, ZPackage pkg) { pkg = pkg.ReadCompressedPackage(); int num = pkg.ReadInt(); for (int i = 0; i < num; i++) { string fileName = pkg.ReadString(); byte[] bytes = pkg.ReadByteArray(); TextureData textureData = new TextureData(fileName, bytes); TextureManager.Add(textureData); textureData.Write(); } } private static void SendTextures(ZRpc rpc, List texturesToIgnore) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Expected O, but got Unknown //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Expected O, but got Unknown Dictionary textureData = TextureManager.GetTextureData(); foreach (string item in texturesToIgnore) { textureData.Remove(item); } if (textureData.Count <= 0) { return; } ZPackage val = new ZPackage(); val.Write(textureData.Count); foreach (KeyValuePair item2 in textureData) { val.Write(item2.Key); val.Write(item2.Value.m_bytes); } ZPackage val2 = new ZPackage(); val2.WriteCompressed(val); byte[] array = val2.GetArray(); int num = array.Length; int num2 = Mathf.CeilToInt((float)num / 65536f); string text = Guid.NewGuid().ToString(); MonsterDBPlugin.LogInfo($"TexturePack: sending {num} bytes in {num2} chunks"); for (int i = 0; i < num2; i++) { int num3 = i * 65536; int num4 = Mathf.Min(65536, num - num3); byte[] array2 = new byte[num4]; Buffer.BlockCopy(array, num3, array2, 0, num4); ZPackage val3 = new ZPackage(); val3.Write(text); val3.Write(i); val3.Write(num2); val3.Write(array2); rpc.Invoke("RPC_ReceiveTextureChunk", new object[1] { val3 }); } } private static void RPC_ReceiveTextureChunk(ZRpc rpc, ZPackage pkg) { string text = pkg.ReadString(); int num = pkg.ReadInt(); int num2 = pkg.ReadInt(); byte[] array = pkg.ReadByteArray(); if (!_chunkBuffers.TryGetValue(text, out var value)) { ChunkBuffer chunkBuffer = new ChunkBuffer(); chunkBuffer.TransferId = text; chunkBuffer.TotalChunks = num2; chunkBuffer.Chunks = new byte[num2][]; value = chunkBuffer; _chunkBuffers.Add(text, value); } value.Add(num, array); int num3 = Mathf.FloorToInt((float)value.Received / (float)value.TotalChunks * 100f); if (num3 >= value.LastLoggedPercent + 10 || value.Received == value.TotalChunks) { value.LastLoggedPercent = num3; MonsterDBPlugin.LogInfo($"TexturePack | {value.Received,3}/{value.TotalChunks,-3} | {num3,3}% | chunk {num + 1,2} | {array.Length,6} bytes | recv {(float)value.ReceivedBytes / 1024f,7:F1} KB"); } if (value.Received >= value.TotalChunks) { value.Assemble(); } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class TextureData { public string m_filePath; public readonly string m_name; public readonly byte[] m_bytes; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] private Texture2D m_tex; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] private Sprite m_sprite; public TextureData(string filePath) { m_filePath = filePath; m_name = Path.GetFileNameWithoutExtension(filePath); m_bytes = File.ReadAllBytes(filePath); } public TextureData(string fileName, byte[] bytes) { m_filePath = "Server"; m_name = fileName; m_bytes = bytes; } public Texture ToTex([<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Texture2D original) { //IL_0039: 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_0053: Expected O, but got Unknown if ((Object)(object)m_tex != (Object)null) { return (Texture)(object)m_tex; } int num = ((original != null) ? ((Texture)original).width : 4); int num2 = ((original != null) ? ((Texture)original).height : 4); num = ((original == null) ? 4 : ((int)original.format)); Texture2D val = new Texture2D(num, num2, (TextureFormat)num, original != null && ((Texture)original).mipmapCount > 1); val.LoadImage4x(m_bytes); val.Apply(); ((Object)val).name = m_name; m_tex = val; return (Texture)(object)val; } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public Sprite ToSprite(Sprite original) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)m_sprite != (Object)null) { return m_sprite; } Texture obj = ToTex((original != null) ? original.texture : null); Texture2D val = (Texture2D)(object)((obj is Texture2D) ? obj : null); if ((Object)(object)val == (Object)null) { return original; } Sprite val2 = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), Vector2.zero); ((Object)val2).name = m_name; m_sprite = val2; return val2; } public void Write(string filepath = "") { if (string.IsNullOrEmpty(filepath)) { string text = Path.Combine(FileManager.ImportFolder, "textures"); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } filepath = Path.Combine(text, m_name + ".png"); } File.WriteAllBytes(filepath, m_bytes); } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class TextureManager { private static readonly Dictionary m_cachedTextures; private static readonly Dictionary m_cachedSprites; private static readonly Dictionary m_customs; static TextureManager() { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown m_cachedSprites = new Dictionary(); m_cachedTextures = new Dictionary(); m_customs = new Dictionary(); Harmony harmony = MonsterDBPlugin.harmony; harmony.Patch((MethodBase)AccessTools.Method(typeof(ZoneSystem), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(TextureManager), "WriteAll", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static void ExportTextureOrPrefabTextures(Terminal context, string input) { if (string.IsNullOrEmpty(input)) { context.LogWarning("Specify name"); return; } if (GetAllTextures().TryGetValue(input, out var value)) { Export((Texture)(object)value, FileManager.ExportFolder); context.AddString("Exported texture: " + ((Object)value).name); return; } GameObject prefab = PrefabManager.GetPrefab(input); if ((Object)(object)prefab == (Object)null) { context.LogWarning("Failed to find prefab: " + input); return; } HashSet allMaterials = prefab.GetAllMaterials(); int count = 0; foreach (Material item in allMaterials) { Save(item, FileManager.ExportFolder, ref count); } context.AddString($"Exported prefab: {((Object)prefab).name} textures (total: {count})"); } [Obsolete] public static void ExportMainTextures(ConsoleEventArgs args) { string stringFrom = args.GetStringFrom(2); if (string.IsNullOrEmpty(stringFrom)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(stringFrom); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + stringFrom); return; } HashSet allMaterials = prefab.GetAllMaterials(); foreach (Material item in allMaterials) { Save(item, FileManager.ExportFolder); } } [Obsolete] public static void ExportTexture(ConsoleEventArgs args) { string stringFrom = args.GetStringFrom(2); Texture2D value; if (string.IsNullOrEmpty(stringFrom)) { args.Context.LogWarning("Invalid parameters"); } else if (!m_cachedTextures.TryGetValue(stringFrom, out value)) { args.Context.LogWarning("Failed to find texture"); } else { Export((Texture)(object)value, FileManager.ExportFolder); } } [Obsolete] public static List GetTextureOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : m_cachedTextures.Keys.ToList()); if (1 == 0) { } return result; } [Obsolete] public static void SearchTextures(ConsoleEventArgs args) { string stringFrom = args.GetStringFrom(2); List list = m_cachedTextures.Keys.ToList(); for (int i = 0; i < list.Count; i++) { string text = list[i]; if (text.ToLower().Contains(stringFrom.ToLower())) { args.Context.AddString("- " + text); MonsterDBPlugin.LogInfo(text); } } } [Obsolete] public static void SearchSprites(ConsoleEventArgs args) { string stringFrom = args.GetStringFrom(2); List list = m_cachedSprites.Keys.ToList(); for (int i = 0; i < list.Count; i++) { string text = list[i]; if (text.ToLower().Contains(stringFrom.ToLower())) { args.Context.AddString("- " + text); MonsterDBPlugin.LogInfo(text); } } } [Obsolete] public static List GetSpriteOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : GetSpriteNames()); if (1 == 0) { } return result; } public static List GetSpriteNames() { return m_cachedSprites.Keys.ToList(); } public static void SetupFileWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(FileManager.ImportFolder, "*.png"); fileSystemWatcher.Created += OnNewImage; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private static void OnNewImage(object sender, FileSystemEventArgs e) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(e.FullPath); if (!m_customs.ContainsKey(fileNameWithoutExtension)) { ReadTexture(e.FullPath); MonsterDBPlugin.LogInfo("Loaded " + Path.GetFileName(e.FullPath)); } } public static void ExportSprite(Terminal context, string input) { if (string.IsNullOrEmpty(input)) { context.LogWarning("Specify sprite name"); return; } Sprite sprite = GetSprite(input, null); if ((Object)(object)sprite == (Object)null) { context.LogWarning("Failed to find sprite: " + input); } else { ExportSprite(sprite, FileManager.ExportFolder); } } [Obsolete] public static void ExportSprite(ConsoleEventArgs args) { string stringFrom = args.GetStringFrom(2); if (string.IsNullOrEmpty(stringFrom)) { args.Context.LogWarning("Invalid parameters"); return; } Sprite sprite = GetSprite(stringFrom, null); if ((Object)(object)sprite == (Object)null) { args.Context.LogWarning("Failed to find sprite: " + stringFrom); } else { ExportSprite(sprite, FileManager.ExportFolder); } } public static HashSet GetAllMaterials(this GameObject prefab) { Renderer[] componentsInChildren = prefab.GetComponentsInChildren(true); HashSet hashSet = new HashSet(); foreach (Renderer val in componentsInChildren) { for (int j = 0; j < val.sharedMaterials.Length; j++) { Material val2 = val.sharedMaterials[j]; if (!((Object)(object)val2 == (Object)null)) { hashSet.Add(val2); } } } return hashSet; } public static bool TryGetTexture(string name, out Texture2D texture) { if (m_cachedTextures.TryGetValue(name, out texture)) { return true; } return false; } public static void Start() { string[] files = Directory.GetFiles(FileManager.ImportFolder, "*.png", SearchOption.AllDirectories); foreach (string filePath in files) { ReadTexture(filePath); } MonsterDBPlugin.LogInfo($"Loaded {files.Length} PNG files"); SetupFileWatcher(); } public static void WriteAll() { GetAllTextures(); string path = "Resources.Textures.Names.txt"; string path2 = Path.Combine(ConfigManager.DirectoryPath, path); string[] contents = m_cachedTextures.Keys.ToArray(); File.WriteAllLines(path2, contents); GetAllSprites(); path = "Resources.Sprites.Names.txt"; path2 = Path.Combine(ConfigManager.DirectoryPath, path); contents = m_cachedSprites.Keys.ToArray(); File.WriteAllLines(path2, contents); } public static Dictionary GetTextureData() { return m_customs; } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public static Texture GetTexture([<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] string name, Texture defaultValue) { if (name == "null") { return null; } if (string.IsNullOrEmpty(name)) { return defaultValue; } if (m_cachedTextures.TryGetValue(name, out var value)) { return (Texture)(object)value; } if (m_customs.TryGetValue(name, out var value2)) { return value2.ToTex((Texture2D)(object)((defaultValue is Texture2D) ? defaultValue : null)); } MonsterDBPlugin.LogDebug("Failed to find texture: " + name); return defaultValue; } public static Dictionary GetAllTextures(bool clear = false) { if (clear) { m_cachedTextures.Clear(); } if (m_cachedTextures.Count > 0) { return m_cachedTextures; } Texture2D[] array = Resources.FindObjectsOfTypeAll(); foreach (Texture2D val in array) { if (((Object)val).GetInstanceID() >= 0 && !m_cachedTextures.ContainsKey(((Object)val).name)) { m_cachedTextures[((Object)val).name] = val; } } return m_cachedTextures; } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public static Sprite GetSprite([<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] string name, Sprite defaultValue) { if (string.IsNullOrEmpty(name)) { return defaultValue; } if (GetAllSprites().TryGetValue(name, out var value)) { return value; } if (m_customs.TryGetValue(name, out var value2)) { return value2.ToSprite(defaultValue); } MonsterDBPlugin.LogDebug("Failed to find sprite: " + name); return defaultValue; } public static Dictionary GetAllSprites(bool clear = false) { if (clear) { m_cachedSprites.Clear(); } if (m_cachedSprites.Count > 0) { return m_cachedSprites; } Sprite[] array = Resources.FindObjectsOfTypeAll(); foreach (Sprite val in array) { if (((Object)val).GetInstanceID() >= 0) { m_cachedSprites[((Object)val).name] = val; } } return m_cachedSprites; } private static void Export(Texture texture, string path) { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown //IL_0083: Unknown result type (might be due to invalid IL or missing references) string name = ((Object)texture).name; string text = Path.Combine(path, name + ".png"); if (File.Exists(text)) { return; } try { RenderTexture temporary = RenderTexture.GetTemporary(texture.width, texture.height, 0, (RenderTextureFormat)7, (RenderTextureReadWrite)2); Graphics.Blit(texture, temporary); RenderTexture active = RenderTexture.active; RenderTexture.active = temporary; Texture2D val = new Texture2D(texture.width, texture.height); val.ReadPixels(new Rect(0f, 0f, (float)((Texture)temporary).width, (float)((Texture)temporary).height), 0, 0); val.Apply(); RenderTexture.active = active; RenderTexture.ReleaseTemporary(temporary); byte[] bytes = ImageConversion.EncodeToPNG(val); File.WriteAllBytes(text, bytes); MonsterDBPlugin.LogInfo("Exported texture: " + text); } catch { MonsterDBPlugin.LogWarning("Failed to save texture: " + name); } } public static void ExportSprite(Sprite sprite, string path) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Expected O, but got Unknown //IL_0110: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)sprite == (Object)null || (Object)(object)sprite.texture == (Object)null) { return; } string name = ((Object)sprite).name; string text = Path.Combine(path, name + ".png"); if (File.Exists(text)) { return; } try { Texture2D texture = sprite.texture; Rect textureRect = sprite.textureRect; if (((Rect)(ref textureRect)).x == 0f && ((Rect)(ref textureRect)).y == 0f && Mathf.Approximately(((Rect)(ref textureRect)).width, (float)((Texture)sprite.texture).width) && Mathf.Approximately(((Rect)(ref textureRect)).height, (float)((Texture)sprite.texture).height)) { Export((Texture)(object)texture, path); return; } RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)7, (RenderTextureReadWrite)2); Graphics.Blit((Texture)(object)texture, temporary); RenderTexture active = RenderTexture.active; RenderTexture.active = temporary; Texture2D val = new Texture2D((int)((Rect)(ref textureRect)).width, (int)((Rect)(ref textureRect)).height); val.ReadPixels(textureRect, 0, 0); val.Apply(); RenderTexture.active = active; RenderTexture.ReleaseTemporary(temporary); byte[] bytes = ImageConversion.EncodeToPNG(val); File.WriteAllBytes(text, bytes); MonsterDBPlugin.LogInfo("Exported sprite: " + text); } catch { MonsterDBPlugin.LogWarning("Failed to save sprite: " + name); } } private static void Save(Material material, string path, ref int count) { if ((Object)(object)material == (Object)null || ((Object)material).GetInstanceID() < 0) { return; } if (material.HasProperty(ShaderRef._FlowMaskTex)) { Texture texture = material.GetTexture(ShaderRef._FlowMaskTex); if ((Object)(object)texture != (Object)null) { Export(texture, path); count++; } } if (material.HasProperty(ShaderRef._BumpMap)) { Texture texture2 = material.GetTexture(ShaderRef._BumpMap); if ((Object)(object)texture2 != (Object)null) { Export(texture2, path); count++; } } if (material.HasProperty(ShaderRef._EmissionMap)) { Texture texture3 = material.GetTexture(ShaderRef._EmissionMap); if ((Object)(object)texture3 != (Object)null) { Export(texture3, path); count++; } } Texture mainTexture = material.mainTexture; if ((Object)(object)mainTexture != (Object)null) { Export(mainTexture, path); count++; } } private static bool Save(Material material, string path) { if ((Object)(object)material == (Object)null) { return false; } if (((Object)material).GetInstanceID() < 0) { return false; } if (material.HasProperty(ShaderRef._FlowMaskTex)) { Texture texture = material.GetTexture(ShaderRef._FlowMaskTex); if ((Object)(object)texture != (Object)null) { Export(texture, path); } } if (material.HasProperty(ShaderRef._BumpMap)) { Texture texture2 = material.GetTexture(ShaderRef._BumpMap); if ((Object)(object)texture2 != (Object)null) { Export(texture2, path); } } if (material.HasProperty(ShaderRef._EmissionMap)) { Texture texture3 = material.GetTexture(ShaderRef._EmissionMap); if ((Object)(object)texture3 != (Object)null) { Export(texture3, path); } } Texture mainTexture = material.mainTexture; if ((Object)(object)mainTexture == (Object)null) { return false; } Export(mainTexture, path); return true; } private static void ReadTexture(string filePath) { if (File.Exists(filePath)) { TextureData textureData = new TextureData(filePath); m_customs[textureData.m_name] = textureData; } } public static void Add(TextureData data) { m_customs[data.m_name] = data; } public static void RegisterNewIcon(Sprite icon) { m_cachedSprites[((Object)icon).name] = icon; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class TextureRef { [CompilerGenerated] [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string P; private static readonly Texture m_emptyTex = (Texture)new Texture2D(4, 4); [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] private Texture tex; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public Texture m_tex { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] get { if ((Object)(object)tex != (Object)null) { return tex; } if (TextureManager.GetAllTextures().TryGetValue(P, out var value)) { tex = (Texture)(object)value; return tex; } MonsterDBPlugin.LogWarning("Failed to find reference texture: " + P); return m_emptyTex; } } public TextureRef(string textureName) { P = textureName; base..ctor(); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class BaseVisual : Header { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [YamlMember(Order = 6)] public VisualRef Visuals; public override void Setup(GameObject prefab, bool isClone = false, string source = "") { base.Setup(prefab, isClone, source); Type = BaseType.Visual; Prefab = ((Object)prefab).name; IsCloned = isClone; ClonedFrom = source; SetupVisuals(prefab); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public override VisualRef GetVisualData() { return Visuals; } public override void CopyFields(Header original) { base.CopyFields(original); if (original is BaseVisual baseVisual && Visuals != null && baseVisual.Visuals != null) { Visuals.ResetTo(baseVisual.Visuals); } } public override void Update() { GameObject prefab = PrefabManager.GetPrefab(Prefab); if (!((Object)(object)prefab == (Object)null)) { UpdatePrefab(prefab); base.Update(); LoadManager.files.PrefabToUpdate = Prefab; LoadManager.files.Add(this); } } private void SetupVisuals(GameObject prefab) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) Visuals = new VisualRef { m_scale = prefab.transform.localScale }; Renderer[] componentsInChildren = prefab.GetComponentsInChildren(true); if (componentsInChildren.Length != 0) { Visuals.m_renderers = componentsInChildren.ToRendererRefArray(); } ParticleSystem[] componentsInChildren2 = prefab.GetComponentsInChildren(true); if (componentsInChildren2.Length != 0) { Visuals.m_particleSystems = componentsInChildren2.ToParticleSystemRefArray(); } Light[] componentsInChildren3 = prefab.GetComponentsInChildren(true); if (componentsInChildren3.Length != 0) { Visuals.m_lights = componentsInChildren3.ToLightRefList(); } } private void UpdatePrefab(GameObject prefab) { Visuals?.Update(prefab, isInstance: false, Object.op_Implicit((Object)(object)prefab.GetComponent())); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class LevelSetupRef : Reference { public float m_scale = 1f; public float m_hue; public float m_saturation; public float m_value; public bool m_setEmissiveColor; public string m_emissiveColor = "#FFFFFFFF"; public string m_enableObject = ""; public LevelSetupRef() { } public LevelSetupRef(LevelSetup setup) { //IL_0088: Unknown result type (might be due to invalid IL or missing references) m_scale = setup.m_scale; m_value = setup.m_value; GameObject enableObject = setup.m_enableObject; m_enableObject = ((enableObject != null) ? ((Object)enableObject).name : null) ?? ""; m_hue = setup.m_hue; m_saturation = setup.m_saturation; m_setEmissiveColor = setup.m_setEmissiveColor; m_emissiveColor = setup.m_emissiveColor.ToRGBAString(); } public void Set(LevelSetup setup, Dictionary renderers) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) setup.m_scale = m_scale; setup.m_hue = m_hue; setup.m_saturation = m_saturation; setup.m_value = m_value; setup.m_setEmissiveColor = m_setEmissiveColor; setup.m_emissiveColor = m_emissiveColor.FromHexOrRGBA(Color.white); if (!string.IsNullOrEmpty(m_enableObject) && renderers.TryGetValue(m_enableObject, out var value)) { setup.m_enableObject = ((Component)value).gameObject; } } public override bool Equals<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>(T other) { if (!(other is LevelSetupRef levelSetupRef)) { return false; } return m_scale.Equals(levelSetupRef.m_scale) && m_hue.Equals(levelSetupRef.m_hue) && m_saturation.Equals(levelSetupRef.m_saturation) && m_value.Equals(levelSetupRef.m_value) && m_setEmissiveColor.Equals(levelSetupRef.m_setEmissiveColor) && m_emissiveColor.Equals(levelSetupRef.m_emissiveColor) && m_enableObject.Equals(levelSetupRef.m_enableObject); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class LightRef : Reference { [Persistent] public string m_prefab = ""; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] [Persistent] public string m_parent; [Persistent] public int? m_index; public bool? m_active; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string color; public LightType? type; public float? intensity; public float? range; public LightRef() { } public LightRef(Light light) { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) m_prefab = ((Object)light).name; Transform parent = ((Component)light).transform.parent; m_parent = ((parent != null) ? ((Object)parent).name : null); m_index = ((Component)light).transform.GetSiblingIndex(); m_active = ((Component)light).gameObject.activeSelf; color = light.color.ToRGBAString(); type = light.type; intensity = light.intensity; range = light.range; } public void Update(Light light, string targetName, bool log) { //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) if (log && !string.IsNullOrEmpty(targetName)) { if (LoadManager.resetting) { MonsterDBPlugin.LogDebug("[" + targetName + "]/[" + ((Object)light).name + "] Resetting light"); } else { MonsterDBPlugin.LogDebug("[" + targetName + "]/[" + ((Object)light).name + "] Updating light"); } } log &= ConfigManager.ShouldLogDetails() && !string.IsNullOrEmpty(targetName); if (m_active.HasValue) { ((Component)light).gameObject.SetActive(m_active.Value); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}]/[{((Object)light).name}] m_active: {m_active.Value}"); } } if (color != null) { light.color = color.FromHexOrRGBA(light.color); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "]/[" + ((Object)light).name + "] m_color: " + color); } } if (type.HasValue) { light.type = type.Value; if (log) { MonsterDBPlugin.LogDebug($"[{targetName}]/[{((Object)light).name}] m_type: {type.Value}"); } } if (intensity.HasValue) { light.intensity = intensity.Value; if (log) { MonsterDBPlugin.LogDebug($"[{targetName}]/[{((Object)light).name}] m_intensity: {intensity.Value}"); } } if (range.HasValue) { light.range = range.Value; if (log) { MonsterDBPlugin.LogDebug($"[{targetName}]/[{((Object)light).name}] m_range: {range.Value}"); } } } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class MaterialManager { private static readonly Dictionary _materials; private static readonly List _invalidQueries; private static float _lastSearchTime; static MaterialManager() { _materials = new Dictionary(); _invalidQueries = new List(); } public static bool TryGetMaterial(string name, out Material material) { if (!_materials.TryGetValue(name, out material)) { if (Time.time - _lastSearchTime < 10f && _invalidQueries.Contains(name)) { return false; } CacheMaterials(); } bool flag = _materials.TryGetValue(name, out material); if (!flag && !_invalidQueries.Contains(name)) { _invalidQueries.Add(name); } else { _invalidQueries.Remove(name); } return flag; } private static void CacheMaterials() { _lastSearchTime = Time.time; Material[] array = Resources.FindObjectsOfTypeAll(); foreach (Material val in array) { if (((Object)val).GetInstanceID() >= 0 && !_materials.ContainsKey(((Object)val).name)) { _materials.Add(((Object)val).name, val); } } } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class MaterialRef : Reference { [Persistent] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] public string m_name = ""; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] public string m_shader = ""; public string m_color = ""; public float? m_hue; public float? m_saturation; public float? m_value; public string m_emissionTexture = ""; public string m_emissionColor = ""; public string m_mainTexture = ""; public string m_tintColor = ""; public string m_materialOverride; public float? m_glossiness; public float? m_metallic; public float? m_bumpScale; public string m_bumpTexture; public float? m_flowSpeedAll; public string m_flowMaskTexture; public float? m_flowSpeedY; public string m_flowTexture; public string m_flowColor; public string m_edgeColor; public string m_emissiveColor; public MaterialRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public MaterialRef(Material mat) { //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_0337: Unknown result type (might be due to invalid IL or missing references) //IL_035d: Unknown result type (might be due to invalid IL or missing references) //IL_0383: Unknown result type (might be due to invalid IL or missing references) m_name = ((Object)mat).name; m_shader = ((Object)mat.shader).name; m_color = (mat.HasProperty(ShaderRef._Color) ? mat.color.ToRGBAString() : null); m_hue = (mat.HasProperty(ShaderRef._Hue) ? new float?(mat.GetFloat(ShaderRef._Hue)) : null); m_saturation = (mat.HasProperty(ShaderRef._Saturation) ? new float?(mat.GetFloat(ShaderRef._Saturation)) : null); m_value = (mat.HasProperty(ShaderRef._Value) ? new float?(mat.GetFloat(ShaderRef._Value)) : null); m_emissionColor = (mat.HasProperty(ShaderRef._EmissionColor) ? mat.GetColor(ShaderRef._EmissionColor).ToRGBAString() : null); Texture mainTexture = mat.mainTexture; m_mainTexture = ((mainTexture != null) ? ((Object)mainTexture).name : null) ?? null; m_tintColor = (mat.HasProperty(ShaderRef._TintColor) ? mat.GetColor(ShaderRef._TintColor).ToRGBAString() : null); object emissionTexture; if (!mat.HasProperty(ShaderRef._EmissionMap)) { emissionTexture = null; } else { Texture texture = mat.GetTexture(ShaderRef._EmissionMap); emissionTexture = ((texture != null) ? ((Object)texture).name : null); } m_emissionTexture = (string)emissionTexture; m_glossiness = (mat.HasProperty(ShaderRef._Glossiness) ? new float?(mat.GetFloat(ShaderRef._Glossiness)) : null); m_metallic = (mat.HasProperty(ShaderRef._Metallic) ? new float?(mat.GetFloat(ShaderRef._Metallic)) : null); m_bumpScale = (mat.HasProperty(ShaderRef._BumpScale) ? new float?(mat.GetFloat(ShaderRef._BumpScale)) : null); object bumpTexture; if (!mat.HasProperty(ShaderRef._BumpMap)) { bumpTexture = null; } else { Texture texture2 = mat.GetTexture(ShaderRef._BumpMap); bumpTexture = ((texture2 != null) ? ((Object)texture2).name : null); } m_bumpTexture = (string)bumpTexture; object flowMaskTexture; if (!mat.HasProperty(ShaderRef._FlowMaskTex)) { flowMaskTexture = null; } else { Texture texture3 = mat.GetTexture(ShaderRef._FlowMaskTex); flowMaskTexture = ((texture3 != null) ? ((Object)texture3).name : null); } m_flowMaskTexture = (string)flowMaskTexture; m_flowSpeedAll = (mat.HasProperty(ShaderRef._FlowSpeedAll) ? new float?(mat.GetFloat(ShaderRef._FlowSpeedAll)) : null); m_flowSpeedY = (mat.HasProperty(ShaderRef._FlowSpeedY) ? new float?(mat.GetFloat(ShaderRef._FlowSpeedY)) : null); object flowTexture; if (!mat.HasProperty(ShaderRef._FlowTexture)) { flowTexture = null; } else { Texture texture4 = mat.GetTexture(ShaderRef._FlowTexture); flowTexture = ((texture4 != null) ? ((Object)texture4).name : null); } m_flowTexture = (string)flowTexture; m_flowColor = (mat.HasProperty(ShaderRef._FlowColor) ? mat.GetColor(ShaderRef._FlowColor).ToRGBAString() : null); m_edgeColor = (mat.HasProperty(ShaderRef._SSS) ? mat.GetColor(ShaderRef._SSS).ToRGBAString() : null); m_emissiveColor = (mat.HasProperty(ShaderRef._EmissiveColor) ? mat.GetColor(ShaderRef._EmissiveColor).ToRGBAString() : null); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public void Update(Material material, string targetName, bool log) { //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_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_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_02e1: Unknown result type (might be due to invalid IL or missing references) //IL_02e3: Unknown result type (might be due to invalid IL or missing references) //IL_02ea: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_0414: Unknown result type (might be due to invalid IL or missing references) //IL_0931: Unknown result type (might be due to invalid IL or missing references) //IL_0936: Unknown result type (might be due to invalid IL or missing references) //IL_093b: Unknown result type (might be due to invalid IL or missing references) //IL_0943: Unknown result type (might be due to invalid IL or missing references) //IL_095f: Unknown result type (might be due to invalid IL or missing references) //IL_099c: Unknown result type (might be due to invalid IL or missing references) //IL_09a1: Unknown result type (might be due to invalid IL or missing references) //IL_09a6: Unknown result type (might be due to invalid IL or missing references) //IL_09ae: Unknown result type (might be due to invalid IL or missing references) //IL_09ca: Unknown result type (might be due to invalid IL or missing references) //IL_0a07: Unknown result type (might be due to invalid IL or missing references) //IL_0a0c: Unknown result type (might be due to invalid IL or missing references) //IL_0a11: Unknown result type (might be due to invalid IL or missing references) //IL_0a19: Unknown result type (might be due to invalid IL or missing references) //IL_0a35: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(targetName)) { targetName = "Unknown"; } log &= ConfigManager.ShouldLogDetails(); if ((Object)(object)material.shader != (Object)null && ((Object)material.shader).name != m_shader && !string.IsNullOrEmpty(m_shader)) { material.shader = ShaderRef.GetShader(m_shader, material.shader); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "][" + ((Object)material).name + "] m_shader: " + ((Object)material.shader).name); } } if (material.HasProperty(ShaderRef._Color) && m_color != null && !string.IsNullOrEmpty(m_color)) { material.color = m_color.FromHexOrRGBA(material.color); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "][" + ((Object)material).name + "] m_color: " + m_color); } } if (m_hue.HasValue && material.HasProperty(ShaderRef._Hue)) { material.SetFloat(ShaderRef._Hue, m_hue.Value); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}][{((Object)material).name}] m_hue: {m_hue.Value}"); } } if (m_saturation.HasValue && material.HasProperty(ShaderRef._Saturation)) { material.SetFloat(ShaderRef._Saturation, m_saturation.Value); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}][{((Object)material).name}] m_value: {m_saturation.Value}"); } } if (m_value.HasValue && material.HasProperty(ShaderRef._Value)) { material.SetFloat(ShaderRef._Value, m_value.Value); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}][{((Object)material).name}] m_value: {m_value.Value}"); } } if (m_emissionColor != null && material.HasProperty(ShaderRef._EmissionColor) && !string.IsNullOrEmpty(m_emissionColor)) { Color val = m_emissionColor.FromHexOrRGBA(material.GetColor(ShaderRef._EmissionColor)); material.SetColor(ShaderRef._EmissionColor, val * val.a); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "][" + ((Object)material).name + "] m_emissionColor: " + m_emissionColor); } } if (m_mainTexture != null) { material.mainTexture = TextureManager.GetTexture(m_mainTexture, material.mainTexture); if (log) { string[] obj = new string[6] { "[", targetName, "][", ((Object)material).name, "] mainTexture: ", null }; Texture mainTexture = material.mainTexture; obj[5] = ((mainTexture != null) ? ((Object)mainTexture).name : null) ?? "null"; MonsterDBPlugin.LogDebug(string.Concat(obj)); } } if (material.HasProperty(ShaderRef._TintColor) && m_tintColor != null && !string.IsNullOrEmpty(m_tintColor)) { material.SetColor(ShaderRef._TintColor, m_tintColor.FromHexOrRGBA(material.GetColor(ShaderRef._TintColor))); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "][" + ((Object)material).name + "] m_tintColor: " + m_tintColor); } } if (m_emissionTexture != null && !string.IsNullOrEmpty(m_emissionTexture) && material.HasProperty(ShaderRef._EmissionMap)) { Texture texture = TextureManager.GetTexture(m_emissionTexture, material.GetTexture(ShaderRef._EmissionMap)); material.SetTexture(ShaderRef._EmissionMap, texture); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "][" + ((Object)material).name + "] m_emissionTexture: " + (((texture != null) ? ((Object)texture).name : null) ?? "null")); } } if (m_glossiness.HasValue && material.HasProperty(ShaderRef._Glossiness)) { material.SetFloat(ShaderRef._Glossiness, m_glossiness.Value); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}][{((Object)material).name}] m_glossiness: {m_glossiness.Value}"); } } if (m_metallic.HasValue && material.HasProperty(ShaderRef._Metallic)) { material.SetFloat(ShaderRef._Metallic, m_metallic.Value); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}][{((Object)material).name}] m_metallic: {m_metallic.Value}"); } } if (m_bumpScale.HasValue && material.HasProperty(ShaderRef._BumpScale)) { material.SetFloat(ShaderRef._BumpScale, m_bumpScale.Value); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}][{((Object)material).name}] m_bumpScale: {m_bumpScale.Value}"); } } if (m_bumpTexture != null && material.HasProperty(ShaderRef._BumpMap)) { Texture texture2 = TextureManager.GetTexture(m_bumpTexture, material.GetTexture(ShaderRef._BumpMap)); material.SetTexture(ShaderRef._BumpMap, texture2); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "][" + ((Object)material).name + "] m_bumpTexture: " + (((texture2 != null) ? ((Object)texture2).name : null) ?? "null")); } } if (m_flowMaskTexture != null && material.HasProperty(ShaderRef._FlowMaskTex)) { Texture texture3 = TextureManager.GetTexture(m_flowMaskTexture, material.GetTexture(ShaderRef._FlowMaskTex)); material.SetTexture(ShaderRef._FlowMaskTex, texture3); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "][" + ((Object)material).name + "] m_flowMaskTex: " + (((texture3 != null) ? ((Object)texture3).name : null) ?? "null")); } } if (m_flowSpeedAll.HasValue && material.HasProperty(ShaderRef._FlowSpeedAll)) { material.SetFloat(ShaderRef._FlowSpeedAll, m_flowSpeedAll.Value); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}][{((Object)material).name}] m_flowSpeedAll: {m_flowSpeedAll.Value}"); } } if (m_flowSpeedY.HasValue && material.HasProperty(ShaderRef._FlowSpeedY)) { material.SetFloat(ShaderRef._FlowSpeedY, m_flowSpeedY.Value); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}][{((Object)material).name}] m_flowSpeedY: {m_flowSpeedY.Value}"); } } if (m_flowTexture != null && material.HasProperty(ShaderRef._FlowTexture)) { Texture texture4 = TextureManager.GetTexture(m_flowTexture, material.GetTexture(ShaderRef._FlowTexture)); material.SetTexture(ShaderRef._FlowTexture, texture4); if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "][" + ((Object)material).name + "] m_flowTexture: " + (((texture4 != null) ? ((Object)texture4).name : null) ?? "null")); } } if (m_flowColor != null && material.HasProperty(ShaderRef._FlowColor)) { Color val2 = m_flowColor.FromHexOrRGBA(material.GetColor(ShaderRef._FlowColor)); material.SetColor(ShaderRef._FlowColor, val2); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}][{((Object)material).name}] m_flowColor: {val2}"); } } if (m_edgeColor != null && material.HasProperty(ShaderRef._SSS)) { Color val3 = m_edgeColor.FromHexOrRGBA(material.GetColor(ShaderRef._SSS)); material.SetColor(ShaderRef._SSS, val3); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}][{((Object)material).name}] m_edgeColor: {val3}"); } } if (m_emissiveColor != null && material.HasProperty(ShaderRef._EmissiveColor)) { Color val4 = m_emissiveColor.FromHexOrRGBA(material.GetColor(ShaderRef._EmissiveColor)); material.SetColor(ShaderRef._EmissiveColor, val4); if (log) { MonsterDBPlugin.LogDebug($"[{targetName}][{((Object)material).name}] m_emissiveColor: {val4}"); } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public override bool Equals<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>(T other) { if (!(other is MaterialRef obj)) { return false; } FieldInfo[] fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { object value = fieldInfo.GetValue(this); object value2 = fieldInfo.GetValue(obj); if (value != value2) { return false; } } return true; } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class ShaderRef { public static readonly int _Color = Shader.PropertyToID("_Color"); public static readonly int _Hue = Shader.PropertyToID("_Hue"); public static readonly int _Saturation = Shader.PropertyToID("_Saturation"); public static readonly int _Value = Shader.PropertyToID("_Value"); public static readonly int _EmissionColor = Shader.PropertyToID("_EmissionColor"); public static readonly int _TintColor = Shader.PropertyToID("_TintColor"); public static readonly int _EmissionMap = Shader.PropertyToID("_EmissionMap"); public static readonly int _Glossiness = Shader.PropertyToID("_Glossiness"); public static readonly int _Metallic = Shader.PropertyToID("_Metallic"); public static readonly int _BumpScale = Shader.PropertyToID("_BumpScale"); public static readonly int _BumpMap = Shader.PropertyToID("_BumpMap"); public static readonly int _FlowSpeedAll = Shader.PropertyToID("_FlowSpeedAll"); public static readonly int _FlowSpeedY = Shader.PropertyToID("_FlowSpeedY"); public static readonly int _FlowTexture = Shader.PropertyToID("_FlowTexture"); public static readonly int _FlowColor = Shader.PropertyToID("_FlowColor"); public static readonly int _SSS = Shader.PropertyToID("_SSS"); public static readonly int _FlowMaskTex = Shader.PropertyToID("_FlowMaskTex"); public static readonly int _EmissiveColor = Shader.PropertyToID("_EmissiveColor"); private static readonly Dictionary m_shaders = new Dictionary(); public static Shader GetShader(string shaderName, Shader originalShader) { if (string.IsNullOrEmpty(shaderName)) { return originalShader; } if (m_shaders.TryGetValue(shaderName, out var value)) { return value; } MonsterDBPlugin.LogWarning("Failed to find shader: " + shaderName); return originalShader; } public static void CacheShaders() { AssetBundle[] array = Resources.FindObjectsOfTypeAll(); foreach (AssetBundle val in array) { IEnumerable enumerable3; try { IEnumerable enumerable2; if (!val.isStreamedSceneAssetBundle || !Object.op_Implicit((Object)(object)val)) { IEnumerable enumerable = ((val != null) ? val.LoadAllAssets() : null); enumerable2 = enumerable; } else { enumerable2 = from shader in ((IEnumerable)val.GetAllAssetNames()).Select((Func)val.LoadAsset) where (Object)(object)shader != (Object)null select shader; } enumerable3 = enumerable2; } catch (Exception) { continue; } if (enumerable3 == null) { continue; } foreach (Shader item in enumerable3) { if (!m_shaders.ContainsKey(((Object)item).name)) { m_shaders[((Object)item).name] = item; } } } Shader[] array2 = Resources.FindObjectsOfTypeAll(); foreach (Shader val2 in array2) { if (!((Object)(object)val2 == (Object)null) && !m_shaders.ContainsKey(((Object)val2).name)) { m_shaders[((Object)val2).name] = val2; } } } public static void SearchShaders(ConsoleEventArgs args) { string stringFrom = args.GetStringFrom(2); if (string.IsNullOrEmpty(stringFrom)) { args.Context.LogWarning("Invalid parameters"); return; } foreach (string key in m_shaders.Keys) { if (key.ToLower().Contains(stringFrom.ToLower())) { MonsterDBPlugin.LogInfo(key); } } } public static List GetShaderOptions(int i, string word) { if (1 == 0) { } List result = ((i != 2) ? new List() : GetShaderNames()); if (1 == 0) { } return result; } public static List GetShaderNames() { return m_shaders.Keys.ToList(); } public static void PrintShaderProperties(ConsoleEventArgs args) { //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) if (args.Length < 3) { args.Context.LogWarning("Invalid parameters"); return; } string[] args2 = args.Args; string text = string.Join(" ", args2, 2, args2.Length - 2); if (string.IsNullOrEmpty(text)) { args.Context.LogWarning("Specify query"); return; } if (!m_shaders.TryGetValue(text, out var value)) { args.Context.LogWarning("Failed to find shader: " + text); return; } MonsterDBPlugin.LogInfo("Shader: " + ((Object)value).name); args.Context.LogDebug("Shader: " + ((Object)value).name); int propertyCount = value.GetPropertyCount(); for (int i = 0; i < propertyCount; i++) { string propertyName = value.GetPropertyName(i); ShaderPropertyType propertyType = value.GetPropertyType(i); if (propertyName != null) { args.Context.LogDebug($"{propertyName}: {propertyType}"); MonsterDBPlugin.LogInfo($"{propertyName}: {propertyType}"); } } } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class GradientRef : Reference { [YamlMember(Description = "Blend, Fixed, PerceptualBlend")] public GradientMode? m_mode; [YamlMember(Description = "Set opacity over time")] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public GradientAlphaKeyRef[] m_alphaKeys; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] [YamlMember(Description = "Set color over time")] public GradientColorKeyRef[] m_colorKeys; [YamlMember(Description = "Uninitialized, Gamma, Linear")] public ColorSpace? m_colorSpace; public void Update(Gradient grad) { //IL_0018: 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) if (m_mode.HasValue) { grad.mode = m_mode.Value; } if (m_colorSpace.HasValue) { grad.colorSpace = m_colorSpace.Value; } if (m_alphaKeys != null) { grad.alphaKeys = m_alphaKeys.FromRef(); } if (m_colorKeys != null) { grad.colorKeys = m_colorKeys.FromRef(); } } public static implicit operator GradientRef(Gradient grad) { //IL_0008: 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) return new GradientRef { m_mode = grad.mode, m_alphaKeys = grad.alphaKeys.ToRef(), m_colorKeys = grad.colorKeys.ToRef(), m_colorSpace = grad.colorSpace }; } } [Serializable] public class GradientAlphaKeyRef : Reference { [YamlMember(DefaultValuesHandling = DefaultValuesHandling.Preserve)] public float m_alpha; [YamlMember(DefaultValuesHandling = DefaultValuesHandling.Preserve)] public float m_time; public GradientAlphaKeyRef() { } public GradientAlphaKeyRef(GradientAlphaKey key) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) m_time = key.time; m_alpha = key.alpha; } public GradientAlphaKey ToGradientAlphaKey() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) GradientAlphaKey result = default(GradientAlphaKey); result.time = m_time; result.alpha = m_alpha; return result; } } [Serializable] public class GradientColorKeyRef : Reference { [YamlMember(DefaultValuesHandling = DefaultValuesHandling.Preserve)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] public string m_color = ""; [YamlMember(DefaultValuesHandling = DefaultValuesHandling.Preserve)] public float m_time; public GradientColorKeyRef() { } public GradientColorKeyRef(GradientColorKey key) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) m_color = key.color.ToRGBAString(); m_time = key.time; } public GradientColorKey ToGradientColorKey() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: 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) GradientColorKey result = default(GradientColorKey); result.color = m_color.FromHexOrRGBA(Color.white); result.time = m_time; return result; } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class MinMaxGradientRef : Reference { [YamlMember(Description = "Color, Gradient, TwoColors, TwoGradients, RandomColor")] public ParticleSystemGradientMode? m_mode; public string m_color; public string m_colorMin; public string m_colorMax; public GradientRef m_gradient; public GradientRef m_gradientMin; public GradientRef m_gradientMax; public MinMaxGradientRef() { } public MinMaxGradientRef(MinMaxGradient gradient) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) m_mode = ((MinMaxGradient)(ref gradient)).mode; m_color = ((MinMaxGradient)(ref gradient)).color.ToRGBAString(); m_colorMin = ((MinMaxGradient)(ref gradient)).colorMin.ToRGBAString(); m_colorMax = ((MinMaxGradient)(ref gradient)).colorMax.ToRGBAString(); if (((MinMaxGradient)(ref gradient)).gradient != null) { m_gradient = ((MinMaxGradient)(ref gradient)).gradient; } if (((MinMaxGradient)(ref gradient)).gradientMin != null) { m_gradientMin = ((MinMaxGradient)(ref gradient)).gradientMin; } if (((MinMaxGradient)(ref gradient)).gradientMax != null) { m_gradientMax = ((MinMaxGradient)(ref gradient)).gradientMax; } } public void Update(MinMaxGradient gradient) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) if (m_mode.HasValue) { m_mode = ((MinMaxGradient)(ref gradient)).mode; } if (m_color != null && !string.IsNullOrEmpty(m_color)) { ((MinMaxGradient)(ref gradient)).color = m_color.FromHexOrRGBA(((MinMaxGradient)(ref gradient)).color); } if (m_colorMin != null && !string.IsNullOrEmpty(m_colorMin)) { ((MinMaxGradient)(ref gradient)).colorMin = m_colorMin.FromHexOrRGBA(((MinMaxGradient)(ref gradient)).colorMin); } if (m_colorMax != null && !string.IsNullOrEmpty(m_colorMax)) { ((MinMaxGradient)(ref gradient)).colorMax = m_colorMax.FromHexOrRGBA(((MinMaxGradient)(ref gradient)).colorMax); } m_gradient?.Update(((MinMaxGradient)(ref gradient)).gradient); m_gradientMin?.Update(((MinMaxGradient)(ref gradient)).gradientMin); m_gradientMax?.Update(((MinMaxGradient)(ref gradient)).gradientMax); } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class CustomDataModuleRef : Reference { public MinMaxGradientRef m_custom1; public MinMaxGradientRef m_custom2; public CustomDataModuleRef() { } public CustomDataModuleRef(CustomDataModule module) { //IL_000c: 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) m_custom1 = new MinMaxGradientRef(((CustomDataModule)(ref module)).GetColor((ParticleSystemCustomData)0)); m_custom2 = new MinMaxGradientRef(((CustomDataModule)(ref module)).GetColor((ParticleSystemCustomData)1)); } public void Update(CustomDataModule cm) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) MinMaxGradient color = ((CustomDataModule)(ref cm)).GetColor((ParticleSystemCustomData)0); MinMaxGradient color2 = ((CustomDataModule)(ref cm)).GetColor((ParticleSystemCustomData)1); m_custom1?.Update(color); m_custom2?.Update(color2); ((CustomDataModule)(ref cm)).SetColor((ParticleSystemCustomData)0, color); ((CustomDataModule)(ref cm)).SetColor((ParticleSystemCustomData)1, color2); } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class ParticleSystemRef : Reference { [Persistent] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(1)] public string m_prefab = ""; [Persistent] public string m_parent; [Persistent] public int? m_index; public MinMaxGradientRef m_startColor; public CustomDataModuleRef m_customData; public MinMaxGradientRef m_colorOverLifetime; public ParticleSystemRef() { } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public ParticleSystemRef(ParticleSystem ps) { //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_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) m_prefab = ((Object)((Component)ps).gameObject).name; Transform parent = ((Component)ps).transform.parent; m_parent = ((parent != null) ? ((Object)parent).name : null); m_index = ((Component)ps).transform.GetSiblingIndex(); MainModule main = ps.main; m_startColor = new MinMaxGradientRef(((MainModule)(ref main)).startColor); CustomDataModule customData = ps.customData; if (((CustomDataModule)(ref customData)).enabled) { m_customData = new CustomDataModuleRef(customData); } ColorOverLifetimeModule colorOverLifetime = ps.colorOverLifetime; if (((ColorOverLifetimeModule)(ref colorOverLifetime)).enabled) { MinMaxGradient color = ((ColorOverLifetimeModule)(ref colorOverLifetime)).color; m_colorOverLifetime = new MinMaxGradientRef(color); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public void Update(ParticleSystem ps, string targetName, bool log) { //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_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_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_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: 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) bool flag = false; if (m_startColor != null) { MainModule main = ps.main; MainModule main2 = ps.main; MinMaxGradient startColor = ((MainModule)(ref main2)).startColor; m_startColor.Update(startColor); ((MainModule)(ref main)).startColor = startColor; flag = true; } if (m_customData != null) { CustomDataModule customData = ps.customData; m_customData.Update(customData); flag = true; } if (m_colorOverLifetime != null) { ColorOverLifetimeModule colorOverLifetime = ps.colorOverLifetime; m_colorOverLifetime.Update(((ColorOverLifetimeModule)(ref colorOverLifetime)).color); flag = true; } if (flag && log && !string.IsNullOrEmpty(targetName)) { MonsterDBPlugin.LogDebug(LoadManager.resetting ? ("[" + targetName + "]/[" + ((Object)ps).name + "] Particle System Reverted") : ("[" + targetName + "]/[" + ((Object)ps).name + "] Particle System Updated")); } } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class RendererRef : Reference { [Persistent] public string m_prefab = ""; [Persistent] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string m_parent; [Persistent] public int? m_index; public bool? m_active; public bool? m_enabled; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public MaterialRef[] m_materials; private static Dictionary _cachedMaterials = new Dictionary(); public RendererRef() { } public RendererRef(Renderer renderer) { m_prefab = ((Object)renderer).name; Transform parent = ((Component)renderer).transform.parent; m_parent = ((parent != null) ? ((Object)parent).name : null); m_index = ((Component)renderer).transform.GetSiblingIndex(); m_active = ((Component)renderer).gameObject.activeSelf; m_enabled = renderer.enabled; m_materials = renderer.sharedMaterials.ToMaterialRefArray(); } public void Update(Renderer renderer, string targetName, bool log) { if (log && !string.IsNullOrEmpty(targetName)) { MonsterDBPlugin.LogDebug(LoadManager.resetting ? ("[" + targetName + "].[" + ((Object)renderer).name + "] Resetting Renderer") : ("[" + targetName + "].[" + ((Object)renderer).name + "] Updating Renderer")); } if (m_active.HasValue) { ((Component)renderer).gameObject.SetActive(m_active.Value); } if (m_enabled.HasValue) { renderer.enabled = m_enabled.Value; } if (m_materials != null) { UpdateMaterials(renderer, m_materials, targetName + "." + ((Object)renderer).name, log); } } private static void UpdateMaterials(Renderer renderer, MaterialRef[] materialRefs, string targetName, bool log) { //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Expected O, but got Unknown Dictionary dictionary = materialRefs.ToSafeDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (MaterialRef f) => f.m_name); Material[] sharedMaterials = renderer.sharedMaterials; for (int i = 0; i < sharedMaterials.Length; i++) { Material val = sharedMaterials[i]; if ((Object)(object)val == (Object)null) { continue; } string text = ((Object)val).name.Replace("(Instance)", string.Empty); if (!dictionary.TryGetValue(text, out var value)) { if (log) { MonsterDBPlugin.LogDebug("[" + targetName + "]/[" + ((Object)renderer).name + "] " + text + " not found in reference file"); } continue; } if (value.m_materialOverride != null) { if (_cachedMaterials.TryGetValue(value.m_materialOverride, out var value2)) { val = value2; } else { CacheMaterials(); if (_cachedMaterials.TryGetValue(value.m_materialOverride, out value2)) { val = value2; } } } Material val2 = new Material(val) { name = text }; value.Update(val2, targetName, log); sharedMaterials[i] = val2; } renderer.materials = sharedMaterials; renderer.sharedMaterials = sharedMaterials; } private static void CacheMaterials() { Material[] array = Resources.FindObjectsOfTypeAll(); foreach (Material val in array) { if (!((Object)(object)val == (Object)null) && ((Object)val).GetInstanceID() > 0 && !_cachedMaterials.ContainsKey(((Object)val).name)) { _cachedMaterials[((Object)val).name] = val; } } } public override bool Equals<[<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] T>(T other) { if (!(other is RendererRef rendererRef)) { return false; } if (m_prefab != rendererRef.m_prefab) { return false; } if (m_parent != rendererRef.m_parent) { return false; } if (m_index != rendererRef.m_index) { return false; } if (m_enabled != rendererRef.m_enabled) { return false; } if (m_enabled != rendererRef.m_enabled) { return false; } if (m_materials != rendererRef.m_materials) { return false; } if (m_materials != null && rendererRef.m_materials != null) { if (m_materials.Length != rendererRef.m_materials.Length) { return false; } for (int i = 0; i < m_materials.Length; i++) { MaterialRef materialRef = m_materials[i]; MaterialRef other2 = rendererRef.m_materials[i]; if (!materialRef.Equals(other2)) { return false; } } } return true; } } [Serializable] public record struct Vector3Ref { public float x; public float y; public float z; public Vector3Ref(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } public Vector3Ref(Vector3 v) : this(v.x, v.y, v.z) { }//IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) public Vector3 ToVector3() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) return new Vector3(x, y, z); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public override string ToString() { return $"{x}, {y}, {z}"; } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static Vector3Ref Parse(string value) { string[] array = value.Split(new char[1] { ',' }); if (array.Length != 3) { throw new FormatException("Invalid Vector3 format"); } return new Vector3Ref(float.Parse(array[0], CultureInfo.InvariantCulture), float.Parse(array[1], CultureInfo.InvariantCulture), float.Parse(array[2], CultureInfo.InvariantCulture)); } public static implicit operator Vector3(Vector3Ref v) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return v.ToVector3(); } public static implicit operator Vector3Ref(Vector3 v) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return new Vector3Ref(v); } [CompilerGenerated] public readonly void Deconstruct(out float x, out float y, out float z) { x = this.x; y = this.y; z = this.z; } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class VisualManager { [Obsolete] public static void WriteVisualYML(ConsoleEventArgs args) { string @string = args.GetString(2); if (string.IsNullOrEmpty(@string)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); return; } string sourceName; bool isClone = CloneManager.IsClone(((Object)prefab).name, out sourceName); Write(prefab, isClone, sourceName); } [Obsolete] public static void CloneVisual(ConsoleEventArgs args) { string @string = args.GetString(2); string string2 = args.GetString(3); if (string.IsNullOrEmpty(@string) || string.IsNullOrEmpty(string2)) { args.Context.LogWarning("Invalid parameters"); return; } GameObject prefab = PrefabManager.GetPrefab(@string); if ((Object)(object)prefab == (Object)null) { args.Context.LogWarning("Failed to find prefab: " + @string); } else { TryClone(prefab, string2, out var _); } } public static bool Write(GameObject prefab, bool isClone = false, string source = "", string dirPath = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (string.IsNullOrEmpty(dirPath)) { dirPath = FileManager.ExportFolder; } string text = Path.Combine(dirPath, ((Object)prefab).name + ".yml"); if (!TrySave(prefab, out var visual, isClone, source)) { return false; } string contents = ConfigManager.Serialize(visual); File.WriteAllText(text, contents); MonsterDBPlugin.LogInfo("Saved " + ((Object)prefab).name + " to: " + text); context?.LogInfo("Exported Visuals " + ((Object)prefab).name); context?.LogInfo(text.RemoveRootPath()); return true; } public static bool TrySave(GameObject prefab, out BaseVisual visual, bool isClone = false, string source = "") { visual = LoadManager.GetOriginal(((Object)prefab).name); if (visual != null) { return true; } visual = new BaseVisual(); visual.Setup(prefab, isClone, source); LoadManager.originals.Add(((Object)prefab).name, visual); return true; } public static bool TryClone(GameObject source, string cloneName, out GameObject clone, bool write = true, string dirPath = "", [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] Terminal context = null) { if (CloneManager.prefabs.TryGetValue(cloneName, out clone)) { return true; } Clone clone2 = new Clone(source, cloneName); clone2.OnCreated += delegate(GameObject p) { MonsterDBPlugin.LogDebug("Cloned " + ((Object)source).name + " as " + cloneName); if (write) { Write(p, isClone: true, ((Object)source).name, dirPath, context); } }; clone = clone2.Create(); context?.LogInfo("Cloned " + ((Object)source).name + " as " + cloneName); return (Object)(object)clone != (Object)null; } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class VisualRef : Reference { public Vector3Ref? m_scale; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List m_levelSetups; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public RendererRef[] m_renderers; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public LightRef[] m_lights; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public ParticleSystemRef[] m_particleSystems; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public int[] m_modelIndex; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public string[] m_beards; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public string[] m_hairs; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public string[] m_hairColors; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public string[] m_skinColors; public VisualRef() { } public VisualRef(GameObject prefab) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) m_scale = prefab.transform.localScale; Renderer[] componentsInChildren = prefab.GetComponentsInChildren(true); if (componentsInChildren.Length != 0) { m_renderers = componentsInChildren.ToRendererRefArray(); } ParticleSystem[] componentsInChildren2 = prefab.GetComponentsInChildren(true); if (componentsInChildren2.Length != 0) { m_particleSystems = componentsInChildren2.ToParticleSystemRefArray(); } Light[] componentsInChildren3 = prefab.GetComponentsInChildren(true); if (componentsInChildren3.Length != 0) { m_lights = componentsInChildren3.ToLightRefList(); } LevelEffects componentInChildren = prefab.GetComponentInChildren(); if ((Object)(object)componentInChildren != (Object)null) { m_levelSetups = componentInChildren.m_levelSetups.ToLevelSetupRefList(); } } public void Update(GameObject prefab, bool isInstance, bool isItem) { UpdateRenderers(prefab, isInstance, isItem); UpdateLights(prefab, isInstance); UpdateParticleSystems(prefab, isInstance); } public void UpdateChildrenScale(GameObject prefab, Renderer[] renderers, bool log) { //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_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) log &= ConfigManager.ShouldLogDetails(); if (!m_scale.HasValue || !LoadManager.originals.TryGetValue(((Object)prefab).name, out var value)) { return; } VisualRef visualData = value.GetVisualData(); if (visualData == null || !visualData.m_scale.HasValue) { return; } Vector3 val = visualData.m_scale.Value; foreach (Renderer val2 in renderers) { GameObject gameObject = ((Component)val2).gameObject; gameObject.transform.localScale = Vector3.Scale(val, (Vector3)m_scale.Value); if (log) { string[] obj = new string[6] { "[", ((Object)prefab).name, "][", ((Object)gameObject).name, "] m_scale: ", null }; Vector3 localScale = gameObject.transform.localScale; obj[5] = ((object)(Vector3)(ref localScale)).ToString(); MonsterDBPlugin.LogDebug(string.Concat(obj)); } } } public void UpdateScale(GameObject prefab, bool log) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) log &= ConfigManager.ShouldLogDetails(); if (m_scale.HasValue) { prefab.transform.localScale = m_scale.Value; if (log) { string name = ((Object)prefab).name; Vector3 localScale = prefab.transform.localScale; MonsterDBPlugin.LogDebug("[" + name + "] m_scale: " + ((object)(Vector3)(ref localScale)).ToString()); } } } public void UpdateRenderers(GameObject prefab, bool isInstance, bool isItem) { Renderer[] componentsInChildren = prefab.GetComponentsInChildren(true); if (!isItem) { UpdateScale(prefab, !isInstance); } else { UpdateChildrenScale(prefab, componentsInChildren, !isInstance); } if (m_renderers == null) { return; } Dictionary<(string, string, int?), RendererRef> dictionary = (from x in m_renderers group x by (x.m_prefab, x.m_parent, x.m_index)).ToDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping<(string m_prefab, string m_parent, int? m_index), RendererRef> x) => x.Key, [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping<(string m_prefab, string m_parent, int? m_index), RendererRef> x) => x.First()); Dictionary dictionary2 = (from x in m_renderers group x by x.m_prefab).ToDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping g) => g.Key, [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping g) => g.First()); foreach (Renderer val in componentsInChildren) { Transform parent = ((Component)val).transform.parent; string item = ((parent != null) ? ((Object)parent).name : null); int siblingIndex = ((Component)val).transform.GetSiblingIndex(); (string, string, int) tuple = (((Object)val).name, item, siblingIndex); (string, string, int) tuple2 = tuple; if (dictionary.TryGetValue((tuple2.Item1, tuple2.Item2, tuple2.Item3), out var value)) { value.Update(val, ((Object)prefab).name, !isInstance); } else if (dictionary2.TryGetValue(((Object)val).name, out value)) { value.Update(val, ((Object)prefab).name, !isInstance); } } } public void UpdateLights(GameObject prefab, bool isInstance) { if (m_lights == null) { return; } Dictionary<(string, string, int?), LightRef> dictionary = (from x in m_lights group x by (x.m_prefab, x.m_parent, x.m_index)).ToDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping<(string m_prefab, string m_parent, int? m_index), LightRef> x) => x.Key, [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping<(string m_prefab, string m_parent, int? m_index), LightRef> x) => x.First()); Dictionary dictionary2 = (from x in m_lights group x by x.m_prefab).ToDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping g) => g.Key, [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping g) => g.First()); Light[] componentsInChildren = prefab.GetComponentsInChildren(true); foreach (Light val in componentsInChildren) { Transform parent = ((Component)val).transform.parent; string item = ((parent != null) ? ((Object)parent).name : null); int siblingIndex = ((Component)val).transform.GetSiblingIndex(); (string, string, int) tuple = (((Object)val).name, item, siblingIndex); (string, string, int) tuple2 = tuple; if (dictionary.TryGetValue((tuple2.Item1, tuple2.Item2, tuple2.Item3), out var value)) { value.Update(val, ((Object)prefab).name, !isInstance); } else if (dictionary2.TryGetValue(((Object)val).name, out value)) { value.Update(val, ((Object)prefab).name, !isInstance); } } } public void UpdateParticleSystems(GameObject prefab, bool isInstance) { if (m_particleSystems == null) { return; } Dictionary<(string, string, int?), ParticleSystemRef> dictionary = (from x in m_particleSystems group x by (x.m_prefab, x.m_parent, x.m_index)).ToDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping<(string m_prefab, string m_parent, int? m_index), ParticleSystemRef> x) => x.Key, [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping<(string m_prefab, string m_parent, int? m_index), ParticleSystemRef> x) => x.First()); Dictionary dictionary2 = (from x in m_particleSystems group x by x.m_prefab).ToDictionary([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping g) => g.Key, [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (IGrouping g) => g.First()); ParticleSystem[] componentsInChildren = prefab.GetComponentsInChildren(true); foreach (ParticleSystem val in componentsInChildren) { Transform parent = ((Component)val).transform.parent; string item = ((parent != null) ? ((Object)parent).name : null); int siblingIndex = ((Component)val).transform.GetSiblingIndex(); (string, string, int) tuple = (((Object)val).name, item, siblingIndex); (string, string, int) tuple2 = tuple; if (dictionary.TryGetValue((tuple2.Item1, tuple2.Item2, tuple2.Item3), out var value)) { value.Update(val, ((Object)prefab).name, !isInstance); } else if (dictionary2.TryGetValue(((Object)val).name, out value)) { value.Update(val, ((Object)prefab).name, !isInstance); } } } public void SetDefaultHumanFields() { m_modelIndex = new int[2] { 0, 1 }; m_hairs = new string[35] { "Hair1", "Hair2", "Hair3", "Hair4", "Hair5", "Hair6", "Hair7", "Hair8", "Hair9", "Hair10", "Hair11", "Hair12", "Hair13", "Hair14", "Hair15", "Hair16", "Hair17", "Hair18", "Hair19", "Hair20", "Hair21", "Hair22", "Hair23", "Hair24", "Hair25", "Hair26", "Hair27", "Hair28", "Hair29", "Hair30", "Hair31", "Hair32", "Hair33", "Hair34", "HairNone" }; m_beards = new string[27] { "Beard1", "Beard2", "Beard3", "Beard4", "Beard5", "Beard6", "Beard7", "Beard8", "Beard9", "Beard10", "Beard11", "Beard12", "Beard13", "Beard14", "Beard15", "Beard16", "Beard17", "Beard18", "Beard19", "Beard20", "Beard21", "Beard22", "Beard23", "Beard24", "Beard25", "Beard26", "BeardNone" }; m_skinColors = new string[15] { "#FFFFFF", "#FFF2EB", "#FFEBDB", "#FFF0E0", "#FFE6D1", "#FFE0C7", "#FAD9B8", "#F2D1AD", "#EBC79E", "#E0B88F", "#D9AD85", "#C79E7A", "#FFE0BF", "#FAE6CC", "#F2DBC2" }; m_hairColors = new string[16] { "#000000", "#FAF0BF", "#A15C00", "#26140D", "#594026", "#8C7359", "#F2DE82", "#D9BF73", "#B8A685", "#732E14", "#8C1F0D", "#B8401F", "#666666", "#A6A6A6", "#E0E0E6", "#404047" }; } } public class VultureOverride : MonoBehaviour { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] private static AnimatorOverrideController overrideController; public void Start() { string prefabName = Utils.GetPrefabName(((Object)this).name); if (LoadManager.originals.ContainsKey(prefabName)) { Character component = ((Component)this).GetComponent(); component.m_animator.runtimeAnimatorController = (RuntimeAnimatorController)(object)overrideController; MonsterDBPlugin.LogDebug("Overriding " + ((Object)this).name + " controller"); if (component.IsTamed() || Object.op_Implicit((Object)(object)((Component)component).GetComponent())) { component.Land(); } else { component.TakeOff(); } } } public static void Setup() { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Expected O, but got Unknown GameObject prefab = PrefabManager.GetPrefab("Volture"); if ((Object)(object)prefab == (Object)null) { return; } Animator componentInChildren = prefab.GetComponentInChildren(); RuntimeAnimatorController runtimeAnimatorController = componentInChildren.runtimeAnimatorController; GameObject val = AssetBundleManager.LoadAsset("volture_fix", "Volture_temp"); if ((Object)(object)val == (Object)null) { MonsterDBPlugin.LogWarning("Volture_temp not found"); return; } Animator val2 = default(Animator); if (!val.TryGetComponent(ref val2)) { MonsterDBPlugin.LogWarning("animator not found"); return; } RuntimeAnimatorController runtimeAnimatorController2 = val2.runtimeAnimatorController; if (!((Object)(object)runtimeAnimatorController2 != (Object)null)) { return; } overrideController = new AnimatorOverrideController(runtimeAnimatorController2); Dictionary dictionary = new Dictionary(); AnimationClip[] animationClips = runtimeAnimatorController.animationClips; foreach (AnimationClip val3 in animationClips) { if ((Object)(object)val3 != (Object)null) { dictionary[((Object)val3).name] = val3; } } List> list = new List>(); AnimationClip[] animationClips2 = runtimeAnimatorController2.animationClips; foreach (AnimationClip val4 in animationClips2) { string key = ((Object)val4).name.Replace("MOCK ", string.Empty); list.Add(dictionary.TryGetValue(key, out var value) ? new KeyValuePair(val4, value) : new KeyValuePair(val4, val4)); } overrideController.ApplyOverrides((IList>)list); prefab.AddComponent(); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class Condition : Attribute { public bool icon; public bool melee; public bool bow; public bool reload; public bool bounce; public bool spawnOnHit; public bool randomSpawnOnHit; public bool noInstance; public bool ShouldSetupField(SharedData sharedData) { if (icon) { return sharedData.m_icons != null && sharedData.m_icons.Length != 0; } if (melee) { return sharedData.m_attack.m_attackRayWidth > 0f; } if (bow) { return sharedData.m_attack.m_drawDurationMin > 0f || (Object)(object)sharedData.m_attack.m_attackProjectile != (Object)null; } return true; } public bool ShouldSetupField(Projectile projectile) { if (bounce) { return projectile.m_bounce; } if (spawnOnHit) { return (Object)(object)projectile.m_spawnOnHit != (Object)null; } if (randomSpawnOnHit) { List list = projectile.m_randomSpawnOnHit; return list != null && list.Count > 0; } return true; } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("RustyMods.MonsterDB", "MonsterDB", "0.3.5")] public class MonsterDBPlugin : BaseUnityPlugin { internal const string ModName = "MonsterDB"; internal const string ModVersion = "0.3.5"; internal const string Author = "RustyMods"; public const string ModGUID = "RustyMods.MonsterDB"; private readonly Harmony _harmony = new Harmony("RustyMods.MonsterDB"); public static MonsterDBPlugin instance; public static Harmony harmony => instance._harmony; public void Awake() { instance = this; ConfigManager.Start(); LocalizationManager.Start(); LegacyManager.Start(); AudioManager.Start(); TextureManager.Start(); FactionManager.Start(); RaidManager.Start(); FileManager.Start(); PrefabManager.Start(); SpawnManager.Setup(); ProcreateText.Setup(); GrowUpText.Setup(); TexturePackage.Setup(); Wiki.Write(); VersionHandshake.Setup(); Commands.Init(); Assembly executingAssembly = Assembly.GetExecutingAssembly(); _harmony.PatchAll(executingAssembly); } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); } public static void LogInfo(string msg) { if (ConfigManager.ShouldLog((LogLevel)16)) { ((BaseUnityPlugin)instance).Logger.LogInfo((object)msg); } } public static void LogError(string msg) { if (ConfigManager.ShouldLog((LogLevel)2)) { ((BaseUnityPlugin)instance).Logger.LogError((object)msg); } } public static void LogWarning(string msg) { if (ConfigManager.ShouldLog((LogLevel)4)) { ((BaseUnityPlugin)instance).Logger.LogWarning((object)msg); } } public static void LogDebug(string msg) { if (ConfigManager.ShouldLog((LogLevel)32)) { ((BaseUnityPlugin)instance).Logger.LogDebug((object)msg); } } public static void LogFatal(string msg) { if (ConfigManager.ShouldLog((LogLevel)1)) { ((BaseUnityPlugin)instance).Logger.LogFatal((object)msg); } } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class RRR_CustomAttacks { public string sOriginalPrefabName; public string sTargetAnim; public float? fAIAttackInterval; public bool? bAIPrioritized; public RRR_Damages dtAttackDamageOverride; public float? fAttackDamageTotalOverride; public string sAttackProjectileOverride; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aStartEffects; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aHitEffects; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aTriggerEffects; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public bool Convert(string prefabId, out BaseItem item) { //IL_0109: 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_016d: Unknown result type (might be due to invalid IL or missing references) item = null; if (sOriginalPrefabName == null || string.IsNullOrEmpty(sOriginalPrefabName)) { return false; } GameObject prefab = PrefabManager.GetPrefab(sOriginalPrefabName); if ((Object)(object)prefab == (Object)null) { return false; } if (!ItemManager.TrySave(prefab, out item)) { return false; } item.IsCloned = true; item.ClonedFrom = ((Object)prefab).name; item.Prefab = prefabId + "_" + ((Object)prefab).name; if (item.ItemData != null && item.ItemData.m_attack != null) { item.ItemData.m_attack.m_attackAnimation = sTargetAnim; item.ItemData.m_aiAttackInterval = fAIAttackInterval; item.ItemData.m_aiPrioritized = bAIPrioritized; if (dtAttackDamageOverride != null) { item.ItemData.m_damages = dtAttackDamageOverride.ToDamages(); } if (fAttackDamageTotalOverride.HasValue && item.ItemData.m_damages.HasValue) { DamageTypes value = item.ItemData.m_damages.Value; ((DamageTypes)(ref value)).Modify(fAttackDamageTotalOverride.Value); item.ItemData.m_damages = value; } item.ItemData.m_attack.m_attackProjectile = sAttackProjectileOverride; if (aStartEffects != null) { item.ItemData.m_startEffect = new EffectListRef(aStartEffects.ToArray()); } if (aHitEffects != null) { item.ItemData.m_hitEffect = new EffectListRef(aHitEffects.ToArray()); } if (aTriggerEffects != null) { item.ItemData.m_triggerEffect = new EffectListRef(aTriggerEffects.ToArray()); } } return true; } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class RRR_Appearance { public RRR_Scale vScale; public RRR_Color cTintColor; public RRR_Color cTintItems; public RRR_Color cBodySmoke; public string sCustomTexture; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public void Setup(VisualRef reference) { if (vScale != null) { reference.m_scale = new Vector3Ref(vScale.fX.GetValueOrDefault(1f), vScale.fY.GetValueOrDefault(1f), vScale.fZ.GetValueOrDefault(1f)); } } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class RRR_BaseAI { public float? fViewRange; public float? fViewAngle; public float? fHearRange; public string sPathAgentType; public float? fRandomCircleInterval; public float? fRandomMoveInterval; public float? fRandomMoveRange; public bool? bAvoidFire; public bool? bAfraidOfFire; public bool? bAvoidWater; public string sSpawnMessage; public string sDeathMessage; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public void Setup(BaseAIRef reference) { reference.m_viewRange = fViewRange; reference.m_viewAngle = fViewAngle; reference.m_hearRange = fHearRange; reference.m_pathAgentType = GetPathAgentType(reference.m_pathAgentType); reference.m_randomCircleInterval = fRandomCircleInterval; reference.m_randomMoveInterval = fRandomMoveInterval; reference.m_randomMoveRange = fRandomMoveRange; reference.m_avoidFire = bAvoidFire; reference.m_afraidOfFire = bAfraidOfFire; reference.m_avoidWater = bAvoidWater; reference.m_spawnMessage = sSpawnMessage ?? ""; reference.m_deathMessage = sDeathMessage ?? ""; } private AgentType? GetPathAgentType(AgentType? defaultValue) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) AgentType result; return (sPathAgentType == null) ? defaultValue : (Enum.TryParse(sPathAgentType, ignoreCase: true, out result) ? new AgentType?(result) : defaultValue); } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class RRR_Character { public string sName; public string sFaction; public bool? bBoss; public string sBossEvent; public string sDefeatSetGlobalKey; public float? fMoveSpeedMulti; public bool? bTolerateWater; public bool? bTolerateFire; public bool? bTolerateSmoke; public bool? bStaggerWhenBlocked; public float? fHealth; public RRR_DamageModifiers DamageTaken; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public void Setup(CharacterRef reference) { //IL_0022: 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_00ba: 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_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: 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_0105: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_014c: 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_0160: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0188: 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_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Unknown result type (might be due to invalid IL or missing references) reference.m_name = sName; if (sFaction != null) { reference.m_faction = FactionManager.GetFaction(sFaction); } reference.m_boss = bBoss; reference.m_bossEvent = sBossEvent; reference.m_defeatSetGlobalKey = sDefeatSetGlobalKey; reference.m_tolerateWater = bTolerateWater; reference.m_tolerateFire = bTolerateFire; reference.m_tolerateSmoke = bTolerateSmoke; reference.m_staggerWhenBlocked = bStaggerWhenBlocked; reference.m_health = fHealth; if (DamageTaken != null && reference.m_damageModifiers.HasValue) { DamageModifiers value = reference.m_damageModifiers.Value; value.m_blunt = GetDamageModifier(DamageTaken.m_blunt, value.m_blunt); value.m_pierce = GetDamageModifier(DamageTaken.m_pierce, value.m_pierce); value.m_slash = GetDamageModifier(DamageTaken.m_slash, value.m_slash); value.m_pickaxe = GetDamageModifier(DamageTaken.m_pickaxe, value.m_pickaxe); value.m_chop = GetDamageModifier(DamageTaken.m_chop, value.m_chop); value.m_fire = GetDamageModifier(DamageTaken.m_fire, value.m_fire); value.m_frost = GetDamageModifier(DamageTaken.m_frost, value.m_frost); value.m_lightning = GetDamageModifier(DamageTaken.m_lightning, value.m_lightning); value.m_poison = GetDamageModifier(DamageTaken.m_poison, value.m_poison); value.m_spirit = GetDamageModifier(DamageTaken.m_spirit, value.m_spirit); reference.m_damageModifiers = value; } } public DamageModifier GetDamageModifier(string input, DamageModifier defaultValue) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) DamageModifier result; return (input == null) ? defaultValue : (Enum.TryParse(input, ignoreCase: true, out result) ? result : defaultValue); } } [Serializable] public class RRR_CharacterDrop { public bool bReplaceOriginalDrops; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List drDrops; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public void Setup(CharacterDropRef reference) { if (bReplaceOriginalDrops) { reference.m_drops = drDrops?.Select((RRR_Drop d) => d.ToDropRef()).ToList(); } } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class RRR_Humanoid { public RRR_Damages dtAttackDamageOverride; public float? fAttackDamageTotalOverride; public string sAttackProjectileOverride; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aDefaultItems; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aRandomArmor; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aRandomShield; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aaRandomSets; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aAdvancedCustomAttacks; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aHitEffects; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aDeathEffects; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aConsumeItemEffects; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public void Setup(HumanoidRef reference) { reference.m_defaultItems = aDefaultItems?.ToArray(); reference.m_randomArmor = aRandomArmor?.ToArray(); reference.m_randomShield = aRandomShield?.ToArray(); reference.m_randomSets = (from s in aaRandomSets?.ToList() select s.ToItemSet()).ToArray(); if (aHitEffects != null) { reference.m_hitEffects = new EffectListRef(aHitEffects.ToArray()); } if (aDeathEffects != null) { reference.m_deathEffects = new EffectListRef(aDeathEffects.ToArray()); } if (aConsumeItemEffects != null) { reference.m_consumeItemEffects = new EffectListRef(aConsumeItemEffects.ToArray()); } } } [Serializable] public class RRR_MonsterAI { public float? fAlertRange; public bool? bFleeIfHurtWhenTargetCantBeReached; public bool? bFleeIfNotAlerted; public float? fFleeIfLowHealth; public bool? bCirculateWhileCharging; public bool? bCirculateWhileChargingFlying; public bool? bEnableHuntPlayer; public bool? bAttackPlayerObjects; public bool? bAttackPlayerObjectsWhenAlerted; public float? fInterceptTimeMax; public float? fInterceptTimeMin; public float? fMaxChaseDistance; public float? fMinAttackInterval; public float? fCircleTargetInterval; public float? fCircleTargetDuration; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aConsumeItems; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public void Setup(MonsterAIRef reference) { reference.m_alertRange = fAlertRange; reference.m_fleeIfHurtWhenTargetCantBeReached = bFleeIfHurtWhenTargetCantBeReached; reference.m_fleeIfNotAlerted = bFleeIfNotAlerted; reference.m_fleeIfLowHealth = fFleeIfLowHealth; reference.m_circulateWhileCharging = bCirculateWhileCharging; reference.m_circulateWhileChargingFlying = bCirculateWhileChargingFlying; reference.m_enableHuntPlayer = bEnableHuntPlayer; reference.m_attackPlayerObjects = bAttackPlayerObjects; reference.m_interceptTimeMax = fInterceptTimeMax; reference.m_interceptTimeMin = fInterceptTimeMin; reference.m_maxChaseDistance = fMaxChaseDistance; reference.m_minAttackInterval = fMinAttackInterval; reference.m_circleTargetInterval = fCircleTargetInterval; reference.m_circleTargetDuration = fCircleTargetDuration; reference.m_consumeItems = aConsumeItems; } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class RRR_NPC { public bool? bIsFemale; public bool? bNoBeardIfFemale; public bool? bRandomGender; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aBeardIds; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aHairIds; public RRR_Color cSkinColorMin; public RRR_Color cSkinColorMax; public RRR_Color cHairColorMin; public RRR_Color cHairColorMax; public float? fHairValueMin; public float? fHairValueMax; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public void Setup(VisualRef reference) { if (bRandomGender.HasValue) { reference.m_modelIndex = ((!bIsFemale.HasValue || !bIsFemale.Value) ? new int[1] : new int[1] { 1 }); if (bIsFemale.HasValue && bIsFemale.Value && bNoBeardIfFemale.HasValue && bNoBeardIfFemale.Value) { reference.m_beards = Array.Empty(); } } else { reference.m_beards = aBeardIds?.ToArray(); reference.m_hairs = aHairIds?.ToArray(); } reference.m_skinColors = GetSkinColors(); reference.m_hairColors = GetHairColors(); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public string[] GetHairColors() { List list = new List(); if (cHairColorMin != null) { list.Add(cHairColorMin.ToRGBA()); } if (cHairColorMax != null) { list.Add(cHairColorMax.ToRGBA()); } return list.ToArray(); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public string[] GetSkinColors() { List list = new List(); if (cSkinColorMin != null) { list.Add(cSkinColorMin.ToRGBA()); } if (cSkinColorMax != null) { list.Add(cSkinColorMax.ToRGBA()); } return list.ToArray(); } } [Serializable] public class RRR_Special { public bool? bCanTame; public bool? bAlwaysTame; public bool? bCommandableWhenTame; public bool? bCanProcreateWhenTame; public bool? bFxNoTame; public bool? bSfxNoAlert; public bool? bSfxNoIdle; public bool? bSfxNoHit; public bool? bSfxNoDeath; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public void Setup(TameableRef reference) { reference.m_commandable = bCommandableWhenTame; } } [Serializable] public class RRR_Damages { public float? fDamage; public float? fBlunt; public float? fSlash; public float? fPierce; public float? fChop; public float? fPickaxe; public float? fFire; public float? fFrost; public float? fLightning; public float? fPoison; public float? fSpirit; public DamageTypes ToDamages() { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: 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) DamageTypes result = default(DamageTypes); result.m_damage = fDamage.GetValueOrDefault(); result.m_blunt = fBlunt.GetValueOrDefault(); result.m_slash = fSlash.GetValueOrDefault(); result.m_pierce = fPierce.GetValueOrDefault(); result.m_chop = fChop.GetValueOrDefault(); result.m_pickaxe = fPickaxe.GetValueOrDefault(); result.m_fire = fFire.GetValueOrDefault(); result.m_frost = fFrost.GetValueOrDefault(); result.m_lightning = fLightning.GetValueOrDefault(); result.m_poison = fPoison.GetValueOrDefault(); result.m_spirit = fSpirit.GetValueOrDefault(); return result; } } [Serializable] public class RRR_Color { public float? fRed; public float? fGreen; public float? fBlue; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public string ToRGBA() { //IL_0026: Unknown result type (might be due to invalid IL or missing references) return Extensions.ToRGBAString(new Color(fRed.GetValueOrDefault(), fGreen.GetValueOrDefault(), fBlue.GetValueOrDefault(), 1f)); } } [Serializable] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class RRR_DamageModifiers { public string m_blunt; public string m_slash; public string m_pierce; public string m_chop; public string m_pickaxe; public string m_fire; public string m_frost; public string m_lightning; public string m_poison; public string m_spirit; } [Serializable] public class RRR_Drop { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] public string sPrefabName; public int? iAmountMin; public int? iAmountMax; public float? fChance; public bool? bOnePerPlayer; public bool? bLevelMultiplier; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public DropRef ToDropRef() { return new DropRef { m_prefab = sPrefabName, m_amountMin = iAmountMin, m_amountMax = iAmountMax, m_chance = fChance, m_onePerPlayer = bOnePerPlayer, m_levelMultiplier = bLevelMultiplier }; } } [Serializable] public class RRR_RandomSet { [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 2, 1 })] public List aSetItems; [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public HumanoidRef.ItemSet ToItemSet() { return new HumanoidRef.ItemSet { m_name = "", m_items = (aSetItems?.ToArray() ?? Array.Empty()) }; } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(2)] public class RRR_Main { public string sOriginalPrefabName; public string sNewPrefabName; public RRR_Appearance Category_Appearance; public RRR_Character Category_Character; public RRR_Humanoid Category_Humanoid; public RRR_BaseAI Category_BaseAI; public RRR_MonsterAI Category_MonsterAI; public RRR_CharacterDrop Category_CharacterDrops; public RRR_Special Category_Special; public RRR_NPC Category_NpcOnly; public string sConfigFormatVersion; } [Serializable] public class RRR_Scale { public float? fX; public float? fY; public float? fZ; } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class DropThat { public string creature = ""; public int index = 0; public string prefab = ""; public int min = 1; public int max = 1; public float chance = 100f; public bool onePerPlayer = false; public bool scaleByLevel = true; public bool enabled = true; public bool isValid => !string.IsNullOrEmpty(prefab) && !string.IsNullOrEmpty(creature); public DropRef ToDropRef() { return new DropRef { m_prefab = prefab, m_amountMin = min, m_amountMax = max, m_chance = chance, m_onePerPlayer = onePerPlayer, m_dontScale = scaleByLevel }; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(new byte[] { 0, 1, 1, 1 })] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class DropDict : Dictionary> { public void Add(DropThat drop) { if (!ContainsKey(drop.creature)) { base[drop.creature] = new List(); } base[drop.creature].Add(drop); } public void Add(DropDict other) { foreach (List value in other.Values) { Add(value); } } public void Add(List drops) { for (int i = 0; i < drops.Count; i++) { Add(drops[i]); } } public List ToDropRefs(string key) { List value; return TryGetValue(key, out value) ? (from d in value where d.enabled select d.ToDropRef()).ToList() : new List(); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public class DropThat_Parser { public readonly DropDict drops = new DropDict(); public void Parse(string filepath) { string[] array = File.ReadAllLines(filepath); bool flag = false; DropThat dropThat = new DropThat(); foreach (string text in array) { if (text.StartsWith("[") && text.EndsWith("]")) { flag = true; string[] parts = text.Replace("[", string.Empty).Replace("]", string.Empty).Split(new char[1] { '.' }); string creature = parts.GetString(0).Replace("RRRM_", string.Empty); int @int = parts.GetInt(1); dropThat.creature = creature; dropThat.index = @int; } else if (string.IsNullOrEmpty(text)) { flag = false; if (dropThat.isValid) { drops.Add(dropThat); MonsterDBPlugin.LogDebug($"[ DropThat ]: {dropThat.creature}, {dropThat.prefab} ( {dropThat.min} - {dropThat.max} )"); } dropThat = new DropThat(); } else if (flag) { string[] parts2 = text.Split(new char[1] { '=' }); switch (parts2.GetString(0)) { case "PrefabName": dropThat.prefab = parts2.GetString(1); break; case "SetAmountMin": dropThat.min = parts2.GetInt(1, 1); break; case "SetAmountMax": dropThat.max = parts2.GetInt(1, 1); break; case "SetChanceToDrop": dropThat.chance = parts2.GetFloat(1, 100f) / 100f; break; case "SetDropOnePerPlayer": dropThat.onePerPlayer = parts2.GetBool(1); break; case "SetScaleByLevel": dropThat.scaleByLevel = parts2.GetBool(1, defaultValue: true); break; case "EnableConfig": dropThat.enabled = parts2.GetBool(1, defaultValue: true); break; } } } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class RRRConverter { private const string FolderName = "RRR"; private static readonly string FolderPath; private static readonly Dictionary files; private static readonly Dictionary textures; private static readonly DropDict drops; [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] private static readonly MethodInfo JsonDeserializeMethod; static RRRConverter() { FolderPath = Path.Combine(ConfigManager.DirectoryPath, "RRR"); files = new Dictionary(); textures = new Dictionary(); drops = new DropDict(); JsonDeserializeMethod = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (Assembly a) => a.GetName().Name == "Newtonsoft.Json")?.GetType("Newtonsoft.Json.JsonConvert")?.GetMethod("DeserializeObject", new Type[2] { typeof(string), typeof(Type) }); } [return: <64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(2)] private static T DeserializeObject(string json) where T : class { return JsonDeserializeMethod?.Invoke(null, new object[2] { json, typeof(T) }) as T; } public static void Read() { if (!Directory.Exists(FolderPath)) { return; } string[] array = Directory.GetFiles(FolderPath, "*.json", SearchOption.AllDirectories); foreach (string text in array) { try { string json = File.ReadAllText(text); RRR_Main rRR_Main = DeserializeObject(json); if (rRR_Main != null) { files[text] = rRR_Main; } } catch (Exception ex) { MonsterDBPlugin.LogWarning(ex.Message + " file: " + Path.GetFileName(text)); } } string[] array2 = Directory.GetFiles(FolderPath, "*.png", SearchOption.AllDirectories); foreach (string text2 in array2) { string fileName = Path.GetFileName(text2); TextureData value = new TextureData(text2); textures[fileName] = value; } string[] array3 = Directory.GetFiles(FolderPath, "*.cfg", SearchOption.AllDirectories); foreach (string text3 in array3) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text3); if (fileNameWithoutExtension.StartsWith("drop_that")) { DropThat_Parser dropThat_Parser = new DropThat_Parser(); dropThat_Parser.Parse(text3); drops.Add(dropThat_Parser.drops); } } } public static void ConvertAll(ConsoleEventArgs args) { int num = 0; int num2 = 0; foreach (KeyValuePair file in files) { if (Convert(file.Key, file.Value)) { num++; } else { num2++; } } args.Context.LogInfo($"Converted {num} RRR files ( failures: {num2} )"); } private static bool Convert(string filepath, RRR_Main main) { string fileName = Path.GetFileName(filepath); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); List list = new List(); List list2 = new List(); if (main.sOriginalPrefabName == null || string.IsNullOrEmpty(main.sOriginalPrefabName)) { MonsterDBPlugin.LogWarning("Failed RRR Conversion: " + fileName); return false; } GameObject prefab = PrefabManager.GetPrefab(main.sOriginalPrefabName); if ((Object)(object)prefab == (Object)null) { MonsterDBPlugin.LogWarning("Failed RRR Conversion: " + fileName); return false; } if (!CreatureManager.TrySave(prefab, out var data)) { MonsterDBPlugin.LogWarning("Failed RRR Conversion: " + fileName); return false; } if (main.sNewPrefabName != null && !string.IsNullOrEmpty(main.sNewPrefabName)) { data.ClonedFrom = ((Object)prefab).name; data.Prefab = main.sNewPrefabName; data.IsCloned = true; } BaseRagdoll baseRagdoll = null; if (main.Category_Appearance != null && data.Visuals != null) { main.Category_Appearance.Setup(data.Visuals); if (main.Category_Appearance.sCustomTexture != null && !string.IsNullOrEmpty(main.Category_Appearance.sCustomTexture)) { SkinnedMeshRenderer skin = prefab.GetComponentInChildren(); if ((Object)(object)skin != (Object)null) { string text = "rrrtex." + main.Category_Appearance.sCustomTexture; RendererRef rendererRef = data.Visuals.m_renderers?.FirstOrDefault([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (RendererRef r) => r.m_prefab == ((Object)skin).name); if (rendererRef != null && rendererRef.m_materials != null) { MaterialRef[] materials = rendererRef.m_materials; foreach (MaterialRef materialRef in materials) { materialRef.m_mainTexture = text; } list2.Add(text); } if (RagdollManager.TryGetRagdoll(prefab, out var output)) { baseRagdoll = new BaseRagdoll(); baseRagdoll.Setup(output, data.IsCloned, data.IsCloned ? ((Object)output).name : ""); if (data.IsCloned) { baseRagdoll.Prefab = data.Prefab + "_ragdoll"; } VisualRef visuals = baseRagdoll.Visuals; if (visuals != null) { RendererRef[] renderers = visuals.m_renderers; if (renderers != null && renderers.Length > 0) { SkinnedMeshRenderer ragSkin = output.GetComponentInChildren(); if ((Object)(object)ragSkin != (Object)null) { RendererRef rendererRef2 = baseRagdoll.Visuals.m_renderers.FirstOrDefault([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (RendererRef r) => r.m_prefab == ((Object)ragSkin).name); if (rendererRef2 != null && rendererRef2.m_materials != null) { MaterialRef[] materials2 = rendererRef2.m_materials; foreach (MaterialRef materialRef2 in materials2) { materialRef2.m_mainTexture = text; } } } } } } } } } if (main.Category_Character != null) { if (data is BaseCharacter baseCharacter && baseCharacter.Character != null) { main.Category_Character.Setup(baseCharacter.Character); } else if (data is BaseHumanoid baseHumanoid && baseHumanoid.Character != null) { main.Category_Character.Setup(baseHumanoid.Character); } else if (data is BaseHuman baseHuman && baseHuman.Character != null) { main.Category_Character.Setup(baseHuman.Character); } } if (main.Category_Humanoid != null) { if (main.sNewPrefabName != null && main.Category_Humanoid.aAdvancedCustomAttacks != null) { List list3 = new List(); for (int k = 0; k < main.Category_Humanoid.aAdvancedCustomAttacks.Count; k++) { RRR_CustomAttacks rRR_CustomAttacks = main.Category_Humanoid.aAdvancedCustomAttacks[k]; if (rRR_CustomAttacks.Convert(main.sNewPrefabName, out var item)) { list3.Add(item.Prefab); list.Add(item); } } if (list3.Count > 0) { main.Category_Humanoid.aDefaultItems = list3; } } if (data is BaseHumanoid baseHumanoid2 && baseHumanoid2.Character != null) { main.Category_Humanoid.Setup(baseHumanoid2.Character); } else if (data is BaseHuman baseHuman2 && baseHuman2.Character != null) { main.Category_Humanoid.Setup(baseHuman2.Character); } } if (main.Category_BaseAI != null) { if (data is BaseCharacter baseCharacter2 && baseCharacter2.AI != null) { main.Category_BaseAI.Setup(baseCharacter2.AI); } else if (data is BaseHumanoid baseHumanoid3 && baseHumanoid3.AI != null) { main.Category_BaseAI.Setup(baseHumanoid3.AI); } else if (data is BaseHuman baseHuman3 && baseHuman3.AI != null) { main.Category_BaseAI.Setup(baseHuman3.AI); } } if (main.Category_MonsterAI != null) { if (data is BaseHumanoid baseHumanoid4 && baseHumanoid4.AI != null) { main.Category_MonsterAI.Setup(baseHumanoid4.AI); } else if (data is BaseHuman baseHuman4 && baseHuman4.AI != null) { main.Category_MonsterAI.Setup(baseHuman4.AI); } } if (main.Category_CharacterDrops != null && data.Drops != null) { main.Category_CharacterDrops.Setup(data.Drops); } if (main.sNewPrefabName != null) { List list4 = drops.ToDropRefs(main.sNewPrefabName); if (list4.Count > 0) { Base @base = data; if (@base.Drops == null) { @base.Drops = new CharacterDropRef(); } data.Drops.m_drops = new List(); data.Drops.m_drops.AddRange(list4); } } if (main.Category_Special != null && data.Tameable != null) { main.Category_Special.Setup(data.Tameable); } if (main.Category_NpcOnly != null && data.Visuals != null) { main.Category_NpcOnly.Setup(data.Visuals); } string text2 = Path.Combine(FolderPath, "Export"); if (!Directory.Exists(text2)) { Directory.CreateDirectory(text2); } string text3 = Path.Combine(text2, fileNameWithoutExtension); if (!Directory.Exists(text3)) { Directory.CreateDirectory(text3); } string text4 = Path.Combine(text3, "items"); if (!Directory.Exists(text4)) { Directory.CreateDirectory(text4); } string text5 = Path.Combine(text3, "textures"); if (!Directory.Exists(text5)) { Directory.CreateDirectory(text5); } foreach (BaseItem item2 in list) { string path = item2.Prefab + ".yml"; string path2 = Path.Combine(text4, path); string contents = ConfigManager.Serialize(item2); File.WriteAllText(path2, contents); } foreach (string item3 in list2) { string text6 = item3 + ".png"; if (textures.TryGetValue(text6, out var value)) { string filepath2 = Path.Combine(text5, text6); value.Write(filepath2); } } string contents2 = ConfigManager.Serialize(data); fileName = main.sNewPrefabName + ".yml"; filepath = Path.Combine(text3, fileName); File.WriteAllText(filepath, contents2); if (baseRagdoll != null) { contents2 = ConfigManager.Serialize(baseRagdoll); fileName = main.sNewPrefabName + "_ragdoll.yml"; filepath = Path.Combine(text3, fileName); File.WriteAllText(filepath, contents2); } MonsterDBPlugin.LogInfo("Converted RRR file: " + fileName); return true; } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class VersionHandshake { private static string ConnectionError; private static readonly List ValidatedPeers; private static readonly string RequestAdminSyncMethodName; static VersionHandshake() { ConnectionError = ""; ValidatedPeers = new List(); RequestAdminSyncMethodName = "MonsterDBRequestAdminSync"; } public static void Setup() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_0098: Expected O, but got Unknown //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Expected O, but got Unknown //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Expected O, but got Unknown Harmony harmony = MonsterDBPlugin.harmony; harmony.Patch((MethodBase)AccessTools.Method(typeof(ZNet), "OnNewConnection", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(VersionHandshake), "RegisterAndCheckVersion", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(ZNet), "RPC_PeerInfo", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(VersionHandshake), "VerifyClient", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.Method(typeof(VersionHandshake), "RequestAdminSync", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(FejdStartup), "ShowConnectError", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(VersionHandshake), "ShowConnectionError", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(ZNet), "Disconnect", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.Method(typeof(VersionHandshake), "RemoveDisconnectedPeerFromVerified", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } private static void RPC_MonsterDB_VersionCheck(ZRpc rpc, ZPackage pkg) { string text = pkg.ReadString(); MonsterDBPlugin.LogInfo("Version check, local: 0.3.5, remove: " + text); if (text != "0.3.5") { ConnectionError = "MonsterDB Installed: 0.3.5\n Needed: " + text; if (ZNet.instance.IsServer()) { MonsterDBPlugin.LogWarning("Peer (" + rpc.m_socket.GetHostName() + ") has incompatible version, disconnecting..."); rpc.Invoke("Error", new object[1] { 3 }); } } else if (!ZNet.instance.IsServer()) { MonsterDBPlugin.LogInfo("Received same version from server!"); } else { MonsterDBPlugin.LogInfo("Adding peer (" + rpc.m_socket.GetHostName() + ") to validated list"); ValidatedPeers.Add(rpc); } } public static void RegisterAndCheckVersion(ZNetPeer peer) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown MonsterDBPlugin.LogDebug("Registering version RPC handler"); peer.m_rpc.Register("RPC_MonsterDB_VersionCheck", (Action)RPC_MonsterDB_VersionCheck); MonsterDBPlugin.LogInfo("Invoking version check"); ZPackage val = new ZPackage(); val.Write("0.3.5"); peer.m_rpc.Invoke("RPC_MonsterDB_VersionCheck", new object[1] { val }); } public static bool VerifyClient(ZRpc rpc, ref ZNet __instance) { if (!__instance.IsServer() || ValidatedPeers.Contains(rpc)) { return true; } MonsterDBPlugin.LogWarning("Peer (" + rpc.m_socket.GetHostName() + ") never sent version or couldn't due to previous disconnect, disconnecting"); rpc.Invoke("Error", new object[1] { 3 }); return false; } public static void RequestAdminSync() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), RequestAdminSyncMethodName, new object[1] { (object)new ZPackage() }); } public static void ShowConnectionError(FejdStartup __instance) { if (__instance.m_connectionFailedPanel.activeSelf) { __instance.m_connectionFailedError.fontSizeMax = 25f; __instance.m_connectionFailedError.fontSizeMin = 15f; TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + ConnectionError; if (string.IsNullOrEmpty(ConnectionError)) { MonsterDBPlugin.LogWarning("Connection failed"); } else { MonsterDBPlugin.LogFatal(ConnectionError); } } } public static void RemoveDisconnectedPeerFromVerified(ZNetPeer peer, ref ZNet __instance) { if (__instance.IsServer()) { MonsterDBPlugin.LogInfo("Peer (" + peer.m_rpc.m_socket.GetHostName() + ") disconnected, removing from validated list"); ValidatedPeers.Remove(peer.m_rpc); } } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class Wiki { private const string FolderName = "README"; private static readonly string FolderPath; static Wiki() { FolderPath = Path.Combine(ConfigManager.DirectoryPath, "README"); if (!Directory.Exists(FolderPath)) { Directory.CreateDirectory(FolderPath); } } public static void Write() { Assembly executingAssembly = Assembly.GetExecutingAssembly(); string[] manifestResourceNames = executingAssembly.GetManifestResourceNames(); string prefix = "MonsterDB.Wiki."; List list = manifestResourceNames.Where([<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(0)] (string r) => r.StartsWith(prefix) && r.EndsWith(".md")).ToList(); foreach (string item in list) { string path = item.Substring(prefix.Length); string fileName = Path.GetFileName(path); string path2 = Path.Combine(FolderPath, fileName); if (File.Exists(path2)) { continue; } using Stream stream = executingAssembly.GetManifestResourceStream(item); if (stream != null) { using FileStream destination = File.Create(path2); stream.CopyTo(destination); } } } } } namespace MonsterDB.Solution.Methods { [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class AnimalAIMethods { public static void ReadAnimalAI(string folderPath, ref CreatureData creatureData) { char directorySeparatorChar = Path.DirectorySeparatorChar; string text = folderPath + directorySeparatorChar + "AnimalAI.yml"; if (!File.Exists(text)) { return; } string text2 = File.ReadAllText(text); if (Utility.IsNullOrWhiteSpace(text2)) { return; } IDeserializer deserializer = new DeserializerBuilder().Build(); try { AnimalAIData animalAIData = deserializer.Deserialize(text2); creatureData.m_animalAIData = animalAIData; directorySeparatorChar = Path.DirectorySeparatorChar; string text3 = folderPath + directorySeparatorChar + "Effects"; if (Directory.Exists(text3)) { directorySeparatorChar = Path.DirectorySeparatorChar; string filePath = text3 + directorySeparatorChar + "AlertedEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath2 = text3 + directorySeparatorChar + "IdleSounds.yml"; Helpers.ReadEffectInfo(filePath, ref creatureData.m_effects.m_alertedEffects); Helpers.ReadEffectInfo(filePath2, ref creatureData.m_effects.m_idleSounds); } } catch { Helpers.LogParseFailure(text); } } public static void Update(GameObject critter, CreatureData creatureData) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_021f: 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_0097: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) AnimalAIData animalAIData = creatureData.m_animalAIData; Vector3 scale = creatureData.m_scale.ToRef(); CharacterEffects effects = creatureData.m_effects; AnimalAI val = default(AnimalAI); if (critter.TryGetComponent(ref val)) { ((BaseAI)val).m_viewRange = animalAIData.ViewRange; ((BaseAI)val).m_viewAngle = animalAIData.ViewAngle; ((BaseAI)val).m_hearRange = animalAIData.HearRange; ((BaseAI)val).m_mistVision = animalAIData.MistVision; ((BaseAI)val).m_idleSoundInterval = animalAIData.IdleSoundInterval; ((BaseAI)val).m_idleSoundChance = animalAIData.IdleSoundChance; if (!Enum.TryParse(animalAIData.PathAgentType, ignoreCase: true, out AgentType result)) { ((BaseAI)val).m_pathAgentType = result; } ((BaseAI)val).m_moveMinAngle = animalAIData.MoveMinAngle; ((BaseAI)val).m_smoothMovement = animalAIData.SmoothMovement; ((BaseAI)val).m_serpentMovement = animalAIData.SerpentMovement; ((BaseAI)val).m_serpentTurnRadius = animalAIData.SerpentTurnRadius; ((BaseAI)val).m_jumpInterval = animalAIData.JumpInterval; ((BaseAI)val).m_randomCircleInterval = animalAIData.RandomCircleInterval; ((BaseAI)val).m_randomMoveInterval = animalAIData.RandomMoveInterval; ((BaseAI)val).m_randomMoveRange = animalAIData.RandomMoveRange; ((BaseAI)val).m_randomFly = animalAIData.RandomFly; ((BaseAI)val).m_chanceToTakeoff = animalAIData.ChanceToTakeOff; ((BaseAI)val).m_chanceToLand = animalAIData.ChanceToLand; ((BaseAI)val).m_groundDuration = animalAIData.GroundDuration; ((BaseAI)val).m_airDuration = animalAIData.AirDuration; ((BaseAI)val).m_maxLandAltitude = animalAIData.MaxLandAltitude; ((BaseAI)val).m_takeoffTime = animalAIData.TakeoffTime; ((BaseAI)val).m_flyAltitudeMin = animalAIData.FlyAltitudeMin; ((BaseAI)val).m_flyAltitudeMax = animalAIData.FlyAltitudeMax; ((BaseAI)val).m_flyAbsMinAltitude = animalAIData.FlyAbsMinAltitude; ((BaseAI)val).m_avoidFire = animalAIData.AvoidFire; ((BaseAI)val).m_afraidOfFire = animalAIData.AfraidOfFire; ((BaseAI)val).m_avoidWater = animalAIData.AvoidWater; ((BaseAI)val).m_avoidLava = animalAIData.AvoidLava; ((BaseAI)val).m_skipLavaTargets = animalAIData.SkipLavaTargets; ((BaseAI)val).m_aggravatable = animalAIData.Aggravatable; ((BaseAI)val).m_passiveAggresive = animalAIData.PassiveAggressive; ((BaseAI)val).m_spawnMessage = animalAIData.SpawnMessage; ((BaseAI)val).m_deathMessage = animalAIData.DeathMessage; ((BaseAI)val).m_alertedMessage = animalAIData.AlertedMessage; ((BaseAI)val).m_fleeRange = animalAIData.FleeRange; ((BaseAI)val).m_fleeAngle = animalAIData.FleeAngle; ((BaseAI)val).m_fleeInterval = animalAIData.FleeInterval; Helpers.UpdateEffectList(effects.m_alertedEffects, ref ((BaseAI)val).m_alertedEffects, scale); Helpers.UpdateEffectList(effects.m_idleSounds, ref ((BaseAI)val).m_alertedEffects, scale); } } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class CharacterDropMethods { public static void ReadCharacterDrops(string folderPath, ref CreatureData creatureData) { char directorySeparatorChar = Path.DirectorySeparatorChar; string text = folderPath + directorySeparatorChar + "CharacterDrop.yml"; if (!File.Exists(text)) { return; } IDeserializer deserializer = new DeserializerBuilder().Build(); string text2 = File.ReadAllText(text); if (Utility.IsNullOrWhiteSpace(text2)) { return; } try { List characterDrops = deserializer.Deserialize>(text2); creatureData.m_characterDrops = characterDrops; } catch { Helpers.LogParseFailure(text); } } public static void Update(GameObject critter, CreatureData creatureData) { //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_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0080: 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_009a: 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_00b9: Expected O, but got Unknown CharacterDrop val = default(CharacterDrop); if (!critter.TryGetComponent(ref val)) { return; } List characterDrops = creatureData.m_characterDrops; List list = new List(); foreach (CharacterDropData item in characterDrops) { GameObject prefab = PrefabManager.GetPrefab(item.PrefabName); if (!((Object)(object)prefab == (Object)null)) { list.Add(new Drop { m_prefab = prefab, m_amountMin = item.AmountMin, m_amountMax = item.AmountMax, m_chance = item.Chance, m_onePerPlayer = item.OnePerPlayer, m_levelMultiplier = item.LevelMultiplier, m_dontScale = item.DoNotScale }); } } val.m_drops = list; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class CharacterMethods { public static void ReadCharacter(string folderPath, ref CreatureData creatureData) { char directorySeparatorChar = Path.DirectorySeparatorChar; string text = folderPath + directorySeparatorChar + "Character.yml"; if (File.Exists(text)) { IDeserializer deserializer = new DeserializerBuilder().Build(); try { CharacterData characterData = deserializer.Deserialize(File.ReadAllText(text)); creatureData.m_characterData = characterData; } catch { Helpers.LogParseFailure(text); } ReadEffects(folderPath, ref creatureData); } } private static void ReadEffects(string folderPath, ref CreatureData creatureData) { char directorySeparatorChar = Path.DirectorySeparatorChar; string text = folderPath + directorySeparatorChar + "Effects"; if (Directory.Exists(text)) { directorySeparatorChar = Path.DirectorySeparatorChar; string filePath = text + directorySeparatorChar + "HitEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath2 = text + directorySeparatorChar + "CritHitEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath3 = text + directorySeparatorChar + "BackstabHitEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath4 = text + directorySeparatorChar + "DeathEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath5 = text + directorySeparatorChar + "WaterEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath6 = text + directorySeparatorChar + "TarEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath7 = text + directorySeparatorChar + "SlideEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath8 = text + directorySeparatorChar + "JumpEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath9 = text + directorySeparatorChar + "FlyingContinuousEffects.yml"; Helpers.ReadEffectInfo(filePath, ref creatureData.m_effects.m_hitEffects); Helpers.ReadEffectInfo(filePath2, ref creatureData.m_effects.m_critHitEffects); Helpers.ReadEffectInfo(filePath3, ref creatureData.m_effects.m_backstabHitEffects); Helpers.ReadEffectInfo(filePath4, ref creatureData.m_effects.m_deathEffects); Helpers.ReadEffectInfo(filePath5, ref creatureData.m_effects.m_waterEffects); Helpers.ReadEffectInfo(filePath6, ref creatureData.m_effects.m_tarEffects); Helpers.ReadEffectInfo(filePath7, ref creatureData.m_effects.m_slideEffects); Helpers.ReadEffectInfo(filePath8, ref creatureData.m_effects.m_jumpEffects); Helpers.ReadEffectInfo(filePath9, ref creatureData.m_effects.m_flyingContinuousEffects); } } public static void Update(GameObject critter, CreatureData creatureData) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_0245: Unknown result type (might be due to invalid IL or missing references) //IL_0266: 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_0289: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_02ac: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: 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_02d1: Unknown result type (might be due to invalid IL or missing references) //IL_02f2: Unknown result type (might be due to invalid IL or missing references) //IL_02f4: Unknown result type (might be due to invalid IL or missing references) //IL_0315: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Unknown result type (might be due to invalid IL or missing references) //IL_0338: Unknown result type (might be due to invalid IL or missing references) //IL_033a: Unknown result type (might be due to invalid IL or missing references) //IL_035b: Unknown result type (might be due to invalid IL or missing references) //IL_035d: Unknown result type (might be due to invalid IL or missing references) //IL_03ab: Unknown result type (might be due to invalid IL or missing references) //IL_03bf: Unknown result type (might be due to invalid IL or missing references) //IL_03d3: Unknown result type (might be due to invalid IL or missing references) //IL_03e7: Unknown result type (might be due to invalid IL or missing references) //IL_03fb: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_0423: Unknown result type (might be due to invalid IL or missing references) //IL_0437: Unknown result type (might be due to invalid IL or missing references) //IL_044b: Unknown result type (might be due to invalid IL or missing references) //IL_037e: Unknown result type (might be due to invalid IL or missing references) //IL_0380: Unknown result type (might be due to invalid IL or missing references) Character val = default(Character); if (critter.TryGetComponent(ref val)) { CharacterData characterData = creatureData.m_characterData; Vector3 scale = creatureData.m_scale.ToRef(); Vector3 scale2 = creatureData.m_ragdollScale.ToRef(); CharacterEffects effects = creatureData.m_effects; val.m_name = characterData.Name; val.m_group = characterData.Group; if (Enum.TryParse(characterData.Faction, ignoreCase: true, out Faction result)) { val.m_faction = result; } val.m_boss = characterData.Boss; val.m_dontHideBossHud = characterData.DoNotHideBossHUD; val.m_bossEvent = characterData.BossEvent; val.m_defeatSetGlobalKey = characterData.DefeatSetGlobalKey; val.m_aiSkipTarget = characterData.AISkipTarget; val.m_crouchSpeed = characterData.CrouchSpeed; val.m_walkSpeed = characterData.WalkSpeed; val.m_speed = characterData.Speed; val.m_turnSpeed = characterData.TurnSpeed; val.m_runSpeed = characterData.RunSpeed; val.m_runTurnSpeed = characterData.RunTurnSpeed; val.m_flySlowSpeed = characterData.FlySlowSpeed; val.m_flyFastSpeed = characterData.FlyFastSpeed; val.m_flyTurnSpeed = characterData.FlyTurnSpeed; val.m_acceleration = characterData.Acceleration; val.m_jumpForce = characterData.JumpForce; val.m_jumpForceForward = characterData.JumpForceForward; val.m_jumpForceTiredFactor = characterData.JumpForceTiredFactor; val.m_airControl = characterData.AirControl; val.m_canSwim = characterData.CanSwim; val.m_swimDepth = characterData.SwimDepth; val.m_swimTurnSpeed = characterData.SwimTurnSpeed; val.m_swimAcceleration = characterData.SwimAcceleration; if (Enum.TryParse(characterData.GroundTilt, ignoreCase: true, out GroundTiltType result2)) { val.m_groundTilt = result2; } val.m_swimSpeed = characterData.SwimSpeed; val.m_groundTiltSpeed = characterData.GroundTiltSpeed; val.m_flying = characterData.Flying; val.m_jumpStaminaUsage = characterData.JumpStaminaUsage; val.m_disableWhileSleeping = characterData.DisableWhileSleeping; val.m_tolerateWater = characterData.TolerateWater; val.m_tolerateFire = characterData.TolerateFire; val.m_tolerateSmoke = characterData.TolerateSmoke; val.m_tolerateTar = characterData.TolerateTar; val.m_health = characterData.Health; if (Enum.TryParse(characterData.BluntResistance, ignoreCase: true, out DamageModifier result3)) { val.m_damageModifiers.m_blunt = result3; } if (Enum.TryParse(characterData.SlashResistance, ignoreCase: true, out DamageModifier result4)) { val.m_damageModifiers.m_slash = result4; } if (Enum.TryParse(characterData.PierceResistance, ignoreCase: true, out DamageModifier result5)) { val.m_damageModifiers.m_pierce = result5; } if (Enum.TryParse(characterData.ChopResistance, ignoreCase: true, out DamageModifier result6)) { val.m_damageModifiers.m_chop = result6; } if (Enum.TryParse(characterData.PickaxeResistance, ignoreCase: true, out DamageModifier result7)) { val.m_damageModifiers.m_pickaxe = result7; } if (Enum.TryParse(characterData.FireResistance, ignoreCase: true, out DamageModifier result8)) { val.m_damageModifiers.m_fire = result8; } if (Enum.TryParse(characterData.FrostResistance, ignoreCase: true, out DamageModifier result9)) { val.m_damageModifiers.m_frost = result9; } if (Enum.TryParse(characterData.LightningResistance, ignoreCase: true, out DamageModifier result10)) { val.m_damageModifiers.m_lightning = result10; } if (Enum.TryParse(characterData.PoisonResistance, ignoreCase: true, out DamageModifier result11)) { val.m_damageModifiers.m_poison = result11; } if (Enum.TryParse(characterData.SpiritResistance, ignoreCase: true, out DamageModifier result12)) { val.m_damageModifiers.m_spirit = result12; } val.m_staggerWhenBlocked = characterData.StaggerWhenBlocked; val.m_staggerDamageFactor = characterData.StaggerDamageFactor; Helpers.UpdateEffectList(effects.m_hitEffects, ref val.m_hitEffects, scale); Helpers.UpdateEffectList(effects.m_critHitEffects, ref val.m_critHitEffects, scale); Helpers.UpdateEffectList(effects.m_backstabHitEffects, ref val.m_backstabHitEffects, scale); Helpers.UpdateEffectList(effects.m_deathEffects, ref val.m_deathEffects, scale2); Helpers.UpdateEffectList(effects.m_waterEffects, ref val.m_waterEffects, scale); Helpers.UpdateEffectList(effects.m_tarEffects, ref val.m_tarEffects, scale); Helpers.UpdateEffectList(effects.m_slideEffects, ref val.m_slideEffects, scale); Helpers.UpdateEffectList(effects.m_jumpEffects, ref val.m_jumpEffects, scale); Helpers.UpdateEffectList(effects.m_flyingContinuousEffects, ref val.m_flyingContinuousEffect, scale); } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class GrowUpMethods { public static void ReadGrowUp(string folderPath, ref CreatureData creatureData) { char directorySeparatorChar = Path.DirectorySeparatorChar; string text = folderPath + directorySeparatorChar + "GrowUp.yml"; if (!File.Exists(text)) { return; } string input = File.ReadAllText(text); try { IDeserializer deserializer = new DeserializerBuilder().Build(); GrowUpData growUp = deserializer.Deserialize(input); creatureData.m_growUp = growUp; } catch { Helpers.LogParseFailure(text); } } public static void Update(GameObject critter, CreatureData creatureData) { //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_00c1: Expected O, but got Unknown GrowUpData growUp = creatureData.m_growUp; Growup val = default(Growup); if (!critter.TryGetComponent(ref val)) { return; } GameObject prefab = PrefabManager.GetPrefab(growUp.GrownPrefab); if ((Object)(object)prefab == (Object)null) { return; } val.m_growTime = growUp.GrowTime; val.m_inheritTame = growUp.InheritTame; val.m_grownPrefab = prefab; val.m_altGrownPrefabs = new List(); foreach (AltGrownData altGrownPrefab in growUp.AltGrownPrefabs) { GameObject prefab2 = PrefabManager.GetPrefab(altGrownPrefab.GrownPrefab); if (!((Object)(object)prefab2 == (Object)null)) { val.m_altGrownPrefabs.Add(new GrownEntry { m_prefab = prefab2, m_weight = altGrownPrefab.Weight }); } } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class Helpers { public static void ReadEffectInfo(string filePath, ref List effectList) { if (!File.Exists(filePath)) { return; } IDeserializer deserializer = new DeserializerBuilder().Build(); string text = File.ReadAllText(filePath); if (Utility.IsNullOrWhiteSpace(text)) { return; } try { effectList = deserializer.Deserialize>(text); } catch { LogParseFailure(filePath); } } public static void LogParseFailure(string filePath) { MonsterDBPlugin.LogDebug("Failed to parse file:"); MonsterDBPlugin.LogDebug(filePath); } public static void UpdateEffectList(List effectInfo, ref EffectList effectList, Vector3 scale) { //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Expected O, but got Unknown //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: 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_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Expected O, but got Unknown //IL_006c: Unknown result type (might be due to invalid IL or missing references) if (effectInfo.Count <= 0) { return; } List list = new List(); foreach (EffectInfo item in effectInfo) { GameObject prefab = PrefabManager.GetPrefab(item.PrefabName); if (!((Object)(object)prefab == (Object)null)) { if (Object.op_Implicit((Object)(object)prefab.GetComponent())) { prefab.transform.localScale = scale; } list.Add(new EffectData { m_prefab = prefab, m_enabled = item.Enabled, m_attach = item.Attach, m_scale = item.Scale, m_follow = item.Follow, m_variant = item.Variant, m_childTransform = item.ChildTransform, m_randomRotation = item.RandomRotation, m_inheritParentScale = item.InheritParentScale, m_multiplyParentVisualScale = item.MultiplyParentVisualScale, m_inheritParentRotation = item.InheritParentRotation }); } } effectList = new EffectList { m_effectPrefabs = list.ToArray() }; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class HumanoidMethods { public static void ReadHumanoid(string folderPath, ref CreatureData creatureData) { char directorySeparatorChar = Path.DirectorySeparatorChar; string text = folderPath + directorySeparatorChar + "Character.yml"; if (File.Exists(text)) { IDeserializer deserializer = new DeserializerBuilder().Build(); try { CharacterData characterData = deserializer.Deserialize(File.ReadAllText(text)); creatureData.m_characterData = characterData; } catch { Helpers.LogParseFailure(text); } directorySeparatorChar = Path.DirectorySeparatorChar; string text2 = folderPath + directorySeparatorChar + "Effects"; if (Directory.Exists(text2)) { directorySeparatorChar = Path.DirectorySeparatorChar; string filePath = text2 + directorySeparatorChar + "HitEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath2 = text2 + directorySeparatorChar + "CritHitEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath3 = text2 + directorySeparatorChar + "BackstabHitEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath4 = text2 + directorySeparatorChar + "DeathEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath5 = text2 + directorySeparatorChar + "WaterEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath6 = text2 + directorySeparatorChar + "TarEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath7 = text2 + directorySeparatorChar + "SlideEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath8 = text2 + directorySeparatorChar + "JumpEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath9 = text2 + directorySeparatorChar + "FlyingContinuousEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath10 = text2 + directorySeparatorChar + "PickupEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath11 = text2 + directorySeparatorChar + "DropEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath12 = text2 + directorySeparatorChar + "ConsumeItemEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath13 = text2 + directorySeparatorChar + "EquipEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath14 = text2 + directorySeparatorChar + "PerfectBlockEffects.yml"; Helpers.ReadEffectInfo(filePath, ref creatureData.m_effects.m_hitEffects); Helpers.ReadEffectInfo(filePath2, ref creatureData.m_effects.m_critHitEffects); Helpers.ReadEffectInfo(filePath3, ref creatureData.m_effects.m_backstabHitEffects); Helpers.ReadEffectInfo(filePath4, ref creatureData.m_effects.m_deathEffects); Helpers.ReadEffectInfo(filePath5, ref creatureData.m_effects.m_waterEffects); Helpers.ReadEffectInfo(filePath6, ref creatureData.m_effects.m_tarEffects); Helpers.ReadEffectInfo(filePath7, ref creatureData.m_effects.m_slideEffects); Helpers.ReadEffectInfo(filePath8, ref creatureData.m_effects.m_jumpEffects); Helpers.ReadEffectInfo(filePath9, ref creatureData.m_effects.m_flyingContinuousEffects); Helpers.ReadEffectInfo(filePath10, ref creatureData.m_effects.m_pickupEffects); Helpers.ReadEffectInfo(filePath11, ref creatureData.m_effects.m_dropEffects); Helpers.ReadEffectInfo(filePath12, ref creatureData.m_effects.m_consumeItemEffects); Helpers.ReadEffectInfo(filePath13, ref creatureData.m_effects.m_equipEffects); Helpers.ReadEffectInfo(filePath14, ref creatureData.m_effects.m_perfectBlockEffects); } directorySeparatorChar = Path.DirectorySeparatorChar; string text3 = folderPath + directorySeparatorChar + "Items"; if (Directory.Exists(text3)) { directorySeparatorChar = Path.DirectorySeparatorChar; string folderPath2 = text3 + directorySeparatorChar + "DefaultItems"; directorySeparatorChar = Path.DirectorySeparatorChar; string folderPath3 = text3 + directorySeparatorChar + "RandomWeapon"; directorySeparatorChar = Path.DirectorySeparatorChar; string folderPath4 = text3 + directorySeparatorChar + "RandomArmor"; directorySeparatorChar = Path.DirectorySeparatorChar; string folderPath5 = text3 + directorySeparatorChar + "RandomShield"; directorySeparatorChar = Path.DirectorySeparatorChar; string folderPath6 = text3 + directorySeparatorChar + "RandomSets"; directorySeparatorChar = Path.DirectorySeparatorChar; string folderPath7 = text3 + directorySeparatorChar + "RandomItems"; ReadItems(folderPath2, ref creatureData.m_defaultItems); ReadItems(folderPath3, ref creatureData.m_randomWeapons); ReadItems(folderPath4, ref creatureData.m_randomArmors); ReadItems(folderPath5, ref creatureData.m_randomShields); ReadRandomSets(folderPath6, ref creatureData.m_randomSets); ReadRandomItems(folderPath7, ref creatureData.m_randomItems); } } } private static void ReadItems(string folderPath, ref List serverData) { if (!Directory.Exists(folderPath)) { return; } IDeserializer deserializer = new DeserializerBuilder().Build(); string[] directories = Directory.GetDirectories(folderPath); string[] array = directories; foreach (string text in array) { char directorySeparatorChar = Path.DirectorySeparatorChar; string text2 = text + directorySeparatorChar + "ItemData.yml"; if (!File.Exists(text2)) { continue; } string text3 = File.ReadAllText(text2); if (!Utility.IsNullOrWhiteSpace(text3)) { try { AttackData attackData = deserializer.Deserialize(text3); ItemAttackData itemAttackData = new ItemAttackData { m_attackData = attackData }; ReadAllEffectInfo(text, ref itemAttackData); serverData.Add(itemAttackData); } catch { Helpers.LogParseFailure(text2); } } } } private static void ReadAllEffectInfo(string folderPath, ref ItemAttackData itemAttackData) { char directorySeparatorChar = Path.DirectorySeparatorChar; string text = folderPath + directorySeparatorChar + "Effects"; if (Directory.Exists(text)) { directorySeparatorChar = Path.DirectorySeparatorChar; string filePath = text + directorySeparatorChar + "HitEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath2 = text + directorySeparatorChar + "HitTerrainEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath3 = text + directorySeparatorChar + "BlockEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath4 = text + directorySeparatorChar + "StartEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath5 = text + directorySeparatorChar + "HoldStartEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath6 = text + directorySeparatorChar + "EquipEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath7 = text + directorySeparatorChar + "UnequipEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath8 = text + directorySeparatorChar + "TriggerEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath9 = text + directorySeparatorChar + "TrailStartEffects.yml"; Helpers.ReadEffectInfo(filePath, ref itemAttackData.m_effects.m_hitEffects); Helpers.ReadEffectInfo(filePath2, ref itemAttackData.m_effects.m_hitTerrainEffects); Helpers.ReadEffectInfo(filePath3, ref itemAttackData.m_effects.m_blockEffects); Helpers.ReadEffectInfo(filePath4, ref itemAttackData.m_effects.m_startEffects); Helpers.ReadEffectInfo(filePath5, ref itemAttackData.m_effects.m_holdStartEffects); Helpers.ReadEffectInfo(filePath6, ref itemAttackData.m_effects.m_equipEffects); Helpers.ReadEffectInfo(filePath7, ref itemAttackData.m_effects.m_unEquipEffects); Helpers.ReadEffectInfo(filePath8, ref itemAttackData.m_effects.m_triggerEffects); Helpers.ReadEffectInfo(filePath9, ref itemAttackData.m_effects.m_trailStartEffects); } } private static void ReadRandomSets(string folderPath, ref List serverData) { if (!Directory.Exists(folderPath)) { return; } string[] directories = Directory.GetDirectories(folderPath); List list = new List(); string[] array = directories; foreach (string text in array) { string fileName = Path.GetFileName(text); if (fileName != null) { RandomItemSetsData randomItemSetsData = new RandomItemSetsData { m_name = fileName }; ReadItems(text, ref randomItemSetsData.m_items); list.Add(randomItemSetsData); } } serverData = list; } private static void ReadRandomItems(string folderPath, ref List serverData) { if (!Directory.Exists(folderPath)) { return; } char directorySeparatorChar = Path.DirectorySeparatorChar; string text = folderPath + directorySeparatorChar + "RandomItems.yml"; if (!File.Exists(text)) { return; } IDeserializer deserializer = new DeserializerBuilder().Build(); string input = File.ReadAllText(text); try { serverData = deserializer.Deserialize>(input); } catch { Helpers.LogParseFailure(text); } } public static void Update(GameObject critter, CreatureData creatureData) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_0245: Unknown result type (might be due to invalid IL or missing references) //IL_0266: 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_0289: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_02ac: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: 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_02d1: Unknown result type (might be due to invalid IL or missing references) //IL_02f2: Unknown result type (might be due to invalid IL or missing references) //IL_02f4: Unknown result type (might be due to invalid IL or missing references) //IL_0315: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Unknown result type (might be due to invalid IL or missing references) //IL_0338: Unknown result type (might be due to invalid IL or missing references) //IL_033a: Unknown result type (might be due to invalid IL or missing references) //IL_035b: Unknown result type (might be due to invalid IL or missing references) //IL_035d: 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_03bd: Unknown result type (might be due to invalid IL or missing references) //IL_03d0: Unknown result type (might be due to invalid IL or missing references) //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03f7: Unknown result type (might be due to invalid IL or missing references) //IL_040a: Unknown result type (might be due to invalid IL or missing references) //IL_041d: Unknown result type (might be due to invalid IL or missing references) //IL_0430: Unknown result type (might be due to invalid IL or missing references) //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_0456: Unknown result type (might be due to invalid IL or missing references) //IL_0469: Unknown result type (might be due to invalid IL or missing references) //IL_047c: Unknown result type (might be due to invalid IL or missing references) //IL_048f: Unknown result type (might be due to invalid IL or missing references) //IL_04a2: Unknown result type (might be due to invalid IL or missing references) //IL_0515: Unknown result type (might be due to invalid IL or missing references) //IL_0529: 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_0551: Unknown result type (might be due to invalid IL or missing references) //IL_0565: Unknown result type (might be due to invalid IL or missing references) //IL_0579: Unknown result type (might be due to invalid IL or missing references) //IL_037e: Unknown result type (might be due to invalid IL or missing references) //IL_0380: Unknown result type (might be due to invalid IL or missing references) Humanoid val = default(Humanoid); if (critter.TryGetComponent(ref val)) { CharacterData characterData = creatureData.m_characterData; CharacterEffects effects = creatureData.m_effects; Vector3 scale = creatureData.m_scale.ToRef(); Vector3 scale2 = creatureData.m_ragdollScale.ToRef(); ((Character)val).m_name = characterData.Name; ((Character)val).m_group = characterData.Group; if (Enum.TryParse(characterData.Faction, ignoreCase: true, out Faction result)) { ((Character)val).m_faction = result; } ((Character)val).m_boss = characterData.Boss; ((Character)val).m_dontHideBossHud = characterData.DoNotHideBossHUD; ((Character)val).m_bossEvent = characterData.BossEvent; ((Character)val).m_defeatSetGlobalKey = characterData.DefeatSetGlobalKey; ((Character)val).m_aiSkipTarget = characterData.AISkipTarget; ((Character)val).m_crouchSpeed = characterData.CrouchSpeed; ((Character)val).m_walkSpeed = characterData.WalkSpeed; ((Character)val).m_speed = characterData.Speed; ((Character)val).m_turnSpeed = characterData.TurnSpeed; ((Character)val).m_runSpeed = characterData.RunSpeed; ((Character)val).m_runTurnSpeed = characterData.RunTurnSpeed; ((Character)val).m_flySlowSpeed = characterData.FlySlowSpeed; ((Character)val).m_flyFastSpeed = characterData.FlyFastSpeed; ((Character)val).m_flyTurnSpeed = characterData.FlyTurnSpeed; ((Character)val).m_acceleration = characterData.Acceleration; ((Character)val).m_jumpForce = characterData.JumpForce; ((Character)val).m_jumpForceForward = characterData.JumpForceForward; ((Character)val).m_jumpForceTiredFactor = characterData.JumpForceTiredFactor; ((Character)val).m_airControl = characterData.AirControl; ((Character)val).m_canSwim = characterData.CanSwim; ((Character)val).m_swimDepth = characterData.SwimDepth; ((Character)val).m_swimTurnSpeed = characterData.SwimTurnSpeed; ((Character)val).m_swimAcceleration = characterData.SwimAcceleration; if (Enum.TryParse(characterData.GroundTilt, ignoreCase: true, out GroundTiltType result2)) { ((Character)val).m_groundTilt = result2; } ((Character)val).m_swimSpeed = characterData.SwimSpeed; ((Character)val).m_groundTiltSpeed = characterData.GroundTiltSpeed; ((Character)val).m_flying = characterData.Flying; ((Character)val).m_jumpStaminaUsage = characterData.JumpStaminaUsage; ((Character)val).m_disableWhileSleeping = characterData.DisableWhileSleeping; ((Character)val).m_tolerateWater = characterData.TolerateWater; ((Character)val).m_tolerateFire = characterData.TolerateFire; ((Character)val).m_tolerateSmoke = characterData.TolerateSmoke; ((Character)val).m_tolerateTar = characterData.TolerateTar; ((Character)val).m_health = characterData.Health; if (Enum.TryParse(characterData.BluntResistance, ignoreCase: true, out DamageModifier result3)) { ((Character)val).m_damageModifiers.m_blunt = result3; } if (Enum.TryParse(characterData.SlashResistance, ignoreCase: true, out DamageModifier result4)) { ((Character)val).m_damageModifiers.m_slash = result4; } if (Enum.TryParse(characterData.PierceResistance, ignoreCase: true, out DamageModifier result5)) { ((Character)val).m_damageModifiers.m_pierce = result5; } if (Enum.TryParse(characterData.ChopResistance, ignoreCase: true, out DamageModifier result6)) { ((Character)val).m_damageModifiers.m_chop = result6; } if (Enum.TryParse(characterData.PickaxeResistance, ignoreCase: true, out DamageModifier result7)) { ((Character)val).m_damageModifiers.m_pickaxe = result7; } if (Enum.TryParse(characterData.FireResistance, ignoreCase: true, out DamageModifier result8)) { ((Character)val).m_damageModifiers.m_fire = result8; } if (Enum.TryParse(characterData.FrostResistance, ignoreCase: true, out DamageModifier result9)) { ((Character)val).m_damageModifiers.m_frost = result9; } if (Enum.TryParse(characterData.LightningResistance, ignoreCase: true, out DamageModifier result10)) { ((Character)val).m_damageModifiers.m_lightning = result10; } if (Enum.TryParse(characterData.PoisonResistance, ignoreCase: true, out DamageModifier result11)) { ((Character)val).m_damageModifiers.m_poison = result11; } if (Enum.TryParse(characterData.SpiritResistance, ignoreCase: true, out DamageModifier result12)) { ((Character)val).m_damageModifiers.m_spirit = result12; } ((Character)val).m_staggerWhenBlocked = characterData.StaggerWhenBlocked; ((Character)val).m_staggerDamageFactor = characterData.StaggerDamageFactor; Helpers.UpdateEffectList(effects.m_hitEffects, ref ((Character)val).m_hitEffects, scale); Helpers.UpdateEffectList(effects.m_critHitEffects, ref ((Character)val).m_critHitEffects, scale); Helpers.UpdateEffectList(effects.m_backstabHitEffects, ref ((Character)val).m_backstabHitEffects, scale); Helpers.UpdateEffectList(effects.m_deathEffects, ref ((Character)val).m_deathEffects, scale2); Helpers.UpdateEffectList(effects.m_waterEffects, ref ((Character)val).m_waterEffects, scale); Helpers.UpdateEffectList(effects.m_tarEffects, ref ((Character)val).m_tarEffects, scale); Helpers.UpdateEffectList(effects.m_slideEffects, ref ((Character)val).m_slideEffects, scale); Helpers.UpdateEffectList(effects.m_jumpEffects, ref ((Character)val).m_jumpEffects, scale); Helpers.UpdateEffectList(effects.m_flyingContinuousEffects, ref ((Character)val).m_flyingContinuousEffect, scale); Helpers.UpdateEffectList(effects.m_pickupEffects, ref val.m_pickupEffects, scale); Helpers.UpdateEffectList(effects.m_dropEffects, ref val.m_dropEffects, scale); Helpers.UpdateEffectList(effects.m_consumeItemEffects, ref val.m_consumeItemEffects, scale); Helpers.UpdateEffectList(effects.m_equipEffects, ref val.m_equipEffects, scale); Helpers.UpdateEffectList(effects.m_perfectBlockEffects, ref val.m_perfectBlockEffect, scale); val.m_defaultItems = new List().ToArray(); val.m_randomWeapon = new List().ToArray(); val.m_randomShield = new List().ToArray(); val.m_randomArmor = new List().ToArray(); val.m_randomSets = new List().ToArray(); val.m_randomItems = new List().ToArray(); UpdateItems(ref val.m_defaultItems, creatureData.m_defaultItems, scale, creatureData); UpdateItems(ref val.m_randomWeapon, creatureData.m_randomWeapons, scale, creatureData); UpdateItems(ref val.m_randomShield, creatureData.m_randomShields, scale, creatureData); UpdateItems(ref val.m_randomArmor, creatureData.m_randomArmors, scale, creatureData); UpdateRandomSets(ref val.m_randomSets, creatureData.m_randomSets, scale, creatureData); UpdateRandomItems(ref val.m_randomItems, creatureData.m_randomItems, scale); } } private static void UpdateItems(ref GameObject[] list, List itemAttackDataList, Vector3 scale, CreatureData creatureData) { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_0351: Unknown result type (might be due to invalid IL or missing references) //IL_0353: Unknown result type (might be due to invalid IL or missing references) //IL_06a4: Unknown result type (might be due to invalid IL or missing references) //IL_06c3: Unknown result type (might be due to invalid IL or missing references) //IL_06e2: Unknown result type (might be due to invalid IL or missing references) //IL_0701: Unknown result type (might be due to invalid IL or missing references) //IL_0720: Unknown result type (might be due to invalid IL or missing references) //IL_073f: Unknown result type (might be due to invalid IL or missing references) //IL_075e: Unknown result type (might be due to invalid IL or missing references) //IL_077d: Unknown result type (might be due to invalid IL or missing references) //IL_079c: Unknown result type (might be due to invalid IL or missing references) if (itemAttackDataList.Count <= 0) { return; } List list2 = new List(); ItemDrop val = default(ItemDrop); foreach (ItemAttackData itemAttackData in itemAttackDataList) { AttackData attackData = itemAttackData.m_attackData; ItemEffects effects = itemAttackData.m_effects; string name = attackData.Name; GameObject prefab = PrefabManager.GetPrefab(name); if (prefab != null && prefab.TryGetComponent(ref val)) { ScaleItem(prefab, scale); UpdateMaterial(itemAttackData.m_attackData.MaterialOverride, creatureData.m_materials, ((Component)val).gameObject); if (Enum.TryParse(attackData.AnimationState, ignoreCase: true, out AnimationState result)) { val.m_itemData.m_shared.m_animationState = result; } val.m_itemData.m_shared.m_toolTier = attackData.ToolTier; val.m_itemData.m_shared.m_damages.m_damage = attackData.Damage; val.m_itemData.m_shared.m_damages.m_blunt = attackData.Blunt; val.m_itemData.m_shared.m_damages.m_slash = attackData.Slash; val.m_itemData.m_shared.m_damages.m_pierce = attackData.Pierce; val.m_itemData.m_shared.m_damages.m_chop = attackData.Chop; val.m_itemData.m_shared.m_damages.m_pickaxe = attackData.Pickaxe; val.m_itemData.m_shared.m_damages.m_fire = attackData.Fire; val.m_itemData.m_shared.m_damages.m_frost = attackData.Frost; val.m_itemData.m_shared.m_damages.m_lightning = attackData.Lightning; val.m_itemData.m_shared.m_damages.m_poison = attackData.Poison; val.m_itemData.m_shared.m_damages.m_spirit = attackData.Spirit; val.m_itemData.m_shared.m_attackForce = attackData.AttackForce; val.m_itemData.m_shared.m_dodgeable = attackData.Dodgeable; val.m_itemData.m_shared.m_blockable = attackData.Blockable; val.m_itemData.m_shared.m_spawnOnHit = null; val.m_itemData.m_shared.m_spawnOnHitTerrain = null; val.m_itemData.m_shared.m_attackStatusEffect = null; if (TryGetGameObject(attackData.SpawnOnHit, out var prefab2)) { val.m_itemData.m_shared.m_spawnOnHit = prefab2; } if (TryGetGameObject(attackData.SpawnOnHitTerrain, out var prefab3)) { val.m_itemData.m_shared.m_spawnOnHitTerrain = prefab3; } if (TryGetStatusEffect(attackData.AttackStatusEffect, out var statusEffect)) { val.m_itemData.m_shared.m_attackStatusEffect = statusEffect; } val.m_itemData.m_shared.m_attackStatusEffectChance = attackData.AttackStatusEffectChance; if (Enum.TryParse(attackData.AttackType, out AttackType result2)) { val.m_itemData.m_shared.m_attack.m_attackType = result2; } val.m_itemData.m_shared.m_attack.m_attackAnimation = attackData.AttackAnimation; val.m_itemData.m_shared.m_attack.m_hitTerrain = attackData.HitTerrain; val.m_itemData.m_shared.m_attack.m_hitFriendly = attackData.HitFriendly; val.m_itemData.m_shared.m_attack.m_damageMultiplier = attackData.DamageMultiplier; val.m_itemData.m_shared.m_attack.m_damageMultiplierPerMissingHP = attackData.DamageMultiplierPerMissingHP; val.m_itemData.m_shared.m_attack.m_damageMultiplierByTotalHealthMissing = attackData.DamageMultiplierByTotalHealthMissing; val.m_itemData.m_shared.m_attack.m_forceMultiplier = attackData.ForceMultiplier; val.m_itemData.m_shared.m_attack.m_staggerMultiplier = attackData.StaggerMultiplier; val.m_itemData.m_shared.m_attack.m_recoilPushback = attackData.RecoilPushback; val.m_itemData.m_shared.m_attack.m_selfDamage = attackData.SelfDamage; val.m_itemData.m_shared.m_attack.m_attackOriginJoint = attackData.AttackOriginJoint; val.m_itemData.m_shared.m_attack.m_attackRange = attackData.AttackRange; val.m_itemData.m_shared.m_attack.m_attackHeight = attackData.AttackHeight; val.m_itemData.m_shared.m_attack.m_attackOffset = attackData.AttackOffset; val.m_itemData.m_shared.m_attack.m_spawnOnTrigger = null; if (TryGetGameObject(attackData.SpawnOnTrigger, out var prefab4)) { val.m_itemData.m_shared.m_attack.m_spawnOnTrigger = prefab4; } val.m_itemData.m_shared.m_attack.m_toggleFlying = attackData.ToggleFlying; val.m_itemData.m_shared.m_attack.m_attach = attackData.Attach; val.m_itemData.m_shared.m_attack.m_attackAngle = attackData.AttackAngle; val.m_itemData.m_shared.m_attack.m_attackRayWidth = attackData.AttackRayWidth; val.m_itemData.m_shared.m_attack.m_maxYAngle = attackData.MaxYAngle; val.m_itemData.m_shared.m_attack.m_lowerDamagePerHit = attackData.LowerDamagePerHit; val.m_itemData.m_shared.m_attack.m_hitThroughWalls = attackData.HitThroughWalls; val.m_itemData.m_shared.m_aiAttackRangeMin = attackData.AttackRangeMinimum; val.m_itemData.m_shared.m_aiAttackInterval = attackData.AttackInterval; val.m_itemData.m_shared.m_aiAttackMaxAngle = attackData.AttackMaxAngle; val.m_itemData.m_shared.m_attack.m_attackProjectile = null; if (TryGetGameObject(attackData.Projectile, out var prefab5)) { val.m_itemData.m_shared.m_attack.m_attackProjectile = prefab5; } Helpers.UpdateEffectList(effects.m_hitEffects, ref val.m_itemData.m_shared.m_hitEffect, scale); Helpers.UpdateEffectList(effects.m_hitTerrainEffects, ref val.m_itemData.m_shared.m_hitTerrainEffect, scale); Helpers.UpdateEffectList(effects.m_blockEffects, ref val.m_itemData.m_shared.m_blockEffect, scale); Helpers.UpdateEffectList(effects.m_startEffects, ref val.m_itemData.m_shared.m_startEffect, scale); Helpers.UpdateEffectList(effects.m_holdStartEffects, ref val.m_itemData.m_shared.m_holdStartEffect, scale); Helpers.UpdateEffectList(effects.m_equipEffects, ref val.m_itemData.m_shared.m_equipEffect, scale); Helpers.UpdateEffectList(effects.m_unEquipEffects, ref val.m_itemData.m_shared.m_unequipEffect, scale); Helpers.UpdateEffectList(effects.m_triggerEffects, ref val.m_itemData.m_shared.m_triggerEffect, scale); Helpers.UpdateEffectList(effects.m_trailStartEffects, ref val.m_itemData.m_shared.m_trailStartEffect, scale); list2.Add(prefab); } } list = list2.ToArray(); } private static void UpdateMaterial(string materialName, Dictionary materialDataList, GameObject prefab) { //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Expected O, but got Unknown //IL_00a1: Unknown result type (might be due to invalid IL or missing references) if (Utility.IsNullOrWhiteSpace(materialName) || !materialDataList.TryGetValue(materialName, out var value)) { return; } Renderer componentInChildren = prefab.GetComponentInChildren(); if (componentInChildren == null) { return; } List list = new List(); Material[] sharedMaterials = componentInChildren.sharedMaterials; foreach (Material val in sharedMaterials) { Material val2 = new Material(val); val2.mainTexture = TextureManager.GetTexture(value._MainTex, val2.mainTexture); if (val2.HasProperty(ShaderRef._EmissionColor)) { val.SetColor(ShaderRef._EmissionColor, VisualMethods.GetColor(value._EmissionColor)); } if (val2.HasProperty(ShaderRef._Hue)) { val.SetFloat(ShaderRef._Hue, value._Hue); } if (val2.HasProperty(ShaderRef._Value)) { val.SetFloat(ShaderRef._Value, value._Value); } if (val2.HasProperty(ShaderRef._Saturation)) { val.SetFloat(ShaderRef._Saturation, value._Saturation); } list.Add(val2); } componentInChildren.sharedMaterials = list.ToArray(); componentInChildren.materials = list.ToArray(); } private static bool TryGetGameObject(string prefabName, out GameObject prefab) { prefab = null; if (Utility.IsNullOrWhiteSpace(prefabName)) { return false; } GameObject prefab2 = PrefabManager.GetPrefab(prefabName); if ((Object)(object)prefab2 == (Object)null) { return false; } prefab = prefab2; return true; } private static bool TryGetStatusEffect(string effectName, out StatusEffect statusEffect) { statusEffect = null; if (Utility.IsNullOrWhiteSpace(effectName)) { return false; } statusEffect = PrefabManager.GetStatusEffect(effectName); return (Object)(object)statusEffect != (Object)null; } public static void UpdateRandomSets(ref ItemSet[] list, List data, Vector3 scale, CreatureData creatureData) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) if (data.Count <= 0) { return; } List list2 = new List(); foreach (RandomItemSetsData datum in data) { string name = datum.m_name; ItemSet val = new ItemSet { m_name = name }; UpdateItems(ref val.m_items, datum.m_items, scale, creatureData); list2.Add(val); } list = list2.ToArray(); } public static void UpdateRandomItems(ref RandomItem[] list, List randomItemDataList, Vector3 scale) { //IL_004e: 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_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Expected O, but got Unknown if (randomItemDataList.Count <= 0) { return; } List list2 = new List(); foreach (RandomItemData randomItemData in randomItemDataList) { GameObject prefab = PrefabManager.GetPrefab(randomItemData.PrefabName); if (!((Object)(object)prefab == (Object)null)) { ScaleItem(prefab, scale); list2.Add(new RandomItem { m_prefab = prefab, m_chance = randomItemData.Chance }); } } list = list2.ToArray(); } private static void ScaleItem(GameObject prefab, Vector3 scale) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) Transform val = prefab.transform.Find("attach"); if (Object.op_Implicit((Object)(object)val)) { ((Component)val).transform.localScale = scale; } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class LevelEffectsMethods { public static void ReadLevelEffects(string folderPath, ref CreatureData creatureData) { char directorySeparatorChar = Path.DirectorySeparatorChar; string text = folderPath + directorySeparatorChar + "LevelEffects.yml"; if (!File.Exists(text)) { return; } IDeserializer deserializer = new DeserializerBuilder().Build(); try { string input = File.ReadAllText(text); creatureData.m_levelEffects = deserializer.Deserialize>(input); } catch { Helpers.LogParseFailure(text); } } public static void Update(GameObject critter, CreatureData creatureData) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_004c: 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_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected O, but got Unknown LevelEffects componentInChildren = critter.GetComponentInChildren(); if ((Object)(object)componentInChildren == (Object)null) { return; } List list = new List(); foreach (LevelEffectData levelEffect in creatureData.m_levelEffects) { LevelSetup val = new LevelSetup { m_scale = levelEffect.Scale, m_hue = levelEffect.Hue, m_saturation = levelEffect.Saturation, m_value = levelEffect.Value, m_setEmissiveColor = levelEffect.SetEmissiveColor, m_emissiveColor = VisualMethods.GetColor(levelEffect.EmissiveColor) }; if (!Utility.IsNullOrWhiteSpace(levelEffect.EnableObject)) { Transform val2 = Utils.FindChild(critter.transform, levelEffect.EnableObject, (IterativeSearchType)0); if ((Object)(object)val2 != (Object)null) { val.m_enableObject = ((Component)val2).gameObject; } } list.Add(val); } componentInChildren.m_levelSetups = list; } } [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static class MonsterAIMethods { public static void ReadMonsterAI(string folderPath, ref CreatureData creatureData) { char directorySeparatorChar = Path.DirectorySeparatorChar; string text = folderPath + directorySeparatorChar + "MonsterAI.yml"; if (!File.Exists(text)) { return; } string text2 = File.ReadAllText(text); if (!Utility.IsNullOrWhiteSpace(text2)) { IDeserializer deserializer = new DeserializerBuilder().Build(); try { MonsterAIData monsterAIData = deserializer.Deserialize(text2); creatureData.m_monsterAIData = monsterAIData; } catch { Helpers.LogParseFailure(text); } directorySeparatorChar = Path.DirectorySeparatorChar; string text3 = folderPath + directorySeparatorChar + "Effects"; if (Directory.Exists(text3)) { directorySeparatorChar = Path.DirectorySeparatorChar; string filePath = text3 + directorySeparatorChar + "AlertedEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath2 = text3 + directorySeparatorChar + "IdleSounds.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath3 = text3 + directorySeparatorChar + "WakeupEffects.yml"; Helpers.ReadEffectInfo(filePath, ref creatureData.m_effects.m_alertedEffects); Helpers.ReadEffectInfo(filePath2, ref creatureData.m_effects.m_idleSounds); Helpers.ReadEffectInfo(filePath3, ref creatureData.m_effects.m_wakeupEffects); } } } public static void Update(GameObject critter, CreatureData creatureData) { //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_0416: Unknown result type (might be due to invalid IL or missing references) //IL_042e: Unknown result type (might be due to invalid IL or missing references) //IL_0446: Unknown result type (might be due to invalid IL or missing references) MonsterAI val = default(MonsterAI); if (!critter.TryGetComponent(ref val)) { return; } MonsterAIData monsterAIData = creatureData.m_monsterAIData; Vector3 scale = default(Vector3); ((Vector3)(ref scale))..ctor(creatureData.m_scale.x, creatureData.m_scale.y, creatureData.m_scale.z); ((BaseAI)val).m_viewRange = monsterAIData.ViewRange; ((BaseAI)val).m_viewAngle = monsterAIData.ViewAngle; ((BaseAI)val).m_hearRange = monsterAIData.HearRange; ((BaseAI)val).m_mistVision = monsterAIData.MistVision; ((BaseAI)val).m_idleSoundInterval = monsterAIData.IdleSoundInterval; ((BaseAI)val).m_idleSoundChance = monsterAIData.IdleSoundChance; if (!Enum.TryParse(monsterAIData.PathAgentType, ignoreCase: true, out AgentType result)) { ((BaseAI)val).m_pathAgentType = result; } ((BaseAI)val).m_moveMinAngle = monsterAIData.MoveMinAngle; ((BaseAI)val).m_smoothMovement = monsterAIData.SmoothMovement; ((BaseAI)val).m_serpentMovement = monsterAIData.SerpentMovement; ((BaseAI)val).m_serpentTurnRadius = monsterAIData.SerpentTurnRadius; ((BaseAI)val).m_jumpInterval = monsterAIData.JumpInterval; ((BaseAI)val).m_randomCircleInterval = monsterAIData.RandomCircleInterval; ((BaseAI)val).m_randomMoveInterval = monsterAIData.RandomMoveInterval; ((BaseAI)val).m_randomMoveRange = monsterAIData.RandomMoveRange; ((BaseAI)val).m_randomFly = monsterAIData.RandomFly; ((BaseAI)val).m_chanceToTakeoff = monsterAIData.ChanceToTakeOff; ((BaseAI)val).m_chanceToLand = monsterAIData.ChanceToLand; ((BaseAI)val).m_groundDuration = monsterAIData.GroundDuration; ((BaseAI)val).m_airDuration = monsterAIData.AirDuration; ((BaseAI)val).m_maxLandAltitude = monsterAIData.MaxLandAltitude; ((BaseAI)val).m_takeoffTime = monsterAIData.TakeoffTime; ((BaseAI)val).m_flyAltitudeMin = monsterAIData.FlyAltitudeMin; ((BaseAI)val).m_flyAltitudeMax = monsterAIData.FlyAltitudeMax; ((BaseAI)val).m_flyAbsMinAltitude = monsterAIData.FlyAbsMinAltitude; ((BaseAI)val).m_avoidFire = monsterAIData.AvoidFire; ((BaseAI)val).m_afraidOfFire = monsterAIData.AfraidOfFire; ((BaseAI)val).m_avoidWater = monsterAIData.AvoidWater; ((BaseAI)val).m_avoidLava = monsterAIData.AvoidLava; ((BaseAI)val).m_skipLavaTargets = monsterAIData.SkipLavaTargets; ((BaseAI)val).m_aggravatable = monsterAIData.Aggravatable; ((BaseAI)val).m_passiveAggresive = monsterAIData.PassiveAggressive; ((BaseAI)val).m_spawnMessage = monsterAIData.SpawnMessage; ((BaseAI)val).m_deathMessage = monsterAIData.DeathMessage; ((BaseAI)val).m_alertedMessage = monsterAIData.AlertedMessage; ((BaseAI)val).m_fleeRange = monsterAIData.FleeRange; ((BaseAI)val).m_fleeAngle = monsterAIData.FleeAngle; ((BaseAI)val).m_fleeInterval = monsterAIData.FleeInterval; val.m_alertRange = monsterAIData.AlertRange; val.m_fleeIfHurtWhenTargetCantBeReached = monsterAIData.FleeIfHurtWhenTargetCannotBeReached; val.m_fleeUnreachableSinceAttacking = monsterAIData.FleeUnreachableSinceAttack; val.m_fleeUnreachableSinceHurt = monsterAIData.FleeUnreachableSinceHurt; val.m_fleeIfNotAlerted = monsterAIData.FleeIfNotAlerted; val.m_fleeTimeSinceHurt = monsterAIData.FleeTimeSinceHurt; val.m_fleeIfLowHealth = monsterAIData.FleeIfLowHealth; val.m_fleeInLava = monsterAIData.FleeInLava; val.m_circulateWhileCharging = monsterAIData.CirculateWhileCharging; val.m_circulateWhileChargingFlying = monsterAIData.CirculateWhileChargingFlying; val.m_enableHuntPlayer = monsterAIData.EnableHuntPlayer; val.m_attackPlayerObjects = monsterAIData.AttackPlayerObjects; val.m_privateAreaTriggerTreshold = monsterAIData.PrivateAreaTriggerThreshold; val.m_interceptTimeMax = monsterAIData.InterceptTimeMax; val.m_interceptTimeMin = monsterAIData.InterceptTimeMin; val.m_maxChaseDistance = monsterAIData.MaxChaseDistance; val.m_minAttackInterval = monsterAIData.MinAttackInterval; val.m_circleTargetInterval = monsterAIData.CircleTargetInterval; val.m_circleTargetDuration = monsterAIData.CircleTargetDuration; val.m_circleTargetDistance = monsterAIData.CircleTargetDistance; val.m_sleeping = monsterAIData.Sleeping; val.m_wakeupRange = monsterAIData.WakeupRange; val.m_noiseWakeup = monsterAIData.NoiseWakeup; val.m_maxNoiseWakeupRange = monsterAIData.MaxNoiseWakeupRange; val.m_wakeUpDelayMin = monsterAIData.WakeupDelayMin; val.m_wakeUpDelayMax = monsterAIData.WakeupDelayMax; val.m_avoidLand = monsterAIData.AvoidLand; val.m_consumeRange = monsterAIData.ConsumeRange; val.m_consumeSearchRange = monsterAIData.ConsumeSearchRange; val.m_consumeSearchInterval = monsterAIData.ConsumeSearchInterval; val.m_consumeItems = new List(); ItemDrop item = default(ItemDrop); foreach (string consumeItem in monsterAIData.ConsumeItems) { GameObject prefab = PrefabManager.GetPrefab(consumeItem); if (!((Object)(object)prefab == (Object)null) && prefab.TryGetComponent(ref item)) { val.m_consumeItems.Add(item); } } Helpers.UpdateEffectList(creatureData.m_effects.m_alertedEffects, ref ((BaseAI)val).m_alertedEffects, scale); Helpers.UpdateEffectList(creatureData.m_effects.m_idleSounds, ref ((BaseAI)val).m_idleSound, scale); Helpers.UpdateEffectList(creatureData.m_effects.m_wakeupEffects, ref val.m_wakeupEffects, scale); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class NPCTalkMethods { public static void ReadNPCTalk(string folderPath, ref CreatureData creatureData) { char directorySeparatorChar = Path.DirectorySeparatorChar; string text = folderPath + directorySeparatorChar + "NPCTalk.yml"; if (!File.Exists(text)) { return; } IDeserializer deserializer = new DeserializerBuilder().Build(); string text2 = File.ReadAllText(text); if (!Utility.IsNullOrWhiteSpace(text2)) { try { creatureData.m_npcTalk = deserializer.Deserialize(text2); } catch { Helpers.LogParseFailure(text); } directorySeparatorChar = Path.DirectorySeparatorChar; string text3 = folderPath + directorySeparatorChar + "Effects"; if (Directory.Exists(text3)) { directorySeparatorChar = Path.DirectorySeparatorChar; string filePath = text3 + directorySeparatorChar + "RandomTalkFX.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath2 = text3 + directorySeparatorChar + "RandomGreetFX.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath3 = text3 + directorySeparatorChar + "RandomGoodbyeFX.yml"; Helpers.ReadEffectInfo(filePath, ref creatureData.m_effects.m_randomTalkFX); Helpers.ReadEffectInfo(filePath2, ref creatureData.m_effects.m_randomGreetFX); Helpers.ReadEffectInfo(filePath3, ref creatureData.m_effects.m_randomGoodbyeFX); } } } public static void Update(GameObject critter, CreatureData creatureData) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) NpcTalk val = default(NpcTalk); if (Object.op_Implicit((Object)(object)critter.GetComponent()) && critter.TryGetComponent(ref val)) { NPCTalkData npcTalk = creatureData.m_npcTalk; Vector3 scale = creatureData.m_scale.ToRef(); val.m_name = npcTalk.Name; val.m_maxRange = npcTalk.MaxRange; val.m_greetRange = npcTalk.GreetRange; val.m_byeRange = npcTalk.ByeRange; val.m_offset = npcTalk.Offset; val.m_minTalkInterval = npcTalk.MinTalkInterval; val.m_hideDialogDelay = npcTalk.HideDialogueDelay; val.m_randomTalkInterval = npcTalk.RandomTalkInterval; val.m_randomTalkChance = npcTalk.RandomTalkChance; val.m_randomTalk = npcTalk.RandomTalk; val.m_randomTalkInFactionBase = npcTalk.RandomTalkInFactionBase; val.m_randomGreets = npcTalk.RandomGreets; val.m_randomGoodbye = npcTalk.RandomGoodbye; val.m_privateAreaAlarm = npcTalk.PrivateAreaAlarm; val.m_aggravated = npcTalk.Aggravated; Helpers.UpdateEffectList(creatureData.m_effects.m_randomTalkFX, ref val.m_randomTalkFX, scale); Helpers.UpdateEffectList(creatureData.m_effects.m_randomGreetFX, ref val.m_randomGreetFX, scale); Helpers.UpdateEffectList(creatureData.m_effects.m_randomGoodbyeFX, ref val.m_randomGoodbyeFX, scale); } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class ProcreationMethods { public static void ReadProcreation(string folderPath, ref CreatureData creatureData) { char directorySeparatorChar = Path.DirectorySeparatorChar; string text = folderPath + directorySeparatorChar + "Procreation.yml"; if (!File.Exists(text)) { return; } string text2 = File.ReadAllText(text); if (!Utility.IsNullOrWhiteSpace(text2)) { IDeserializer deserializer = new DeserializerBuilder().Build(); try { ProcreationData procreation = deserializer.Deserialize(text2); creatureData.m_procreation = procreation; } catch { Helpers.LogParseFailure(text); } directorySeparatorChar = Path.DirectorySeparatorChar; string text3 = folderPath + directorySeparatorChar + "Effects"; if (Directory.Exists(text3)) { directorySeparatorChar = Path.DirectorySeparatorChar; string filePath = text3 + directorySeparatorChar + "BirthEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath2 = text3 + directorySeparatorChar + "LoveEffects.yml"; Helpers.ReadEffectInfo(filePath, ref creatureData.m_effects.m_birthEffects); Helpers.ReadEffectInfo(filePath2, ref creatureData.m_effects.m_loveEffects); } } } public static void Update(GameObject critter, CreatureData creatureData) { //IL_0060: 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_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) ProcreationData procreation = creatureData.m_procreation; Procreation val = default(Procreation); if (Object.op_Implicit((Object)(object)critter.GetComponent()) && Object.op_Implicit((Object)(object)critter.GetComponent()) && Object.op_Implicit((Object)(object)critter.GetComponent()) && critter.TryGetComponent(ref val)) { Vector3 scale = creatureData.m_scale.ToRef(); GameObject prefab = PrefabManager.GetPrefab(procreation.Offspring); if (!((Object)(object)prefab == (Object)null)) { val.m_updateInterval = procreation.UpdateInterval; val.m_totalCheckRange = procreation.TotalCheckRange; val.m_maxCreatures = procreation.MaxCreatures; val.m_partnerCheckRange = procreation.PartnerCheckRange; val.m_pregnancyChance = procreation.PregnancyChance; val.m_pregnancyDuration = procreation.PregnancyDuration; val.m_requiredLovePoints = procreation.RequiredLovePoints; val.m_offspring = prefab; val.m_minOffspringLevel = procreation.MinOffspringLevel; val.m_spawnOffset = procreation.SpawnOffset; Helpers.UpdateEffectList(creatureData.m_effects.m_birthEffects, ref val.m_birthEffects, scale); Helpers.UpdateEffectList(creatureData.m_effects.m_loveEffects, ref val.m_loveEffects, scale); } } } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] public static class TameableMethods { public static void ReadTameable(string folderPath, ref CreatureData creatureData) { char directorySeparatorChar = Path.DirectorySeparatorChar; string text = folderPath + directorySeparatorChar + "Tameable.yml"; if (!File.Exists(text)) { return; } IDeserializer deserializer = new DeserializerBuilder().Build(); string text2 = File.ReadAllText(text); if (!Utility.IsNullOrWhiteSpace(text2)) { try { TameableData tameable = deserializer.Deserialize(text2); creatureData.m_tameable = tameable; } catch { Helpers.LogParseFailure(text); } directorySeparatorChar = Path.DirectorySeparatorChar; string text3 = folderPath + directorySeparatorChar + "Effects"; if (Directory.Exists(text3)) { directorySeparatorChar = Path.DirectorySeparatorChar; string filePath = text3 + directorySeparatorChar + "TamedEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath2 = text3 + directorySeparatorChar + "SoothEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath3 = text3 + directorySeparatorChar + "PetEffects.yml"; directorySeparatorChar = Path.DirectorySeparatorChar; string filePath4 = text3 + directorySeparatorChar + "UnsummonEffects.yml"; Helpers.ReadEffectInfo(filePath, ref creatureData.m_effects.m_tamedEffects); Helpers.ReadEffectInfo(filePath2, ref creatureData.m_effects.m_soothEffects); Helpers.ReadEffectInfo(filePath3, ref creatureData.m_effects.m_petEffects); Helpers.ReadEffectInfo(filePath4, ref creatureData.m_effects.m_unSummonEffects); } } } public static void Update(GameObject critter, CreatureData creatureData) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_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) TameableData tameable = creatureData.m_tameable; Vector3 scale = creatureData.m_scale.ToRef(); Tameable val = default(Tameable); if (critter.TryGetComponent(ref val)) { val.m_fedDuration = tameable.FedDuration; val.m_tamingTime = tameable.TamingTime; val.m_startsTamed = tameable.StartTamed; val.m_commandable = tameable.Commandable; val.m_unsummonDistance = tameable.UnsummonDistance; val.m_unsummonOnOwnerLogoutSeconds = tameable.UnsummonOnOwnerLogoutSeconds; if (Enum.TryParse(tameable.LevelUpOwnerSkill, out SkillType result)) { val.m_levelUpOwnerSkill = result; } val.m_levelUpFactor = tameable.LevelUpFactor; val.m_dropSaddleOnDeath = tameable.DropSaddleOnDeath; val.m_randomStartingName = tameable.RandomStartingName; Helpers.UpdateEffectList(creatureData.m_effects.m_tamedEffects, ref val.m_tamedEffect, scale); Helpers.UpdateEffectList(creatureData.m_effects.m_soothEffects, ref val.m_sootheEffect, scale); Helpers.UpdateEffectList(creatureData.m_effects.m_petEffects, ref val.m_petEffect, scale); Helpers.UpdateEffectList(creatureData.m_effects.m_unSummonEffects, ref val.m_unSummonEffect, scale); } } } public static class VisualMethods { [Serializable] public class HumanData { public int ModelIndex = 0; public int BeardIndex = 0; public int HairIndex = 0; } [Serializable] public class ScaleData { public float x; public float y; public float z; public Vector3Ref ToRef() { return new Vector3Ref(x, y, z); } } [Serializable] [<64cf9182-2f81-4902-ae94-34c63181c9f0>Nullable(0)] [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public class MaterialData { public string ShaderType = ""; public string Name = ""; public ColorData _Color = new ColorData(); public string _MainTex = ""; public ColorData _EmissionColor = new ColorData(); public bool Transparent; public float _Hue; public float _Value; public float _Saturation; public void Set(MaterialRef r) { r.m_shader = ShaderType; r.m_color = _Color.ToHex(); r.m_emissionColor = _EmissionColor.ToHex(); r.m_hue = _Hue; r.m_value = _Value; r.m_saturation = _Saturation; r.m_mainTexture = _MainTex; } } [Serializable] public class ColorData { public float r; public float g; public float b; public float a; public Color ToColor() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) return new Color(r, g, b, a); } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public string ToHex() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return ToColor().ToRGBAString(); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static void ReadVisuals(string folderPath, ref CreatureData creatureData) { char directorySeparatorChar = Path.DirectorySeparatorChar; string text = folderPath + directorySeparatorChar + "Visual"; if (!Directory.Exists(text)) { return; } directorySeparatorChar = Path.DirectorySeparatorChar; string text2 = text + directorySeparatorChar + "Scale.yml"; if (!File.Exists(text2)) { return; } IDeserializer deserializer = new DeserializerBuilder().Build(); string text3 = File.ReadAllText(text2); if (Utility.IsNullOrWhiteSpace(text3)) { return; } try { ScaleData scale = deserializer.Deserialize(text3); creatureData.m_scale = scale; } catch { Helpers.LogParseFailure(text2); } directorySeparatorChar = Path.DirectorySeparatorChar; string text4 = text + directorySeparatorChar + "Human.yml"; if (File.Exists(text4)) { try { HumanData humanData = deserializer.Deserialize(File.ReadAllText(text4)); creatureData.m_humanData = humanData; } catch { Helpers.LogParseFailure(text4); } } directorySeparatorChar = Path.DirectorySeparatorChar; string text5 = text + directorySeparatorChar + "RagdollScale.yml"; if (File.Exists(text5)) { try { creatureData.m_ragdollScale = deserializer.Deserialize(File.ReadAllText(text5)); } catch { Helpers.LogParseFailure(text5); } } directorySeparatorChar = Path.DirectorySeparatorChar; string path = text + directorySeparatorChar + "Materials"; if (!Directory.Exists(path)) { return; } string[] files = Directory.GetFiles(path); Dictionary dictionary = new Dictionary(); string[] array = files; foreach (string text6 in array) { string text7 = File.ReadAllText(text6); if (!Utility.IsNullOrWhiteSpace(text7)) { try { MaterialData materialData = deserializer.Deserialize(text7); dictionary[materialData.Name] = materialData; } catch { Helpers.LogParseFailure(text6); } } } creatureData.m_materials = dictionary; directorySeparatorChar = Path.DirectorySeparatorChar; string text8 = text + directorySeparatorChar + "Particles.yml"; if (!File.Exists(text8)) { return; } try { Dictionary particles = deserializer.Deserialize>(File.ReadAllText(text8)); creatureData.m_particles = particles; } catch { Helpers.LogParseFailure(text8); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static void Update(GameObject critter, CreatureData creatureData) { //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_001f: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) Vector3 localScale = creatureData.m_scale.ToRef(); Dictionary materials = creatureData.m_materials; critter.transform.localScale = localScale; SkinnedMeshRenderer[] componentsInChildren = critter.GetComponentsInChildren(); SkinnedMeshRenderer[] array = componentsInChildren; foreach (SkinnedMeshRenderer val in array) { Material[] sharedMaterials = ((Renderer)val).sharedMaterials; Material[] array2 = sharedMaterials; foreach (Material val2 in array2) { string name = ((Object)val2).name; if (materials.TryGetValue(name, out var value)) { val2.shader = ShaderRef.GetShader(value.ShaderType, val2.shader); ((Object)val2).name = name; val2.color = GetColor(value._Color); val2.mainTexture = TextureManager.GetTexture(value._MainTex, val2.mainTexture); if (val2.HasProperty(ShaderRef._EmissionColor)) { val2.SetColor(ShaderRef._EmissionColor, GetColor(value._EmissionColor)); } if (val2.HasProperty(ShaderRef._Hue)) { val2.SetFloat(ShaderRef._Hue, value._Hue); } if (val2.HasProperty(ShaderRef._Value)) { val2.SetFloat(ShaderRef._Value, value._Value); } if (val2.HasProperty(ShaderRef._Saturation)) { val2.SetFloat(ShaderRef._Saturation, value._Saturation); } } } ((Renderer)val).sharedMaterials = sharedMaterials.ToArray(); ((Renderer)val).materials = sharedMaterials.ToArray(); } } [<5e8279cf-d0bd-4f5f-8d10-178823668550>NullableContext(1)] public static Color GetColor(ColorData data) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) return new Color(data.r, data.g, data.b, data.a); } } } [CompilerGenerated] internal sealed class { internal static uint ComputeStringHash(string s) { uint num = default(uint); if (s != null) { num = 2166136261u; for (int i = 0; i < s.Length; i++) { num = (s[i] ^ num) * 16777619; } } return num; } } [CompilerGenerated] internal sealed class <>z__ReadOnlyArray : IEnumerable, ICollection, IList, IEnumerable, IReadOnlyCollection, IReadOnlyList, ICollection, IList { int ICollection.Count => _items.Length; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection.Count => _items.Length; T IReadOnlyList.this[int index] => _items[index]; int ICollection.Count => _items.Length; bool ICollection.IsReadOnly => true; T IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyArray(T[] items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.Add(T item) { throw new NotSupportedException(); } void ICollection.Clear() { throw new NotSupportedException(); } bool ICollection.Contains(T item) { return ((ICollection)_items).Contains(item); } void ICollection.CopyTo(T[] array, int arrayIndex) { ((ICollection)_items).CopyTo(array, arrayIndex); } bool ICollection.Remove(T item) { throw new NotSupportedException(); } int IList.IndexOf(T item) { return ((IList)_items).IndexOf(item); } void IList.Insert(int index, T item) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } } [CompilerGenerated] internal sealed class <>z__ReadOnlySingleElementList : IEnumerable, ICollection, IList, IEnumerable, IReadOnlyCollection, IReadOnlyList, ICollection, IList { private sealed class Enumerator : IDisposable, IEnumerator, IEnumerator { object IEnumerator.Current => _item; T IEnumerator.Current => _item; public Enumerator(T item) { _item = item; } bool IEnumerator.MoveNext() { return !_moveNextCalled && (_moveNextCalled = true); } void IEnumerator.Reset() { _moveNextCalled = false; } void IDisposable.Dispose() { } } int ICollection.Count => 1; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return _item; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection.Count => 1; T IReadOnlyList.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return _item; } } int ICollection.Count => 1; bool ICollection.IsReadOnly => true; T IList.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return _item; } set { throw new NotSupportedException(); } } public <>z__ReadOnlySingleElementList(T item) { _item = item; } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_item); } void ICollection.CopyTo(Array array, int index) { array.SetValue(_item, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return EqualityComparer.Default.Equals(_item, (T)value); } int IList.IndexOf(object value) { return (!EqualityComparer.Default.Equals(_item, (T)value)) ? (-1) : 0; } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_item); } void ICollection.Add(T item) { throw new NotSupportedException(); } void ICollection.Clear() { throw new NotSupportedException(); } bool ICollection.Contains(T item) { return EqualityComparer.Default.Equals(_item, item); } void ICollection.CopyTo(T[] array, int arrayIndex) { array[arrayIndex] = _item; } bool ICollection.Remove(T item) { throw new NotSupportedException(); } int IList.IndexOf(T item) { return (!EqualityComparer.Default.Equals(_item, item)) ? (-1) : 0; } void IList.Insert(int index, T item) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<41b8bf6e-8977-47d6-9d78-6f38fe40f276>Embedded] internal sealed class <41b8bf6e-8977-47d6-9d78-6f38fe40f276>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [<41b8bf6e-8977-47d6-9d78-6f38fe40f276>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] [<41b8bf6e-8977-47d6-9d78-6f38fe40f276>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; } } [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] [<41b8bf6e-8977-47d6-9d78-6f38fe40f276>Embedded] [CompilerGenerated] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ServerSync { [Nullable(0)] [NullableContext(1)] [PublicAPI] internal abstract class OwnConfigEntryBase { [Nullable(2)] public object LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] [NullableContext(1)] [Nullable(0)] internal class SyncedConfigEntry<[Nullable(2)] T> : OwnConfigEntryBase { public readonly ConfigEntry SourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public SyncedConfigEntry(ConfigEntry sourceConfig) { SourceConfig = sourceConfig; base..ctor(); } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } [NullableContext(2)] [Nullable(0)] internal abstract class CustomSyncedValueBase { public object LocalBaseValue; [Nullable(1)] public readonly string Identifier; [Nullable(1)] public readonly Type Type; private object boxedValue; protected bool localIsOwner; public readonly int Priority; public object BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action ValueChanged; [NullableContext(1)] protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [PublicAPI] [Nullable(0)] [NullableContext(1)] internal sealed class CustomSyncedValue<[Nullable(2)] T> : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [PublicAPI] [Nullable(0)] [NullableContext(1)] internal class ConfigSync { [NullableContext(0)] [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { [Nullable(2)] public static ZRpc currentRpc; [NullableContext(1)] [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [NullableContext(0)] [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [NullableContext(1)] [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register(configSync2.Name + " ConfigSync", (Action)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } [NullableContext(1)] static void SendAdmin(List peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } [NullableContext(1)] static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List CurrentList = new List(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List(adminList.GetList()); List adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } } [NullableContext(0)] [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] [NullableContext(1)] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register(configSync.Name + " ConfigSync", (Action)configSync.RPC_FromServerConfigSync); } } } [NullableContext(0)] private class ParsedConfigs { [Nullable(new byte[] { 1, 1, 2 })] public readonly Dictionary configValues = new Dictionary(); [Nullable(new byte[] { 1, 1, 2 })] public readonly Dictionary customValues = new Dictionary(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] [NullableContext(0)] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [Nullable(0)] [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { [Nullable(0)] private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished = false; public volatile int versionMatchQueued = -1; public readonly List Package = new List(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFabSocket)this)..ctor(); } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix([Nullable(new byte[] { 2, 1, 1 })] ref Dictionary __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend > 0) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); object? value = fieldInfo.GetValue(val); ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null); if (val2 != null) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId); } fieldInfo.SetValue(val, bufferingSocket); } if (__state == null) { __state = new Dictionary(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List entries = new List(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select([NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List { peer }, package)); } SendBufferedData(); } } } [Nullable(0)] private class PackageEntry { public string section = null; public string key = null; public Type type = null; [Nullable(2)] public object value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] [NullableContext(0)] private static class PreventSavingServerInfo { [HarmonyPrefix] [NullableContext(1)] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] [NullableContext(0)] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] [NullableContext(1)] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } [Nullable(0)] private class InvalidDeserializationTypeException : Exception { public string expected = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; [Nullable(2)] public string DisplayName; [Nullable(2)] public string CurrentVersion; [Nullable(2)] public string MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet configSyncs; private readonly HashSet allConfigs = new HashSet(); private HashSet allCustomValues = new HashSet(); private static bool isServer; private static bool lockExempt; [Nullable(2)] private OwnConfigEntryBase lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary> configValueCache = new Dictionary>(); [Nullable(new byte[] { 1, 0, 1 })] private readonly List> cacheExpirations = new List>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag.GetValueOrDefault(); } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0053: return (byte)result != 0; IL_0052: result = 0; goto IL_0053; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; [Nullable(2)] [method: NullableContext(2)] [field: Nullable(2)] public event Action SourceOfTruthChanged; [Nullable(2)] [method: NullableContext(2)] [field: Nullable(2)] private event Action lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry AddConfigEntry<[Nullable(2)] T>(ConfigEntry configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry syncedEntry = ownConfigEntryBase as SyncedConfigEntry; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty()).Concat(new SyncedConfigEntry[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += [NullableContext(0)] (object _, EventArgs _) => { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry AddLockingConfigEntry<[Nullable(0)] T>(ConfigEntry lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry(lockingConfig); lockingConfig.SettingChanged += [NullableContext(0)] (object _, EventArgs _) => { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select([NullableContext(0)] (CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet(allCustomValues.OrderByDescending([NullableContext(0)] (CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(([Nullable(new byte[] { 0, 1 })] KeyValuePair kv) => { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2u) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out var value)) { value = new SortedDictionary(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany([NullableContext(0)] (byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4u) != 0) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; } foreach (KeyValuePair customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary dictionary = allConfigs.Where([NullableContext(0)] (OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary([NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, [NullableContext(0)] (OwnConfigEntryBase c) => c); Dictionary dictionary2 = allCustomValues.ToDictionary([NullableContext(0)] (CustomSyncedValueBase c) => c.Identifier, [NullableContext(0)] (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int i = 0; i < num; i++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected)); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown"))); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName)); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match.")); } continue; } Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs")); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault([NullableContext(0)] (ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where([NullableContext(0)] (OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (val == null) { val = item.BaseConfig.ConfigFile; saveOnConfigSet = val.SaveOnConfigSet; val.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (val != null) { val.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where([NullableContext(0)] (CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer.m_socket.IsConnected()) { ZPackage fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg }); } } IEnumerable waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty().GetEnumerator(); } List list = (List)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where([NullableContext(0)] (ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List> writers = (from peer in peers where peer.IsReady() select peer into p select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } [return: Nullable(2)] private static OwnConfigEntryBase configData(ConfigEntryBase config) { return config.Description.Tags?.OfType().SingleOrDefault(); } [return: Nullable(new byte[] { 2, 1 })] public static SyncedConfigEntry ConfigData<[Nullable(2)] T>(ConfigEntry config) { return ((ConfigEntryBase)config).Description.Tags?.OfType>().SingleOrDefault(); } private static T configAttribute<[Nullable(2)] T>(ConfigEntryBase config) { return config.Description.Tags.OfType().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage([Nullable(new byte[] { 2, 1 })] IEnumerable configs = null, [Nullable(new byte[] { 2, 1 })] IEnumerable customValues = null, [Nullable(new byte[] { 2, 1 })] IEnumerable packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List list = configs?.Where([NullableContext(0)] (ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List(); List list2 = customValues?.ToList() ?? new List(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty()) { AddEntryToPackage(val, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(val, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(val, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return val; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, [Nullable(2)] object value) { Type type = value?.GetType(); if (value is Enum) { value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture); } else { if (value is ICollection collection) { package.Write(collection.Count); { foreach (object item in collection) { AddValueToZPackage(package, item); } return; } } if ((object)type != null && type.IsValueType && !type.IsPrimitive) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); package.Write(fields.Length); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { package.Write(GetZPackageTypeString(fieldInfo.FieldType)); AddValueToZPackage(package, fieldInfo.GetValue(value)); } return; } } ZRpc.Serialize(new object[1] { value }, ref package); } private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type) { if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); int num = package.ReadInt(); if (num != fields.Length) { throw new InvalidDeserializationTypeException { received = $"(field count: {num})", expected = $"(field count: {fields.Length})" }; } object uninitializedObject = FormatterServices.GetUninitializedObject(type); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { string text = package.ReadString(); if (text != GetZPackageTypeString(fieldInfo.FieldType)) { throw new InvalidDeserializationTypeException { received = text, expected = GetZPackageTypeString(fieldInfo.FieldType), field = fieldInfo.Name }; } fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType)); } return uninitializedObject; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { int num2 = package.ReadInt(); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type); Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments); FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic); for (int j = 0; j < num2; j++) { object obj = ReadValueWithTypeFromZPackage(package, type2); dictionary.Add(field.GetValue(obj), field2.GetValue(obj)); } return dictionary; } if (type != typeof(List) && type.IsGenericType) { Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]); if ((object)type3 != null && type3.IsAssignableFrom(type)) { int num3 = package.ReadInt(); object obj2 = Activator.CreateInstance(type); MethodInfo method = type3.GetMethod("Add"); for (int k = 0; k < num3; k++) { method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) }); } return obj2; } } ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo)); AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type); List source = new List(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [NullableContext(1)] [Nullable(0)] [PublicAPI] [HarmonyPatch] internal class VersionCheck { private static readonly HashSet versionChecks; private static readonly Dictionary notProcessedNames; public string Name; [Nullable(2)] private string displayName; [Nullable(2)] private string currentVersion; [Nullable(2)] private string minimumRequiredVersion; public bool ModRequired = true; [Nullable(2)] private string ReceivedCurrentVersion; [Nullable(2)] private string ReceivedMinimumRequiredVersion; private readonly List ValidatedClients = new List(); [Nullable(2)] private ConfigSync ConfigSync; public string DisplayName { get { return displayName ?? Name; } set { displayName = value; } } public string CurrentVersion { get { return currentVersion ?? "0.0.0"; } set { currentVersion = value; } } public string MinimumRequiredVersion { get { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null)); if (patchInfo != null && patchInfo.Postfixes.Count([NullableContext(0)] (Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony val = new Harmony("org.bepinex.helpers.ServerSync"); foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) }) where t.IsClass select t) { val.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet(); notProcessedNames = new Dictionary(); typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1] { new Action(PatchServerSync) }); } public VersionCheck(string name) { Name = name; ModRequired = true; versionChecks.Add(this); } public VersionCheck(ConfigSync configSync) { ConfigSync = configSync; Name = ConfigSync.Name; versionChecks.Add(this); } public void Initialize() { ReceivedCurrentVersion = null; ReceivedMinimumRequiredVersion = null; if (ConfigSync != null) { Name = ConfigSync.Name; DisplayName = ConfigSync.DisplayName; CurrentVersion = ConfigSync.CurrentVersion; MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion; ModRequired = ConfigSync.ModRequired; } } private bool IsVersionOk() { if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null) { return !ModRequired; } bool flag = new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion); bool flag2 = new System.Version(ReceivedCurrentVersion) >= new System.Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + "."); } private string ErrorServer(ZRpc rpc) { return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion; } private string Error([Nullable(2)] ZRpc rpc = null) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where([NullableContext(0)] (VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { return versionChecks.Where([NullableContext(0)] (VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray(); } private static void Logout() { Game.instance.Logout(true, true); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", new object[1] { 3 }); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, [Nullable(new byte[] { 2, 1, 1 })] Action original) { string text = pkg.ReadString(); string text2 = pkg.ReadString(); string text3 = pkg.ReadString(); bool flag = false; foreach (VersionCheck versionCheck in versionChecks) { if (!(text != versionCheck.Name)) { Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + ".")); versionCheck.ReceivedMinimumRequiredVersion = text2; versionCheck.ReceivedCurrentVersion = text3; if (ZNet.instance.IsServer() && versionCheck.IsVersionOk()) { versionCheck.ValidatedClients.Add(rpc); } flag = true; } } if (flag) { return; } pkg.SetPos(0); if (original != null) { original(rpc, pkg); if (pkg.GetPos() == 0) { notProcessedNames.Add(text, text3); } } } [HarmonyPrefix] [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Expected O, but got Unknown notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck"))) { object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")]; Action action = (Action)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register("ServerSync VersionCheck", (Action)([NullableContext(0)] (ZRpc rpc, [Nullable(1)] ZPackage pkg) => { CheckVersion(rpc, pkg, action); })); } else { peer.m_rpc.Register("ServerSync VersionCheck", (Action)CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + ".")); ZPackage val = new ZPackage(); val.Write(versionCheck.Name); val.Write(versionCheck.MinimumRequiredVersion); val.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val }); } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] [HarmonyPrefix] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPostfix] [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] private static void ShowConnectionError(FejdStartup __instance) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3) { return; } bool flag = false; VersionCheck[] failedClient = GetFailedClient(); if (failedClient.Length != 0) { string text = string.Join("\n", failedClient.Select([NullableContext(0)] (VersionCheck check) => check.Error())); TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + text; flag = true; } foreach (KeyValuePair item in notProcessedNames.OrderBy([NullableContext(0)] (KeyValuePair kv) => kv.Key)) { if (!__instance.m_connectionFailedError.text.Contains(item.Key)) { TMP_Text connectionFailedError2 = __instance.m_connectionFailedError; connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed."; flag = true; } } if (flag) { RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; __instance.m_connectionFailedError.ForceMeshUpdate(false, false); float num = __instance.m_connectionFailedError.renderedHeight + 105f; RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } } namespace Microsoft.CodeAnalysis { [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] internal sealed class IsReadOnlyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace YamlDotNet { internal sealed class CultureInfoAdapter : CultureInfo { private readonly IFormatProvider provider; public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider) : base(baseCulture.LCID) { this.provider = provider; } public override object? GetFormat(Type? formatType) { return provider.GetFormat(formatType); } } internal static class ReflectionExtensions { private static readonly FieldInfo? RemoteStackTraceField = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic); public static Type? BaseType(this Type type) { return type.BaseType; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static bool IsGenericTypeDefinition(this Type type) { return type.IsGenericTypeDefinition; } public static bool IsInterface(this Type type) { return type.IsInterface; } public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsDbNull(this object value) { return value is DBNull; } public static bool HasDefaultConstructor(this Type type, bool allowPrivateConstructors) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (allowPrivateConstructors) { bindingFlags |= BindingFlags.NonPublic; } if (!type.IsValueType) { return type.GetConstructor(bindingFlags, null, Type.EmptyTypes, null) != null; } return true; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static PropertyInfo? GetPublicProperty(this Type type, string name) { return type.GetProperty(name); } public static FieldInfo? GetPublicStaticField(this Type type, string name) { return type.GetField(name, BindingFlags.Static | BindingFlags.Public); } public static IEnumerable GetProperties(this Type type, bool includeNonPublic) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (includeNonPublic) { bindingFlags |= BindingFlags.NonPublic; } if (!type.IsInterface) { return type.GetProperties(bindingFlags); } return new Type[1] { type }.Concat(type.GetInterfaces()).SelectMany((Type i) => i.GetProperties(bindingFlags)); } public static IEnumerable GetPublicProperties(this Type type) { return type.GetProperties(includeNonPublic: false); } public static IEnumerable GetPublicFields(this Type type) { return type.GetFields(BindingFlags.Instance | BindingFlags.Public); } public static IEnumerable GetPublicStaticMethods(this Type type) { return type.GetMethods(BindingFlags.Static | BindingFlags.Public); } public static MethodInfo GetPrivateStaticMethod(this Type type, string name) { return type.GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic) ?? throw new MissingMethodException("Expected to find a method named '" + name + "' in '" + type.FullName + "'."); } public static MethodInfo? GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes) { return type.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, parameterTypes, null); } public static MethodInfo? GetPublicInstanceMethod(this Type type, string name) { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public); } public static Exception Unwrap(this TargetInvocationException ex) { Exception innerException = ex.InnerException; if (innerException == null) { return ex; } if (RemoteStackTraceField != null) { RemoteStackTraceField.SetValue(innerException, innerException.StackTrace + "\r\n"); } return innerException; } public static bool IsInstanceOf(this Type type, object o) { return type.IsInstanceOfType(o); } public static Attribute[] GetAllCustomAttributes(this PropertyInfo property) { return Attribute.GetCustomAttributes(property, typeof(TAttribute), inherit: true); } } internal static class PropertyInfoExtensions { public static object? ReadValue(this PropertyInfo property, object target) { return property.GetValue(target, null); } } internal static class StandardRegexOptions { public const RegexOptions Compiled = RegexOptions.Compiled; } } namespace YamlDotNet.Serialization { internal abstract class BuilderSkeleton where TBuilder : BuilderSkeleton { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal ITypeResolver typeResolver; internal readonly YamlAttributeOverrides overrides; internal readonly LazyComponentRegistrationList typeConverterFactories; internal readonly LazyComponentRegistrationList typeInspectorFactories; internal bool ignoreFields; internal bool includeNonPublicProperties; internal Settings settings; protected abstract TBuilder Self { get; } internal BuilderSkeleton(ITypeResolver typeResolver) { overrides = new YamlAttributeOverrides(); typeConverterFactories = new LazyComponentRegistrationList { { typeof(YamlDotNet.Serialization.Converters.GuidConverter), (Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false) }, { typeof(SystemTypeConverter), (Nothing _) => new SystemTypeConverter() } }; typeInspectorFactories = new LazyComponentRegistrationList(); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); settings = new Settings(); } public TBuilder IgnoreFields() { ignoreFields = true; return Self; } public TBuilder IncludeNonPublicProperties() { includeNonPublicProperties = true; return Self; } public TBuilder EnablePrivateConstructors() { settings.AllowPrivateConstructors = true; return Self; } public TBuilder WithNamingConvention(INamingConvention namingConvention) { this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); return Self; } public TBuilder WithTypeResolver(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); return Self; } public abstract TBuilder WithTagMapping(TagName tag, Type type); public TBuilder WithAttributeOverride(Expression> propertyAccessor, Attribute attribute) { overrides.Add(propertyAccessor, attribute); return Self; } public TBuilder WithAttributeOverride(Type type, string member, Attribute attribute) { overrides.Add(type, member, attribute); return Self; } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter) { return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action> where) { IYamlTypeConverter typeConverter2 = typeConverter; if (typeConverter2 == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter2.GetType(), (Nothing _) => typeConverter2)); return Self; } public TBuilder WithTypeConverter(WrapperFactory typeConverterFactory, Action> where) where TYamlTypeConverter : IYamlTypeConverter { WrapperFactory typeConverterFactory2 = typeConverterFactory; if (typeConverterFactory2 == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory2(wrapped))); return Self; } public TBuilder WithoutTypeConverter() where TYamlTypeConverter : IYamlTypeConverter { return WithoutTypeConverter(typeof(TYamlTypeConverter)); } public TBuilder WithoutTypeConverter(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } typeConverterFactories.Remove(converterType); return Self; } public TBuilder WithTypeInspector(Func typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeInspector(Func typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { Func typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory2(inner))); return Self; } public TBuilder WithTypeInspector(WrapperFactory typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { WrapperFactory typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory2(wrapped, inner))); return Self; } public TBuilder WithoutTypeInspector() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if (inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } protected IEnumerable BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } internal delegate TComponent WrapperFactory(TComponentBase wrapped) where TComponent : TComponentBase; internal delegate TComponent WrapperFactory(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase; [Flags] internal enum DefaultValuesHandling { Preserve = 0, OmitNull = 1, OmitDefaults = 2, OmitEmptyCollections = 4 } internal sealed class Deserializer : IDeserializer { private readonly IValueDeserializer valueDeserializer; public Deserializer() : this(new DeserializerBuilder().BuildValueDeserializer()) { } private Deserializer(IValueDeserializer valueDeserializer) { this.valueDeserializer = valueDeserializer ?? throw new ArgumentNullException("valueDeserializer"); } public static Deserializer FromValueDeserializer(IValueDeserializer valueDeserializer) { return new Deserializer(valueDeserializer); } public T Deserialize(string input) { using StringReader input2 = new StringReader(input); return Deserialize(input2); } public T Deserialize(TextReader input) { return Deserialize(new Parser(input)); } public object? Deserialize(TextReader input) { return Deserialize(input, typeof(object)); } public object? Deserialize(string input, Type type) { using StringReader input2 = new StringReader(input); return Deserialize(input2, type); } public object? Deserialize(TextReader input, Type type) { return Deserialize(new Parser(input), type); } public T Deserialize(IParser parser) { return (T)Deserialize(parser, typeof(T)); } public object? Deserialize(IParser parser) { return Deserialize(parser, typeof(object)); } public object? Deserialize(IParser parser, Type type) { if (parser == null) { throw new ArgumentNullException("parser"); } if (type == null) { throw new ArgumentNullException("type"); } YamlDotNet.Core.Events.StreamStart @event; bool flag = parser.TryConsume(out @event); YamlDotNet.Core.Events.DocumentStart event2; bool flag2 = parser.TryConsume(out event2); object result = null; if (!parser.Accept(out var _) && !parser.Accept(out var _)) { using SerializerState serializerState = new SerializerState(); result = valueDeserializer.DeserializeValue(parser, type, serializerState, valueDeserializer); serializerState.OnDeserialization(); } if (flag2) { parser.Consume(); } if (flag) { parser.Consume(); } return result; } } internal sealed class DeserializerBuilder : BuilderSkeleton { private Lazy objectFactory; private readonly LazyComponentRegistrationList nodeDeserializerFactories; private readonly LazyComponentRegistrationList nodeTypeResolverFactories; private readonly Dictionary tagMappings; private readonly Dictionary typeMappings; private readonly ITypeConverter typeConverter; private bool ignoreUnmatched; private bool duplicateKeyChecking; private bool attemptUnknownTypeDeserialization; protected override DeserializerBuilder Self => this; public DeserializerBuilder() : base((ITypeResolver)new StaticTypeResolver()) { typeMappings = new Dictionary(); objectFactory = new Lazy(() => new DefaultObjectFactory(typeMappings, settings), isThreadSafe: true); tagMappings = new Dictionary { { FailsafeSchema.Tags.Map, typeof(Dictionary) }, { FailsafeSchema.Tags.Str, typeof(string) }, { JsonSchema.Tags.Bool, typeof(bool) }, { JsonSchema.Tags.Float, typeof(double) }, { JsonSchema.Tags.Int, typeof(int) }, { DefaultSchema.Tags.Timestamp, typeof(DateTime) } }; typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone())); typeInspectorFactories.Add(typeof(ReadableAndWritablePropertiesTypeInspector), (ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner)); nodeDeserializerFactories = new LazyComponentRegistrationList { { typeof(YamlConvertibleNodeDeserializer), (Nothing _) => new YamlConvertibleNodeDeserializer(objectFactory.Value) }, { typeof(YamlSerializableNodeDeserializer), (Nothing _) => new YamlSerializableNodeDeserializer(objectFactory.Value) }, { typeof(TypeConverterNodeDeserializer), (Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters()) }, { typeof(NullNodeDeserializer), (Nothing _) => new NullNodeDeserializer() }, { typeof(ScalarNodeDeserializer), (Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter) }, { typeof(ArrayNodeDeserializer), (Nothing _) => new ArrayNodeDeserializer() }, { typeof(DictionaryNodeDeserializer), (Nothing _) => new DictionaryNodeDeserializer(objectFactory.Value, duplicateKeyChecking) }, { typeof(CollectionNodeDeserializer), (Nothing _) => new CollectionNodeDeserializer(objectFactory.Value) }, { typeof(EnumerableNodeDeserializer), (Nothing _) => new EnumerableNodeDeserializer() }, { typeof(ObjectNodeDeserializer), (Nothing _) => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter) } }; nodeTypeResolverFactories = new LazyComponentRegistrationList { { typeof(MappingNodeTypeResolver), (Nothing _) => new MappingNodeTypeResolver(typeMappings) }, { typeof(YamlConvertibleTypeResolver), (Nothing _) => new YamlConvertibleTypeResolver() }, { typeof(YamlSerializableTypeResolver), (Nothing _) => new YamlSerializableTypeResolver() }, { typeof(TagNodeTypeResolver), (Nothing _) => new TagNodeTypeResolver(tagMappings) }, { typeof(PreventUnknownTagsNodeTypeResolver), (Nothing _) => new PreventUnknownTagsNodeTypeResolver() }, { typeof(DefaultContainersNodeTypeResolver), (Nothing _) => new DefaultContainersNodeTypeResolver() } }; typeConverter = new ReflectionTypeConverter(); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = new WritablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector); } return typeInspectorFactories.BuildComponentChain(typeInspector); } public DeserializerBuilder WithAttemptingUnquotedStringTypeDeserialization() { attemptUnknownTypeDeserialization = true; return this; } public DeserializerBuilder WithObjectFactory(IObjectFactory objectFactory) { IObjectFactory objectFactory2 = objectFactory; if (objectFactory2 == null) { throw new ArgumentNullException("objectFactory"); } this.objectFactory = new Lazy(() => objectFactory2, isThreadSafe: true); return this; } public DeserializerBuilder WithObjectFactory(Func objectFactory) { if (objectFactory == null) { throw new ArgumentNullException("objectFactory"); } return WithObjectFactory(new LambdaObjectFactory(objectFactory)); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer) { return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action> where) { INodeDeserializer nodeDeserializer2 = nodeDeserializer; if (nodeDeserializer2 == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer2.GetType(), (Nothing _) => nodeDeserializer2)); return this; } public DeserializerBuilder WithNodeDeserializer(WrapperFactory nodeDeserializerFactory, Action> where) where TNodeDeserializer : INodeDeserializer { WrapperFactory nodeDeserializerFactory2 = nodeDeserializerFactory; if (nodeDeserializerFactory2 == null) { throw new ArgumentNullException("nodeDeserializerFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory2(wrapped))); return this; } public DeserializerBuilder WithoutNodeDeserializer() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public DeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if (nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public DeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1) { TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions(); configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions); TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength); return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax s) { s.Before(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action> where) { INodeTypeResolver nodeTypeResolver2 = nodeTypeResolver; if (nodeTypeResolver2 == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver2.GetType(), (Nothing _) => nodeTypeResolver2)); return this; } public DeserializerBuilder WithNodeTypeResolver(WrapperFactory nodeTypeResolverFactory, Action> where) where TNodeTypeResolver : INodeTypeResolver { WrapperFactory nodeTypeResolverFactory2 = nodeTypeResolverFactory; if (nodeTypeResolverFactory2 == null) { throw new ArgumentNullException("nodeTypeResolverFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory2(wrapped))); return this; } public DeserializerBuilder WithoutNodeTypeResolver() where TNodeTypeResolver : INodeTypeResolver { return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); } public DeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) { if (nodeTypeResolverType == null) { throw new ArgumentNullException("nodeTypeResolverType"); } nodeTypeResolverFactories.Remove(nodeTypeResolverType); return this; } public override DeserializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(tag, out Type value)) { throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag"); } tagMappings.Add(tag, type); return this; } public DeserializerBuilder WithTypeMapping() where TConcrete : TInterface { Type typeFromHandle = typeof(TInterface); Type typeFromHandle2 = typeof(TConcrete); if (!typeFromHandle.IsAssignableFrom(typeFromHandle2)) { throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'."); } if (typeMappings.ContainsKey(typeFromHandle)) { typeMappings[typeFromHandle] = typeFromHandle2; } else { typeMappings.Add(typeFromHandle, typeFromHandle2); } return this; } public DeserializerBuilder WithoutTagMapping(TagName tag) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (!tagMappings.Remove(tag)) { throw new KeyNotFoundException($"Tag '{tag}' is not registered"); } return this; } public DeserializerBuilder IgnoreUnmatchedProperties() { ignoreUnmatched = true; return this; } public DeserializerBuilder WithDuplicateKeyChecking() { duplicateKeyChecking = true; return this; } public IDeserializer Build() { return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public IValueDeserializer BuildValueDeserializer() { return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter)); } } internal sealed class EmissionPhaseObjectGraphVisitorArgs { private readonly IEnumerable> preProcessingPhaseVisitors; public IObjectGraphVisitor InnerVisitor { get; private set; } public IEventEmitter EventEmitter { get; private set; } public ObjectSerializer NestedObjectSerializer { get; private set; } public IEnumerable TypeConverters { get; private set; } public EmissionPhaseObjectGraphVisitorArgs(IObjectGraphVisitor innerVisitor, IEventEmitter eventEmitter, IEnumerable> preProcessingPhaseVisitors, IEnumerable typeConverters, ObjectSerializer nestedObjectSerializer) { InnerVisitor = innerVisitor ?? throw new ArgumentNullException("innerVisitor"); EventEmitter = eventEmitter ?? throw new ArgumentNullException("eventEmitter"); this.preProcessingPhaseVisitors = preProcessingPhaseVisitors ?? throw new ArgumentNullException("preProcessingPhaseVisitors"); TypeConverters = typeConverters ?? throw new ArgumentNullException("typeConverters"); NestedObjectSerializer = nestedObjectSerializer ?? throw new ArgumentNullException("nestedObjectSerializer"); } public T GetPreProcessingPhaseObjectGraphVisitor() where T : IObjectGraphVisitor { return preProcessingPhaseVisitors.OfType().Single(); } } internal abstract class EventInfo { public IObjectDescriptor Source { get; } protected EventInfo(IObjectDescriptor source) { Source = source ?? throw new ArgumentNullException("source"); } } internal class AliasEventInfo : EventInfo { public AnchorName Alias { get; } public bool NeedsExpansion { get; set; } public AliasEventInfo(IObjectDescriptor source, AnchorName alias) : base(source) { if (alias.IsEmpty) { throw new ArgumentNullException("alias"); } Alias = alias; } } internal class ObjectEventInfo : EventInfo { public AnchorName Anchor { get; set; } public TagName Tag { get; set; } protected ObjectEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class ScalarEventInfo : ObjectEventInfo { public string RenderedValue { get; set; } public ScalarStyle Style { get; set; } public bool IsPlainImplicit { get; set; } public bool IsQuotedImplicit { get; set; } public ScalarEventInfo(IObjectDescriptor source) : base(source) { Style = source.ScalarStyle; RenderedValue = string.Empty; } } internal sealed class MappingStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public MappingStyle Style { get; set; } public MappingStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class MappingEndEventInfo : EventInfo { public MappingEndEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public SequenceStyle Style { get; set; } public SequenceStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceEndEventInfo : EventInfo { public SequenceEndEventInfo(IObjectDescriptor source) : base(source) { } } internal interface IAliasProvider { AnchorName GetAlias(object target); } internal interface IDeserializer { T Deserialize(string input); T Deserialize(TextReader input); object? Deserialize(TextReader input); object? Deserialize(string input, Type type); object? Deserialize(TextReader input, Type type); T Deserialize(IParser parser); object? Deserialize(IParser parser); object? Deserialize(IParser parser, Type type); } internal interface IEventEmitter { void Emit(AliasEventInfo eventInfo, IEmitter emitter); void Emit(ScalarEventInfo eventInfo, IEmitter emitter); void Emit(MappingStartEventInfo eventInfo, IEmitter emitter); void Emit(MappingEndEventInfo eventInfo, IEmitter emitter); void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter); void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter); } internal interface INamingConvention { string Apply(string value); } internal interface INodeDeserializer { bool Deserialize(IParser reader, Type expectedType, Func nestedObjectDeserializer, out object? value); } internal interface INodeTypeResolver { bool Resolve(NodeEvent? nodeEvent, ref Type currentType); } internal interface IObjectAccessor { void Set(string name, object target, object value); object? Read(string name, object target); } internal interface IObjectDescriptor { object? Value { get; } Type Type { get; } Type StaticType { get; } ScalarStyle ScalarStyle { get; } } internal static class ObjectDescriptorExtensions { public static object NonNullValue(this IObjectDescriptor objectDescriptor) { return objectDescriptor.Value ?? throw new InvalidOperationException("Attempted to use a IObjectDescriptor of type '" + objectDescriptor.Type.FullName + "' whose Value is null at a point whete it is invalid to do so. This may indicate a bug in YamlDotNet."); } } internal interface IObjectFactory { object Create(Type type); object? CreatePrimitive(Type type); bool GetDictionary(IObjectDescriptor descriptor, out IDictionary? dictionary, out Type[]? genericArguments); Type GetValueType(Type type); } internal interface IObjectGraphTraversalStrategy { void Traverse(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context); } internal interface IObjectGraphVisitor { bool Enter(IObjectDescriptor value, TContext context); bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, TContext context); bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, TContext context); void VisitScalar(IObjectDescriptor scalar, TContext context); void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, TContext context); void VisitMappingEnd(IObjectDescriptor mapping, TContext context); void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, TContext context); void VisitSequenceEnd(IObjectDescriptor sequence, TContext context); } internal interface IPropertyDescriptor { string Name { get; } bool CanWrite { get; } Type Type { get; } Type? TypeOverride { get; set; } int Order { get; set; } ScalarStyle ScalarStyle { get; set; } T? GetCustomAttribute() where T : Attribute; IObjectDescriptor Read(object target); void Write(object target, object? value); } internal interface IRegistrationLocationSelectionSyntax { void InsteadOf() where TRegistrationType : TBaseRegistrationType; void Before() where TRegistrationType : TBaseRegistrationType; void After() where TRegistrationType : TBaseRegistrationType; void OnTop(); void OnBottom(); } internal interface ITrackingRegistrationLocationSelectionSyntax { void InsteadOf() where TRegistrationType : TBaseRegistrationType; } internal interface ISerializer { void Serialize(TextWriter writer, object? graph); string Serialize(object? graph); void Serialize(TextWriter writer, object? graph, Type type); void Serialize(IEmitter emitter, object? graph); void Serialize(IEmitter emitter, object? graph, Type type); } internal interface ITypeInspector { IEnumerable GetProperties(Type type, object? container); IPropertyDescriptor GetProperty(Type type, object? container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched); } internal interface ITypeResolver { Type Resolve(Type staticType, object? actualValue); } internal interface IValueDeserializer { object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer); } internal interface IValuePromise { event Action ValueAvailable; } internal interface IValueSerializer { void SerializeValue(IEmitter emitter, object? value, Type? type); } internal interface IYamlConvertible { void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer); void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer); } internal delegate object? ObjectDeserializer(Type type); internal delegate void ObjectSerializer(object? value, Type? type = null); [Obsolete("Please use IYamlConvertible instead")] internal interface IYamlSerializable { void ReadYaml(IParser parser); void WriteYaml(IEmitter emitter); } internal interface IYamlTypeConverter { bool Accepts(Type type); object? ReadYaml(IParser parser, Type type); void WriteYaml(IEmitter emitter, object? value, Type type); } internal sealed class LazyComponentRegistrationList : IEnumerable>, IEnumerable { public sealed class LazyComponentRegistration { public readonly Type ComponentType; public readonly Func Factory; public LazyComponentRegistration(Type componentType, Func factory) { ComponentType = componentType; Factory = factory; } } public sealed class TrackingLazyComponentRegistration { public readonly Type ComponentType; public readonly Func Factory; public TrackingLazyComponentRegistration(Type componentType, Func factory) { ComponentType = componentType; Factory = factory; } } private class RegistrationLocationSelector : IRegistrationLocationSelectionSyntax { private readonly LazyComponentRegistrationList registrations; private readonly LazyComponentRegistration newRegistration; public RegistrationLocationSelector(LazyComponentRegistrationList registrations, LazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void IRegistrationLocationSelectionSyntax.InsteadOf() { if (newRegistration.ComponentType != typeof(TRegistrationType)) { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); } int index = registrations.EnsureRegistrationExists(); registrations.entries[index] = newRegistration; } void IRegistrationLocationSelectionSyntax.After() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); int num = registrations.EnsureRegistrationExists(); registrations.entries.Insert(num + 1, newRegistration); } void IRegistrationLocationSelectionSyntax.Before() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); int index = registrations.EnsureRegistrationExists(); registrations.entries.Insert(index, newRegistration); } void IRegistrationLocationSelectionSyntax.OnBottom() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); registrations.entries.Add(newRegistration); } void IRegistrationLocationSelectionSyntax.OnTop() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); registrations.entries.Insert(0, newRegistration); } } private class TrackingRegistrationLocationSelector : ITrackingRegistrationLocationSelectionSyntax { private readonly LazyComponentRegistrationList registrations; private readonly TrackingLazyComponentRegistration newRegistration; public TrackingRegistrationLocationSelector(LazyComponentRegistrationList registrations, TrackingLazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void ITrackingRegistrationLocationSelectionSyntax.InsteadOf() { if (newRegistration.ComponentType != typeof(TRegistrationType)) { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); } int index = registrations.EnsureRegistrationExists(); Func innerComponentFactory = registrations.entries[index].Factory; registrations.entries[index] = new LazyComponentRegistration(newRegistration.ComponentType, (TArgument arg) => newRegistration.Factory(innerComponentFactory(arg), arg)); } } private readonly List entries = new List(); public int Count => entries.Count; public IEnumerable> InReverseOrder { get { int i = entries.Count - 1; while (i >= 0) { yield return entries[i].Factory; int num = i - 1; i = num; } } } public LazyComponentRegistrationList Clone() { LazyComponentRegistrationList lazyComponentRegistrationList = new LazyComponentRegistrationList(); foreach (LazyComponentRegistration entry in entries) { lazyComponentRegistrationList.entries.Add(entry); } return lazyComponentRegistrationList; } public void Clear() { entries.Clear(); } public void Add(Type componentType, Func factory) { entries.Add(new LazyComponentRegistration(componentType, factory)); } public void Remove(Type componentType) { for (int i = 0; i < entries.Count; i++) { if (entries[i].ComponentType == componentType) { entries.RemoveAt(i); return; } } throw new KeyNotFoundException("A component registration of type '" + componentType.FullName + "' was not found."); } public IRegistrationLocationSelectionSyntax CreateRegistrationLocationSelector(Type componentType, Func factory) { return new RegistrationLocationSelector(this, new LazyComponentRegistration(componentType, factory)); } public ITrackingRegistrationLocationSelectionSyntax CreateTrackingRegistrationLocationSelector(Type componentType, Func factory) { return new TrackingRegistrationLocationSelector(this, new TrackingLazyComponentRegistration(componentType, factory)); } public IEnumerator> GetEnumerator() { return entries.Select((LazyComponentRegistration e) => e.Factory).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private int IndexOfRegistration(Type registrationType) { for (int i = 0; i < entries.Count; i++) { if (registrationType == entries[i].ComponentType) { return i; } } return -1; } private void EnsureNoDuplicateRegistrationType(Type componentType) { if (IndexOfRegistration(componentType) != -1) { throw new InvalidOperationException("A component of type '" + componentType.FullName + "' has already been registered."); } } private int EnsureRegistrationExists() { int num = IndexOfRegistration(typeof(TRegistrationType)); if (num == -1) { throw new InvalidOperationException("A component of type '" + typeof(TRegistrationType).FullName + "' has not been registered."); } return num; } } internal static class LazyComponentRegistrationListExtensions { public static TComponent BuildComponentChain(this LazyComponentRegistrationList registrations, TComponent innerComponent) { return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func factory) => factory(inner)); } public static TComponent BuildComponentChain(this LazyComponentRegistrationList registrations, TComponent innerComponent, Func argumentBuilder) { Func argumentBuilder2 = argumentBuilder; return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func factory) => factory(argumentBuilder2(inner))); } public static List BuildComponentList(this LazyComponentRegistrationList registrations) { return registrations.Select((Func factory) => factory(default(Nothing))).ToList(); } public static List BuildComponentList(this LazyComponentRegistrationList registrations, TArgument argument) { TArgument argument2 = argument; return registrations.Select((Func factory) => factory(argument2)).ToList(); } } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct Nothing { } internal sealed class ObjectDescriptor : IObjectDescriptor { public object? Value { get; private set; } public Type Type { get; private set; } public Type StaticType { get; private set; } public ScalarStyle ScalarStyle { get; private set; } public ObjectDescriptor(object? value, Type type, Type staticType) : this(value, type, staticType, ScalarStyle.Any) { } public ObjectDescriptor(object? value, Type type, Type staticType, ScalarStyle scalarStyle) { Value = value; Type = type ?? throw new ArgumentNullException("type"); StaticType = staticType ?? throw new ArgumentNullException("staticType"); ScalarStyle = scalarStyle; } } internal delegate IObjectGraphTraversalStrategy ObjectGraphTraversalStrategyFactory(ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion); internal sealed class PropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; public string Name { get; set; } public Type Type => baseDescriptor.Type; public Type? TypeOverride { get { return baseDescriptor.TypeOverride; } set { baseDescriptor.TypeOverride = value; } } public int Order { get; set; } public ScalarStyle ScalarStyle { get { return baseDescriptor.ScalarStyle; } set { baseDescriptor.ScalarStyle = value; } } public bool CanWrite => baseDescriptor.CanWrite; public PropertyDescriptor(IPropertyDescriptor baseDescriptor) { this.baseDescriptor = baseDescriptor; Name = baseDescriptor.Name; } public void Write(object target, object? value) { baseDescriptor.Write(target, value); } public T? GetCustomAttribute() where T : Attribute { return baseDescriptor.GetCustomAttribute(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } internal sealed class Serializer : ISerializer { private readonly IValueSerializer valueSerializer; private readonly EmitterSettings emitterSettings; public Serializer() : this(new SerializerBuilder().BuildValueSerializer(), EmitterSettings.Default) { } private Serializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings) { this.valueSerializer = valueSerializer ?? throw new ArgumentNullException("valueSerializer"); this.emitterSettings = emitterSettings ?? throw new ArgumentNullException("emitterSettings"); } public static Serializer FromValueSerializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings) { return new Serializer(valueSerializer, emitterSettings); } public void Serialize(TextWriter writer, object? graph) { Serialize(new Emitter(writer, emitterSettings), graph); } public string Serialize(object? graph) { using StringWriter stringWriter = new StringWriter(); Serialize(stringWriter, graph); return stringWriter.ToString(); } public void Serialize(TextWriter writer, object? graph, Type type) { Serialize(new Emitter(writer, emitterSettings), graph, type); } public void Serialize(IEmitter emitter, object? graph) { if (emitter == null) { throw new ArgumentNullException("emitter"); } EmitDocument(emitter, graph, null); } public void Serialize(IEmitter emitter, object? graph, Type type) { if (emitter == null) { throw new ArgumentNullException("emitter"); } if (type == null) { throw new ArgumentNullException("type"); } EmitDocument(emitter, graph, type); } private void EmitDocument(IEmitter emitter, object? graph, Type? type) { emitter.Emit(new YamlDotNet.Core.Events.StreamStart()); emitter.Emit(new YamlDotNet.Core.Events.DocumentStart()); valueSerializer.SerializeValue(emitter, graph, type); emitter.Emit(new YamlDotNet.Core.Events.DocumentEnd(isImplicit: true)); emitter.Emit(new YamlDotNet.Core.Events.StreamEnd()); } } internal sealed class SerializerBuilder : BuilderSkeleton { private class ValueSerializer : IValueSerializer { private readonly IObjectGraphTraversalStrategy traversalStrategy; private readonly IEventEmitter eventEmitter; private readonly IEnumerable typeConverters; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable typeConverters, LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories) { this.traversalStrategy = traversalStrategy; this.eventEmitter = eventEmitter; this.typeConverters = typeConverters; this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories; this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories; } public void SerializeValue(IEmitter emitter, object? value, Type? type) { IEmitter emitter2 = emitter; Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object)); Type staticType = type ?? typeof(object); ObjectDescriptor graph = new ObjectDescriptor(value, type2, staticType); List> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters); foreach (IObjectGraphVisitor item in preProcessingPhaseObjectGraphVisitors) { traversalStrategy.Traverse(graph, item, default(Nothing)); } IObjectGraphVisitor visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain>(new EmittingObjectGraphVisitor(eventEmitter), (IObjectGraphVisitor inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); traversalStrategy.Traverse(graph, visitor, emitter2); void NestedObjectSerializer(object? v, Type? t) { SerializeValue(emitter2, v, t); } } } private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList eventEmitterFactories; private readonly IDictionary tagMappings = new Dictionary(); private readonly IObjectFactory objectFactory; private int maximumRecursion = 50; private EmitterSettings emitterSettings = EmitterSettings.Default; private DefaultValuesHandling defaultValuesHandlingConfiguration; private bool quoteNecessaryStrings; private bool quoteYaml1_1Strings; protected override SerializerBuilder Self => this; public SerializerBuilder() : base((ITypeResolver)new DynamicTypeResolver()) { typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone())); preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList, IObjectGraphVisitor> { { typeof(AnchorAssigner), (IEnumerable typeConverters) => new AnchorAssigner(typeConverters) } }; emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList> { { typeof(CustomSerializationObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer) }, { typeof(AnchorAssigningObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor()) }, { typeof(DefaultValuesObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, new DefaultObjectFactory()) }, { typeof(CommentsObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor) } }; eventEmitterFactories = new LazyComponentRegistrationList { { typeof(TypeAssigningEventEmitter), (IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: false, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings) } }; objectFactory = new DefaultObjectFactory(); objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention, objectFactory); } public SerializerBuilder WithQuotingNecessaryStrings(bool quoteYaml1_1Strings = false) { quoteNecessaryStrings = true; this.quoteYaml1_1Strings = quoteYaml1_1Strings; return this; } public SerializerBuilder WithMaximumRecursion(int maximumRecursion) { if (maximumRecursion <= 0) { throw new ArgumentOutOfRangeException("maximumRecursion", $"The maximum recursion specified ({maximumRecursion}) is invalid. It should be a positive integer."); } this.maximumRecursion = maximumRecursion; return this; } public SerializerBuilder WithEventEmitter(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public SerializerBuilder WithEventEmitter(Func eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { Func eventEmitterFactory2 = eventEmitterFactory; if (eventEmitterFactory2 == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory2(inner))); return Self; } public SerializerBuilder WithEventEmitter(WrapperFactory eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { WrapperFactory eventEmitterFactory2 = eventEmitterFactory; if (eventEmitterFactory2 == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory2(wrapped, inner))); return Self; } public SerializerBuilder WithoutEventEmitter() where TEventEmitter : IEventEmitter { return WithoutEventEmitter(typeof(TEventEmitter)); } public SerializerBuilder WithoutEventEmitter(Type eventEmitterType) { if (eventEmitterType == null) { throw new ArgumentNullException("eventEmitterType"); } eventEmitterFactories.Remove(eventEmitterType); return this; } public override SerializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(type, out var value)) { throw new ArgumentException($"Type already has a registered tag '{value}' for type '{type.FullName}'", "type"); } tagMappings.Add(type, tag); return this; } public SerializerBuilder WithoutTagMapping(Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (!tagMappings.Remove(type)) { throw new KeyNotFoundException("Tag for type '" + type.FullName + "' is not registered"); } return this; } public SerializerBuilder EnsureRoundtrip() { objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(typeConverters, typeInspector, typeResolver, maximumRecursion, namingConvention, settings, objectFactory); WithEventEmitter((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: true, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); return WithTypeInspector((ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.OnBottom(); }); } public SerializerBuilder DisableAliases() { preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner)); emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor)); return this; } [Obsolete("The default behavior is now to always emit default values, thefore calling this method has no effect. This behavior is now controlled by ConfigureDefaultValuesHandling.", true)] public SerializerBuilder EmitDefaults() { return ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve); } public SerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration) { defaultValuesHandlingConfiguration = configuration; return this; } public SerializerBuilder JsonCompatible() { emitterSettings = emitterSettings.WithMaxSimpleKeyLength(int.MaxValue).WithoutAnchorName(); return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax w) { w.InsteadOf(); }).WithTypeConverter(new YamlDotNet.Serialization.Converters.DateTimeConverter(DateTimeKind.Utc, null, true)).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); } public SerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(TObjectGraphVisitor objectGraphVisitor, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { TObjectGraphVisitor objectGraphVisitor2 = objectGraphVisitor; if (objectGraphVisitor2 == null) { throw new ArgumentNullException("objectGraphVisitor"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable _) => objectGraphVisitor2)); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, IEnumerable _) => objectGraphVisitorFactory2(wrapped))); return this; } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public SerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory) { this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory; return this; } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor(Func objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor(Func objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { Func objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(args))); return this; } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(wrapped, args))); return this; } public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public SerializerBuilder WithIndentedSequences() { emitterSettings = emitterSettings.WithIndentedSequences(); return this; } public ISerializer Build() { return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings); } public IValueSerializer BuildValueSerializer() { IEnumerable typeConverters = BuildTypeConverters(); ITypeInspector typeInspector = BuildTypeInspector(); IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion); IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter()); return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone()); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = new ReadablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector); } return typeInspectorFactories.BuildComponentChain(typeInspector); } } internal class Settings { public bool AllowPrivateConstructors { get; set; } } internal abstract class StaticBuilderSkeleton where TBuilder : StaticBuilderSkeleton { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal ITypeResolver typeResolver; internal readonly LazyComponentRegistrationList typeConverterFactories; internal readonly LazyComponentRegistrationList typeInspectorFactories; internal bool includeNonPublicProperties; internal Settings settings; protected abstract TBuilder Self { get; } internal StaticBuilderSkeleton(ITypeResolver typeResolver) { typeConverterFactories = new LazyComponentRegistrationList { { typeof(YamlDotNet.Serialization.Converters.GuidConverter), (Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false) } }; typeInspectorFactories = new LazyComponentRegistrationList(); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); settings = new Settings(); } public TBuilder WithNamingConvention(INamingConvention namingConvention) { this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); return Self; } public TBuilder WithTypeResolver(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); return Self; } public abstract TBuilder WithTagMapping(TagName tag, Type type); public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter) { return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action> where) { IYamlTypeConverter typeConverter2 = typeConverter; if (typeConverter2 == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter2.GetType(), (Nothing _) => typeConverter2)); return Self; } public TBuilder WithTypeConverter(WrapperFactory typeConverterFactory, Action> where) where TYamlTypeConverter : IYamlTypeConverter { WrapperFactory typeConverterFactory2 = typeConverterFactory; if (typeConverterFactory2 == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory2(wrapped))); return Self; } public TBuilder WithoutTypeConverter() where TYamlTypeConverter : IYamlTypeConverter { return WithoutTypeConverter(typeof(TYamlTypeConverter)); } public TBuilder WithoutTypeConverter(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } typeConverterFactories.Remove(converterType); return Self; } public TBuilder WithTypeInspector(Func typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeInspector(Func typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { Func typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory2(inner))); return Self; } public TBuilder WithTypeInspector(WrapperFactory typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { WrapperFactory typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory2(wrapped, inner))); return Self; } public TBuilder WithoutTypeInspector() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if (inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } protected IEnumerable BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } internal abstract class StaticContext { public virtual StaticObjectFactory GetFactory() { throw new NotImplementedException(); } public virtual ITypeInspector GetTypeInspector() { throw new NotImplementedException(); } } internal sealed class StaticDeserializerBuilder : StaticBuilderSkeleton { private readonly StaticContext context; private readonly StaticObjectFactory factory; private readonly LazyComponentRegistrationList nodeDeserializerFactories; private readonly LazyComponentRegistrationList nodeTypeResolverFactories; private readonly Dictionary tagMappings; private readonly ITypeConverter typeConverter; private readonly Dictionary typeMappings; private bool ignoreUnmatched; private bool duplicateKeyChecking; private bool attemptUnknownTypeDeserialization; protected override StaticDeserializerBuilder Self => this; public StaticDeserializerBuilder(StaticContext context) : base((ITypeResolver)new StaticTypeResolver()) { this.context = context; factory = context.GetFactory(); typeMappings = new Dictionary(); tagMappings = new Dictionary { { FailsafeSchema.Tags.Map, typeof(Dictionary) }, { FailsafeSchema.Tags.Str, typeof(string) }, { JsonSchema.Tags.Bool, typeof(bool) }, { JsonSchema.Tags.Float, typeof(double) }, { JsonSchema.Tags.Int, typeof(int) }, { DefaultSchema.Tags.Timestamp, typeof(DateTime) } }; typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); nodeDeserializerFactories = new LazyComponentRegistrationList { { typeof(YamlConvertibleNodeDeserializer), (Nothing _) => new YamlConvertibleNodeDeserializer(factory) }, { typeof(YamlSerializableNodeDeserializer), (Nothing _) => new YamlSerializableNodeDeserializer(factory) }, { typeof(TypeConverterNodeDeserializer), (Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters()) }, { typeof(NullNodeDeserializer), (Nothing _) => new NullNodeDeserializer() }, { typeof(ScalarNodeDeserializer), (Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter) }, { typeof(StaticArrayNodeDeserializer), (Nothing _) => new StaticArrayNodeDeserializer(factory) }, { typeof(StaticDictionaryNodeDeserializer), (Nothing _) => new StaticDictionaryNodeDeserializer(factory, duplicateKeyChecking) }, { typeof(StaticCollectionNodeDeserializer), (Nothing _) => new StaticCollectionNodeDeserializer(factory) }, { typeof(ObjectNodeDeserializer), (Nothing _) => new ObjectNodeDeserializer(factory, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter) } }; nodeTypeResolverFactories = new LazyComponentRegistrationList { { typeof(MappingNodeTypeResolver), (Nothing _) => new MappingNodeTypeResolver(typeMappings) }, { typeof(YamlConvertibleTypeResolver), (Nothing _) => new YamlConvertibleTypeResolver() }, { typeof(YamlSerializableTypeResolver), (Nothing _) => new YamlSerializableTypeResolver() }, { typeof(TagNodeTypeResolver), (Nothing _) => new TagNodeTypeResolver(tagMappings) }, { typeof(PreventUnknownTagsNodeTypeResolver), (Nothing _) => new PreventUnknownTagsNodeTypeResolver() }, { typeof(DefaultContainersNodeTypeResolver), (Nothing _) => new DefaultContainersNodeTypeResolver() } }; typeConverter = new NullTypeConverter(); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = context.GetTypeInspector(); return typeInspectorFactories.BuildComponentChain(typeInspector); } public StaticDeserializerBuilder WithAttemptingUnquotedStringTypeDeserialization() { attemptUnknownTypeDeserialization = true; return this; } public StaticDeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer) { return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticDeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action> where) { INodeDeserializer nodeDeserializer2 = nodeDeserializer; if (nodeDeserializer2 == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer2.GetType(), (Nothing _) => nodeDeserializer2)); return this; } public StaticDeserializerBuilder WithNodeDeserializer(WrapperFactory nodeDeserializerFactory, Action> where) where TNodeDeserializer : INodeDeserializer { WrapperFactory nodeDeserializerFactory2 = nodeDeserializerFactory; if (nodeDeserializerFactory2 == null) { throw new ArgumentNullException("nodeDeserializerFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory2(wrapped))); return this; } public StaticDeserializerBuilder WithoutNodeDeserializer() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public StaticDeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if (nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public StaticDeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1) { TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions(); configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions); TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength); return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax s) { s.Before(); }); } public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action> where) { INodeTypeResolver nodeTypeResolver2 = nodeTypeResolver; if (nodeTypeResolver2 == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver2.GetType(), (Nothing _) => nodeTypeResolver2)); return this; } public StaticDeserializerBuilder WithNodeTypeResolver(WrapperFactory nodeTypeResolverFactory, Action> where) where TNodeTypeResolver : INodeTypeResolver { WrapperFactory nodeTypeResolverFactory2 = nodeTypeResolverFactory; if (nodeTypeResolverFactory2 == null) { throw new ArgumentNullException("nodeTypeResolverFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory2(wrapped))); return this; } public StaticDeserializerBuilder WithoutNodeTypeResolver() where TNodeTypeResolver : INodeTypeResolver { return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); } public StaticDeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) { if (nodeTypeResolverType == null) { throw new ArgumentNullException("nodeTypeResolverType"); } nodeTypeResolverFactories.Remove(nodeTypeResolverType); return this; } public override StaticDeserializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(tag, out Type value)) { throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag"); } tagMappings.Add(tag, type); return this; } public StaticDeserializerBuilder WithTypeMapping() where TConcrete : TInterface { Type typeFromHandle = typeof(TInterface); Type typeFromHandle2 = typeof(TConcrete); if (!typeFromHandle.IsAssignableFrom(typeFromHandle2)) { throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'."); } if (typeMappings.ContainsKey(typeFromHandle)) { typeMappings[typeFromHandle] = typeFromHandle2; } else { typeMappings.Add(typeFromHandle, typeFromHandle2); } return this; } public StaticDeserializerBuilder WithoutTagMapping(TagName tag) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (!tagMappings.Remove(tag)) { throw new KeyNotFoundException($"Tag '{tag}' is not registered"); } return this; } public StaticDeserializerBuilder IgnoreUnmatchedProperties() { ignoreUnmatched = true; return this; } public StaticDeserializerBuilder WithDuplicateKeyChecking() { duplicateKeyChecking = true; return this; } public IDeserializer Build() { return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public IValueDeserializer BuildValueDeserializer() { return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter)); } } internal sealed class StaticSerializerBuilder : StaticBuilderSkeleton { private class ValueSerializer : IValueSerializer { private readonly IObjectGraphTraversalStrategy traversalStrategy; private readonly IEventEmitter eventEmitter; private readonly IEnumerable typeConverters; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable typeConverters, LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories) { this.traversalStrategy = traversalStrategy; this.eventEmitter = eventEmitter; this.typeConverters = typeConverters; this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories; this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories; } public void SerializeValue(IEmitter emitter, object? value, Type? type) { IEmitter emitter2 = emitter; Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object)); Type staticType = type ?? typeof(object); ObjectDescriptor graph = new ObjectDescriptor(value, type2, staticType); List> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters); foreach (IObjectGraphVisitor item in preProcessingPhaseObjectGraphVisitors) { traversalStrategy.Traverse(graph, item, default(Nothing)); } IObjectGraphVisitor visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain>(new EmittingObjectGraphVisitor(eventEmitter), (IObjectGraphVisitor inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); traversalStrategy.Traverse(graph, visitor, emitter2); void NestedObjectSerializer(object? v, Type? t) { SerializeValue(emitter2, v, t); } } } private readonly StaticContext context; private readonly StaticObjectFactory factory; private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList eventEmitterFactories; private readonly IDictionary tagMappings = new Dictionary(); private int maximumRecursion = 50; private EmitterSettings emitterSettings = EmitterSettings.Default; private DefaultValuesHandling defaultValuesHandlingConfiguration; private bool quoteNecessaryStrings; protected override StaticSerializerBuilder Self => this; public StaticSerializerBuilder(StaticContext context) : base((ITypeResolver)new DynamicTypeResolver()) { this.context = context; factory = context.GetFactory(); typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList, IObjectGraphVisitor> { { typeof(AnchorAssigner), (IEnumerable typeConverters) => new AnchorAssigner(typeConverters) } }; emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList> { { typeof(CustomSerializationObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer) }, { typeof(AnchorAssigningObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor()) }, { typeof(DefaultValuesObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, factory) }, { typeof(CommentsObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor) } }; eventEmitterFactories = new LazyComponentRegistrationList { { typeof(TypeAssigningEventEmitter), (IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: false, tagMappings, quoteNecessaryStrings) } }; objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention, factory); } public StaticSerializerBuilder WithQuotingNecessaryStrings() { quoteNecessaryStrings = true; return this; } public StaticSerializerBuilder WithMaximumRecursion(int maximumRecursion) { if (maximumRecursion <= 0) { throw new ArgumentOutOfRangeException("maximumRecursion", $"The maximum recursion specified ({maximumRecursion}) is invalid. It should be a positive integer."); } this.maximumRecursion = maximumRecursion; return this; } public StaticSerializerBuilder WithEventEmitter(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticSerializerBuilder WithEventEmitter(Func eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { Func eventEmitterFactory2 = eventEmitterFactory; if (eventEmitterFactory2 == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory2(inner))); return Self; } public StaticSerializerBuilder WithEventEmitter(WrapperFactory eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { WrapperFactory eventEmitterFactory2 = eventEmitterFactory; if (eventEmitterFactory2 == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory2(wrapped, inner))); return Self; } public StaticSerializerBuilder WithoutEventEmitter() where TEventEmitter : IEventEmitter { return WithoutEventEmitter(typeof(TEventEmitter)); } public StaticSerializerBuilder WithoutEventEmitter(Type eventEmitterType) { if (eventEmitterType == null) { throw new ArgumentNullException("eventEmitterType"); } eventEmitterFactories.Remove(eventEmitterType); return this; } public override StaticSerializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(type, out var value)) { throw new ArgumentException($"Type already has a registered tag '{value}' for type '{type.FullName}'", "type"); } tagMappings.Add(type, tag); return this; } public StaticSerializerBuilder WithoutTagMapping(Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (!tagMappings.Remove(type)) { throw new KeyNotFoundException("Tag for type '" + type.FullName + "' is not registered"); } return this; } public StaticSerializerBuilder EnsureRoundtrip() { objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(typeConverters, typeInspector, typeResolver, maximumRecursion, namingConvention, settings, factory); WithEventEmitter((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: true, tagMappings, quoteNecessaryStrings), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); return WithTypeInspector((ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.OnBottom(); }); } public StaticSerializerBuilder DisableAliases() { preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner)); emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor)); return this; } [Obsolete("The default behavior is now to always emit default values, thefore calling this method has no effect. This behavior is now controlled by ConfigureDefaultValuesHandling.", true)] public StaticSerializerBuilder EmitDefaults() { return ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve); } public StaticSerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration) { defaultValuesHandlingConfiguration = configuration; return this; } public StaticSerializerBuilder JsonCompatible() { emitterSettings = emitterSettings.WithMaxSimpleKeyLength(int.MaxValue).WithoutAnchorName(); return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax w) { w.InsteadOf(); }).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); } public StaticSerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(TObjectGraphVisitor objectGraphVisitor, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { TObjectGraphVisitor objectGraphVisitor2 = objectGraphVisitor; if (objectGraphVisitor2 == null) { throw new ArgumentNullException("objectGraphVisitor"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable _) => objectGraphVisitor2)); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, IEnumerable _) => objectGraphVisitorFactory2(wrapped))); return this; } public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public StaticSerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory) { this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory; return this; } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor(Func objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor(Func objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { Func objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(args))); return this; } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(wrapped, args))); return this; } public StaticSerializerBuilder WithoutEmissionPhaseObjectGraphVisitor() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public StaticSerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public StaticSerializerBuilder WithIndentedSequences() { emitterSettings = emitterSettings.WithIndentedSequences(); return this; } public ISerializer Build() { return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings); } public IValueSerializer BuildValueSerializer() { IEnumerable typeConverters = BuildTypeConverters(); ITypeInspector typeInspector = BuildTypeInspector(); IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion); IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter()); return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone()); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = context.GetTypeInspector(); return typeInspectorFactories.BuildComponentChain(typeInspector); } } internal sealed class StreamFragment : IYamlConvertible { private readonly List events = new List(); public IList Events => events; void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { events.Clear(); int num = 0; do { if (!parser.MoveNext()) { throw new InvalidOperationException("The parser has reached the end before deserialization completed."); } ParsingEvent current = parser.Current; events.Add(current); num += current.NestingIncrease; } while (num > 0); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { foreach (ParsingEvent @event in events) { emitter.Emit(@event); } } } internal sealed class TagMappings { private readonly IDictionary mappings; public TagMappings() { mappings = new Dictionary(); } public TagMappings(IDictionary mappings) { this.mappings = new Dictionary(mappings); } public void Add(string tag, Type mapping) { mappings.Add(tag, mapping); } internal Type? GetMapping(string tag) { if (!mappings.TryGetValue(tag, out Type value)) { return null; } return value; } } internal sealed class YamlAttributeOverrides { private struct AttributeKey { public readonly Type AttributeType; public readonly string PropertyName; public AttributeKey(Type attributeType, string propertyName) { AttributeType = attributeType; PropertyName = propertyName; } public override bool Equals(object? obj) { if (obj is AttributeKey attributeKey && AttributeType.Equals(attributeKey.AttributeType)) { return PropertyName.Equals(attributeKey.PropertyName); } return false; } public override int GetHashCode() { return YamlDotNet.Core.HashCode.CombineHashCodes(AttributeType.GetHashCode(), PropertyName.GetHashCode()); } } private sealed class AttributeMapping { public readonly Type RegisteredType; public readonly Attribute Attribute; public AttributeMapping(Type registeredType, Attribute attribute) { RegisteredType = registeredType; Attribute = attribute; } public override bool Equals(object? obj) { if (obj is AttributeMapping attributeMapping && RegisteredType.Equals(attributeMapping.RegisteredType)) { return Attribute.Equals(attributeMapping.Attribute); } return false; } public override int GetHashCode() { return YamlDotNet.Core.HashCode.CombineHashCodes(RegisteredType.GetHashCode(), Attribute.GetHashCode()); } public int Matches(Type matchType) { int num = 0; Type type = matchType; while (type != null) { num++; if (type == RegisteredType) { return num; } type = type.BaseType(); } if (matchType.GetInterfaces().Contains(RegisteredType)) { return num; } return 0; } } private readonly Dictionary> overrides = new Dictionary>(); [return: MaybeNull] public T GetAttribute(Type type, string member) where T : Attribute { if (overrides.TryGetValue(new AttributeKey(typeof(T), member), out List value)) { int num = 0; AttributeMapping attributeMapping = null; foreach (AttributeMapping item in value) { int num2 = item.Matches(type); if (num2 > num) { num = num2; attributeMapping = item; } } if (num > 0) { return (T)attributeMapping.Attribute; } } return null; } public void Add(Type type, string member, Attribute attribute) { AttributeMapping item = new AttributeMapping(type, attribute); AttributeKey key = new AttributeKey(attribute.GetType(), member); if (!overrides.TryGetValue(key, out List value)) { value = new List(); overrides.Add(key, value); } else if (value.Contains(item)) { throw new InvalidOperationException($"Attribute ({attribute}) already set for Type {type.FullName}, Member {member}"); } value.Add(item); } public YamlAttributeOverrides Clone() { YamlAttributeOverrides yamlAttributeOverrides = new YamlAttributeOverrides(); foreach (KeyValuePair> @override in overrides) { foreach (AttributeMapping item in @override.Value) { yamlAttributeOverrides.Add(item.RegisteredType, @override.Key.PropertyName, item.Attribute); } } return yamlAttributeOverrides; } public void Add(Expression> propertyAccessor, Attribute attribute) { PropertyInfo propertyInfo = propertyAccessor.AsProperty(); Add(typeof(TClass), propertyInfo.Name, attribute); } } internal sealed class YamlAttributeOverridesInspector : TypeInspectorSkeleton { public sealed class OverridePropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; private readonly YamlAttributeOverrides overrides; private readonly Type classType; public string Name => baseDescriptor.Name; public bool CanWrite => baseDescriptor.CanWrite; public Type Type => baseDescriptor.Type; public Type? TypeOverride { get { return baseDescriptor.TypeOverride; } set { baseDescriptor.TypeOverride = value; } } public int Order { get { return baseDescriptor.Order; } set { baseDescriptor.Order = value; } } public ScalarStyle ScalarStyle { get { return baseDescriptor.ScalarStyle; } set { baseDescriptor.ScalarStyle = value; } } public OverridePropertyDescriptor(IPropertyDescriptor baseDescriptor, YamlAttributeOverrides overrides, Type classType) { this.baseDescriptor = baseDescriptor; this.overrides = overrides; this.classType = classType; } public void Write(object target, object? value) { baseDescriptor.Write(target, value); } public T? GetCustomAttribute() where T : Attribute { return overrides.GetAttribute(classType, Name) ?? baseDescriptor.GetCustomAttribute(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } private readonly ITypeInspector innerTypeDescriptor; private readonly YamlAttributeOverrides overrides; public YamlAttributeOverridesInspector(ITypeInspector innerTypeDescriptor, YamlAttributeOverrides overrides) { this.innerTypeDescriptor = innerTypeDescriptor; this.overrides = overrides; } public override IEnumerable GetProperties(Type type, object? container) { Type type2 = type; IEnumerable enumerable = innerTypeDescriptor.GetProperties(type2, container); if (overrides != null) { enumerable = enumerable.Select((Func)((IPropertyDescriptor p) => new OverridePropertyDescriptor(p, overrides, type2))); } return enumerable; } } internal sealed class YamlAttributesTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; public YamlAttributesTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor; } public override IEnumerable GetProperties(Type type, object? container) { return from p in (from p in innerTypeDescriptor.GetProperties(type, container) where p.GetCustomAttribute() == null select p).Select((Func)delegate(IPropertyDescriptor p) { PropertyDescriptor propertyDescriptor = new PropertyDescriptor(p); YamlMemberAttribute customAttribute = p.GetCustomAttribute(); if (customAttribute != null) { if (customAttribute.SerializeAs != null) { propertyDescriptor.TypeOverride = customAttribute.SerializeAs; } propertyDescriptor.Order = customAttribute.Order; propertyDescriptor.ScalarStyle = customAttribute.ScalarStyle; if (customAttribute.Alias != null) { propertyDescriptor.Name = customAttribute.Alias; } } return propertyDescriptor; }) orderby p.Order select p; } } internal static class YamlFormatter { public static readonly NumberFormatInfo NumberFormat = new NumberFormatInfo { CurrencyDecimalSeparator = ".", CurrencyGroupSeparator = "_", CurrencyGroupSizes = new int[1] { 3 }, CurrencySymbol = string.Empty, CurrencyDecimalDigits = 99, NumberDecimalSeparator = ".", NumberGroupSeparator = "_", NumberGroupSizes = new int[1] { 3 }, NumberDecimalDigits = 99, NaNSymbol = ".nan", PositiveInfinitySymbol = ".inf", NegativeInfinitySymbol = "-.inf" }; public static string FormatNumber(object number) { return Convert.ToString(number, NumberFormat); } public static string FormatNumber(double number) { return number.ToString("G", NumberFormat); } public static string FormatNumber(float number) { return number.ToString("G", NumberFormat); } public static string FormatBoolean(object boolean) { if (!boolean.Equals(true)) { return "false"; } return "true"; } public static string FormatDateTime(object dateTime) { return ((DateTime)dateTime).ToString("o", CultureInfo.InvariantCulture); } public static string FormatTimeSpan(object timeSpan) { return ((TimeSpan)timeSpan).ToString(); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal sealed class YamlIgnoreAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal sealed class YamlMemberAttribute : Attribute { private DefaultValuesHandling? defaultValuesHandling; public string? Description { get; set; } public Type? SerializeAs { get; set; } public int Order { get; set; } public string? Alias { get; set; } public bool ApplyNamingConventions { get; set; } public ScalarStyle ScalarStyle { get; set; } public DefaultValuesHandling DefaultValuesHandling { get { return defaultValuesHandling.GetValueOrDefault(); } set { defaultValuesHandling = value; } } public bool IsDefaultValuesHandlingSpecified => defaultValuesHandling.HasValue; public YamlMemberAttribute() { ScalarStyle = ScalarStyle.Any; ApplyNamingConventions = true; } public YamlMemberAttribute(Type serializeAs) : this() { SerializeAs = serializeAs ?? throw new ArgumentNullException("serializeAs"); } } [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] internal sealed class YamlSerializableAttribute : Attribute { } internal sealed class YamlStaticContextAttribute : Attribute { } } namespace YamlDotNet.Serialization.ValueDeserializers { internal sealed class AliasValueDeserializer : IValueDeserializer { private sealed class AliasState : Dictionary, IPostDeserializationCallback { public void OnDeserialization() { foreach (ValuePromise value in base.Values) { if (!value.HasValue) { YamlDotNet.Core.Events.AnchorAlias alias = value.Alias; Mark start = alias.Start; Mark end = alias.End; throw new AnchorNotFoundException(in start, in end, $"Anchor '{alias.Value}' not found"); } } } } private sealed class ValuePromise : IValuePromise { private object? value; public readonly YamlDotNet.Core.Events.AnchorAlias? Alias; public bool HasValue { get; private set; } public object? Value { get { if (!HasValue) { throw new InvalidOperationException("Value not set"); } return value; } set { if (HasValue) { throw new InvalidOperationException("Value already set"); } HasValue = true; this.value = value; this.ValueAvailable?.Invoke(value); } } public event Action? ValueAvailable; public ValuePromise(YamlDotNet.Core.Events.AnchorAlias alias) { Alias = alias; } public ValuePromise(object? value) { HasValue = true; this.value = value; } } private readonly IValueDeserializer innerDeserializer; public AliasValueDeserializer(IValueDeserializer innerDeserializer) { this.innerDeserializer = innerDeserializer ?? throw new ArgumentNullException("innerDeserializer"); } public object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { if (parser.TryConsume(out var @event)) { if (!state.Get().TryGetValue(@event.Value, out ValuePromise value)) { Mark start = @event.Start; Mark end = @event.End; throw new AnchorNotFoundException(in start, in end, $"Alias ${@event.Value} cannot precede anchor declaration"); } if (!value.HasValue) { return value; } return value.Value; } AnchorName anchorName = AnchorName.Empty; if (parser.Accept(out var event2) && !event2.Anchor.IsEmpty) { anchorName = event2.Anchor; AliasState aliasState = state.Get(); if (!aliasState.ContainsKey(anchorName)) { aliasState[anchorName] = new ValuePromise(new YamlDotNet.Core.Events.AnchorAlias(anchorName)); } } object obj = innerDeserializer.DeserializeValue(parser, expectedType, state, nestedObjectDeserializer); if (!anchorName.IsEmpty) { AliasState aliasState2 = state.Get(); if (!aliasState2.TryGetValue(anchorName, out ValuePromise value2)) { aliasState2.Add(anchorName, new ValuePromise(obj)); } else if (!value2.HasValue) { value2.Value = obj; } else { aliasState2[anchorName] = new ValuePromise(obj); } } return obj; } } internal sealed class NodeValueDeserializer : IValueDeserializer { private readonly IList deserializers; private readonly IList typeResolvers; private readonly ITypeConverter typeConverter; public NodeValueDeserializer(IList deserializers, IList typeResolvers, ITypeConverter typeConverter) { this.deserializers = deserializers ?? throw new ArgumentNullException("deserializers"); this.typeResolvers = typeResolvers ?? throw new ArgumentNullException("typeResolvers"); this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); } public object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { IValueDeserializer nestedObjectDeserializer2 = nestedObjectDeserializer; SerializerState state2 = state; parser.Accept(out var @event); Type typeFromEvent = GetTypeFromEvent(@event, expectedType); Mark start; Mark end; try { foreach (INodeDeserializer deserializer in deserializers) { if (deserializer.Deserialize(parser, typeFromEvent, (IParser r, Type t) => nestedObjectDeserializer2.DeserializeValue(r, t, state2, nestedObjectDeserializer2), out object value)) { return typeConverter.ChangeType(value, expectedType); } } } catch (YamlException) { throw; } catch (Exception innerException) { start = @event?.Start ?? Mark.Empty; end = @event?.End ?? Mark.Empty; throw new YamlException(in start, in end, "Exception during deserialization", innerException); } start = @event?.Start ?? Mark.Empty; end = @event?.End ?? Mark.Empty; throw new YamlException(in start, in end, "No node deserializer was able to deserialize the node into type " + expectedType.AssemblyQualifiedName); } private Type GetTypeFromEvent(NodeEvent? nodeEvent, Type currentType) { using (IEnumerator enumerator = typeResolvers.GetEnumerator()) { while (enumerator.MoveNext() && !enumerator.Current.Resolve(nodeEvent, ref currentType)) { } } return currentType; } } } namespace YamlDotNet.Serialization.Utilities { internal interface IPostDeserializationCallback { void OnDeserialization(); } internal interface ITypeConverter { object? ChangeType(object? value, Type expectedType); } internal class NullTypeConverter : ITypeConverter { public object? ChangeType(object? value, Type expectedType) { return value; } } internal sealed class ObjectAnchorCollection { private readonly IDictionary objectsByAnchor = new Dictionary(); private readonly IDictionary anchorsByObject = new Dictionary(); public object this[string anchor] { get { if (objectsByAnchor.TryGetValue(anchor, out object value)) { return value; } throw new AnchorNotFoundException("The anchor '" + anchor + "' does not exists"); } } public void Add(string anchor, object @object) { objectsByAnchor.Add(anchor, @object); if (@object != null) { anchorsByObject.Add(@object, anchor); } } public bool TryGetAnchor(object @object, [MaybeNullWhen(false)] out string? anchor) { return anchorsByObject.TryGetValue(@object, out anchor); } } internal class ReflectionTypeConverter : ITypeConverter { public object? ChangeType(object? value, Type expectedType) { return TypeConverter.ChangeType(value, expectedType); } } internal static class ReflectionUtility { public static Type? GetImplementedGenericInterface(Type type, Type genericInterfaceType) { foreach (Type implementedInterface in GetImplementedInterfaces(type)) { if (implementedInterface.IsGenericType() && implementedInterface.GetGenericTypeDefinition() == genericInterfaceType) { return implementedInterface; } } return null; } public static IEnumerable GetImplementedInterfaces(Type type) { if (type.IsInterface()) { yield return type; } Type[] interfaces = type.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { yield return interfaces[i]; } } } internal sealed class SerializerState : IDisposable { private readonly IDictionary items = new Dictionary(); public T Get() where T : class, new() { if (!items.TryGetValue(typeof(T), out object value)) { value = new T(); items.Add(typeof(T), value); } return (T)value; } public void OnDeserialization() { foreach (IPostDeserializationCallback item in items.Values.OfType()) { item.OnDeserialization(); } } public void Dispose() { foreach (IDisposable item in items.Values.OfType()) { item.Dispose(); } } } internal static class StringExtensions { private static string ToCamelOrPascalCase(string str, Func firstLetterTransform) { string text = Regex.Replace(str, "([_\\-])(?[a-z])", (Match match) => match.Groups["char"].Value.ToUpperInvariant(), RegexOptions.IgnoreCase); return firstLetterTransform(text[0]) + text.Substring(1); } public static string ToCamelCase(this string str) { return ToCamelOrPascalCase(str, char.ToLowerInvariant); } public static string ToPascalCase(this string str) { return ToCamelOrPascalCase(str, char.ToUpperInvariant); } public static string FromCamelCase(this string str, string separator) { string separator2 = separator; str = char.ToLower(str[0]) + str.Substring(1); str = Regex.Replace(str.ToCamelCase(), "(?[A-Z])", (Match match) => separator2 + match.Groups["char"].Value.ToLowerInvariant()); return str; } } internal static class TypeConverter { public static T ChangeType(object? value) { return (T)ChangeType(value, typeof(T)); } public static T ChangeType(object? value, IFormatProvider provider) { return (T)ChangeType(value, typeof(T), provider); } public static T ChangeType(object? value, CultureInfo culture) { return (T)ChangeType(value, typeof(T), culture); } public static object? ChangeType(object? value, Type destinationType) { return ChangeType(value, destinationType, CultureInfo.InvariantCulture); } public static object? ChangeType(object? value, Type destinationType, IFormatProvider provider) { return ChangeType(value, destinationType, new CultureInfoAdapter(CultureInfo.CurrentCulture, provider)); } public static object? ChangeType(object? value, Type destinationType, CultureInfo culture) { if (value == null || value.IsDbNull()) { if (!destinationType.IsValueType()) { return null; } return Activator.CreateInstance(destinationType); } Type type = value.GetType(); if (destinationType == type || destinationType.IsAssignableFrom(type)) { return value; } if (destinationType.IsGenericType() && destinationType.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type destinationType2 = destinationType.GetGenericArguments()[0]; object obj = ChangeType(value, destinationType2, culture); return Activator.CreateInstance(destinationType, obj); } if (destinationType.IsEnum()) { if (!(value is string value2)) { return value; } return Enum.Parse(destinationType, value2, ignoreCase: true); } if (destinationType == typeof(bool)) { if ("0".Equals(value)) { return false; } if ("1".Equals(value)) { return true; } } System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter != null && converter.CanConvertTo(destinationType)) { return converter.ConvertTo(null, culture, value, destinationType); } System.ComponentModel.TypeConverter converter2 = TypeDescriptor.GetConverter(destinationType); if (converter2 != null && converter2.CanConvertFrom(type)) { return converter2.ConvertFrom(null, culture, value); } Type[] array = new Type[2] { type, destinationType }; for (int i = 0; i < array.Length; i++) { foreach (MethodInfo publicStaticMethod2 in array[i].GetPublicStaticMethods()) { if (!publicStaticMethod2.IsSpecialName || (!(publicStaticMethod2.Name == "op_Implicit") && !(publicStaticMethod2.Name == "op_Explicit")) || !destinationType.IsAssignableFrom(publicStaticMethod2.ReturnParameter.ParameterType)) { continue; } ParameterInfo[] parameters = publicStaticMethod2.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(type)) { try { return publicStaticMethod2.Invoke(null, new object[1] { value }); } catch (TargetInvocationException ex) { throw ex.Unwrap(); } } } } if (type == typeof(string)) { try { MethodInfo publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string), typeof(IFormatProvider)); if (publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[2] { value, culture }); } publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string)); if (publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[1] { value }); } } catch (TargetInvocationException ex2) { throw ex2.Unwrap(); } } if (destinationType == typeof(TimeSpan)) { return TimeSpan.Parse((string)ChangeType(value, typeof(string), CultureInfo.InvariantCulture)); } return Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture); } public static void RegisterTypeConverter() where TConverter : System.ComponentModel.TypeConverter { if (!TypeDescriptor.GetAttributes(typeof(TConvertible)).OfType().Any((TypeConverterAttribute a) => a.ConverterTypeName == typeof(TConverter).AssemblyQualifiedName)) { TypeDescriptor.AddAttributes(typeof(TConvertible), new TypeConverterAttribute(typeof(TConverter))); } } } } namespace YamlDotNet.Serialization.TypeResolvers { internal sealed class DynamicTypeResolver : ITypeResolver { public Type Resolve(Type staticType, object? actualValue) { if (actualValue == null) { return staticType; } return actualValue.GetType(); } } internal sealed class StaticTypeResolver : ITypeResolver { public Type Resolve(Type staticType, object? actualValue) { return staticType; } } } namespace YamlDotNet.Serialization.TypeInspectors { internal sealed class CachedTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly ConcurrentDictionary> cache = new ConcurrentDictionary>(); public CachedTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); } public override IEnumerable GetProperties(Type type, object? container) { object container2 = container; return cache.GetOrAdd(type, (Type t) => innerTypeDescriptor.GetProperties(t, container2).ToList()); } } internal sealed class CompositeTypeInspector : TypeInspectorSkeleton { private readonly IEnumerable typeInspectors; public CompositeTypeInspector(params ITypeInspector[] typeInspectors) : this((IEnumerable)typeInspectors) { } public CompositeTypeInspector(IEnumerable typeInspectors) { this.typeInspectors = typeInspectors?.ToList() ?? throw new ArgumentNullException("typeInspectors"); } public override IEnumerable GetProperties(Type type, object? container) { Type type2 = type; object container2 = container; return typeInspectors.SelectMany((ITypeInspector i) => i.GetProperties(type2, container2)); } } internal sealed class NamingConventionTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly INamingConvention namingConvention; public NamingConventionTypeInspector(ITypeInspector innerTypeDescriptor, INamingConvention namingConvention) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); } public override IEnumerable GetProperties(Type type, object? container) { return innerTypeDescriptor.GetProperties(type, container).Select(delegate(IPropertyDescriptor p) { YamlMemberAttribute customAttribute = p.GetCustomAttribute(); return (customAttribute != null && !customAttribute.ApplyNamingConventions) ? p : new PropertyDescriptor(p) { Name = namingConvention.Apply(p.Name) }; }); } } internal sealed class ReadableAndWritablePropertiesTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; public ReadableAndWritablePropertiesTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); } public override IEnumerable GetProperties(Type type, object? container) { return from p in innerTypeDescriptor.GetProperties(type, container) where p.CanWrite select p; } } internal sealed class ReadableFieldsTypeInspector : TypeInspectorSkeleton { private sealed class ReflectionFieldDescriptor : IPropertyDescriptor { private readonly FieldInfo fieldInfo; private readonly ITypeResolver typeResolver; public string Name => fieldInfo.Name; public Type Type => fieldInfo.FieldType; public Type? TypeOverride { get; set; } public int Order { get; set; } public bool CanWrite => !fieldInfo.IsInitOnly; public ScalarStyle ScalarStyle { get; set; } public ReflectionFieldDescriptor(FieldInfo fieldInfo, ITypeResolver typeResolver) { this.fieldInfo = fieldInfo; this.typeResolver = typeResolver; ScalarStyle = ScalarStyle.Any; } public void Write(object target, object? value) { fieldInfo.SetValue(target, value); } public T? GetCustomAttribute() where T : Attribute { return (T)fieldInfo.GetCustomAttributes(typeof(T), inherit: true).FirstOrDefault(); } public IObjectDescriptor Read(object target) { object value = fieldInfo.GetValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, value); return new ObjectDescriptor(value, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; public ReadableFieldsTypeInspector(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); } public override IEnumerable GetProperties(Type type, object? container) { return type.GetPublicFields().Select((Func)((FieldInfo p) => new ReflectionFieldDescriptor(p, typeResolver))); } } internal sealed class ReadablePropertiesTypeInspector : TypeInspectorSkeleton { private sealed class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly ITypeResolver typeResolver; public string Name => propertyInfo.Name; public Type Type => propertyInfo.PropertyType; public Type? TypeOverride { get; set; } public int Order { get; set; } public bool CanWrite => propertyInfo.CanWrite; public ScalarStyle ScalarStyle { get; set; } public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, ITypeResolver typeResolver) { this.propertyInfo = propertyInfo ?? throw new ArgumentNullException("propertyInfo"); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); ScalarStyle = ScalarStyle.Any; } public void Write(object target, object? value) { propertyInfo.SetValue(target, value, null); } public T? GetCustomAttribute() where T : Attribute { return (T)propertyInfo.GetAllCustomAttributes().FirstOrDefault(); } public IObjectDescriptor Read(object target) { object obj = propertyInfo.ReadValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, obj); return new ObjectDescriptor(obj, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; private readonly bool includeNonPublicProperties; public ReadablePropertiesTypeInspector(ITypeResolver typeResolver) : this(typeResolver, includeNonPublicProperties: false) { } public ReadablePropertiesTypeInspector(ITypeResolver typeResolver, bool includeNonPublicProperties) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); this.includeNonPublicProperties = includeNonPublicProperties; } private static bool IsValidProperty(PropertyInfo property) { if (property.CanRead) { return property.GetGetMethod(nonPublic: true).GetParameters().Length == 0; } return false; } public override IEnumerable GetProperties(Type type, object? container) { return type.GetProperties(includeNonPublicProperties).Where(IsValidProperty).Select((Func)((PropertyInfo p) => new ReflectionPropertyDescriptor(p, typeResolver))); } } internal abstract class TypeInspectorSkeleton : ITypeInspector { public abstract IEnumerable GetProperties(Type type, object? container); public IPropertyDescriptor GetProperty(Type type, object? container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched) { string name2 = name; IEnumerable enumerable = from p in GetProperties(type, container) where p.Name == name2 select p; using IEnumerator enumerator = enumerable.GetEnumerator(); if (!enumerator.MoveNext()) { if (ignoreUnmatched) { return null; } throw new SerializationException("Property '" + name2 + "' not found on type '" + type.FullName + "'."); } IPropertyDescriptor current = enumerator.Current; if (enumerator.MoveNext()) { throw new SerializationException("Multiple properties with the name/alias '" + name2 + "' already exists on type '" + type.FullName + "', maybe you're misusing YamlAlias or maybe you are using the wrong naming convention? The matching properties are: " + string.Join(", ", enumerable.Select((IPropertyDescriptor p) => p.Name).ToArray())); } return current; } } internal sealed class WritablePropertiesTypeInspector : TypeInspectorSkeleton { private sealed class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly ITypeResolver typeResolver; public string Name => propertyInfo.Name; public Type Type => propertyInfo.PropertyType; public Type? TypeOverride { get; set; } public int Order { get; set; } public bool CanWrite => propertyInfo.CanWrite; public ScalarStyle ScalarStyle { get; set; } public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, ITypeResolver typeResolver) { this.propertyInfo = propertyInfo ?? throw new ArgumentNullException("propertyInfo"); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); ScalarStyle = ScalarStyle.Any; } public void Write(object target, object? value) { propertyInfo.SetValue(target, value, null); } public T? GetCustomAttribute() where T : Attribute { return (T)propertyInfo.GetAllCustomAttributes().FirstOrDefault(); } public IObjectDescriptor Read(object target) { object obj = propertyInfo.ReadValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, obj); return new ObjectDescriptor(obj, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; private readonly bool includeNonPublicProperties; public WritablePropertiesTypeInspector(ITypeResolver typeResolver) : this(typeResolver, includeNonPublicProperties: false) { } public WritablePropertiesTypeInspector(ITypeResolver typeResolver, bool includeNonPublicProperties) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); this.includeNonPublicProperties = includeNonPublicProperties; } private static bool IsValidProperty(PropertyInfo property) { if (property.CanWrite) { return property.GetSetMethod(nonPublic: true).GetParameters().Length == 1; } return false; } public override IEnumerable GetProperties(Type type, object? container) { return type.GetProperties(includeNonPublicProperties).Where(IsValidProperty).Select((Func)((PropertyInfo p) => new ReflectionPropertyDescriptor(p, typeResolver))) .ToArray(); } } } namespace YamlDotNet.Serialization.Schemas { internal sealed class FailsafeSchema { public static class Tags { public static readonly TagName Map = new TagName("tag:yaml.org,2002:map"); public static readonly TagName Seq = new TagName("tag:yaml.org,2002:seq"); public static readonly TagName Str = new TagName("tag:yaml.org,2002:str"); } } internal sealed class JsonSchema { public static class Tags { public static readonly TagName Null = new TagName("tag:yaml.org,2002:null"); public static readonly TagName Bool = new TagName("tag:yaml.org,2002:bool"); public static readonly TagName Int = new TagName("tag:yaml.org,2002:int"); public static readonly TagName Float = new TagName("tag:yaml.org,2002:float"); } } internal sealed class CoreSchema { public static class Tags { } } internal sealed class DefaultSchema { public static class Tags { public static readonly TagName Timestamp = new TagName("tag:yaml.org,2002:timestamp"); } } } namespace YamlDotNet.Serialization.ObjectGraphVisitors { internal sealed class AnchorAssigner : PreProcessingPhaseObjectGraphVisitorSkeleton, IAliasProvider { private class AnchorAssignment { public AnchorName Anchor; } private readonly IDictionary assignments = new Dictionary(); private uint nextId; public AnchorAssigner(IEnumerable typeConverters) : base(typeConverters) { } protected override bool Enter(IObjectDescriptor value) { if (value.Value != null && assignments.TryGetValue(value.Value, out AnchorAssignment value2)) { if (value2.Anchor.IsEmpty) { value2.Anchor = new AnchorName("o" + nextId.ToString(CultureInfo.InvariantCulture)); nextId++; } return false; } return true; } protected override bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value) { return true; } protected override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value) { return true; } protected override void VisitScalar(IObjectDescriptor scalar) { } protected override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType) { VisitObject(mapping); } protected override void VisitMappingEnd(IObjectDescriptor mapping) { } protected override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType) { VisitObject(sequence); } protected override void VisitSequenceEnd(IObjectDescriptor sequence) { } private void VisitObject(IObjectDescriptor value) { if (value.Value != null) { assignments.Add(value.Value, new AnchorAssignment()); } } AnchorName IAliasProvider.GetAlias(object target) { if (target != null && assignments.TryGetValue(target, out AnchorAssignment value)) { return value.Anchor; } return AnchorName.Empty; } } internal sealed class AnchorAssigningObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly IEventEmitter eventEmitter; private readonly IAliasProvider aliasProvider; private readonly HashSet emittedAliases = new HashSet(); public AnchorAssigningObjectGraphVisitor(IObjectGraphVisitor nextVisitor, IEventEmitter eventEmitter, IAliasProvider aliasProvider) : base(nextVisitor) { this.eventEmitter = eventEmitter; this.aliasProvider = aliasProvider; } public override bool Enter(IObjectDescriptor value, IEmitter context) { if (value.Value != null) { AnchorName alias = aliasProvider.GetAlias(value.Value); if (!alias.IsEmpty && !emittedAliases.Add(alias)) { AliasEventInfo aliasEventInfo = new AliasEventInfo(value, alias); eventEmitter.Emit(aliasEventInfo, context); return aliasEventInfo.NeedsExpansion; } } return base.Enter(value, context); } public override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) { AnchorName alias = aliasProvider.GetAlias(mapping.NonNullValue()); eventEmitter.Emit(new MappingStartEventInfo(mapping) { Anchor = alias }, context); } public override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) { AnchorName alias = aliasProvider.GetAlias(sequence.NonNullValue()); eventEmitter.Emit(new SequenceStartEventInfo(sequence) { Anchor = alias }, context); } public override void VisitScalar(IObjectDescriptor scalar, IEmitter context) { ScalarEventInfo scalarEventInfo = new ScalarEventInfo(scalar); if (scalar.Value != null) { scalarEventInfo.Anchor = aliasProvider.GetAlias(scalar.Value); } eventEmitter.Emit(scalarEventInfo, context); } } internal abstract class ChainedObjectGraphVisitor : IObjectGraphVisitor { private readonly IObjectGraphVisitor nextVisitor; protected ChainedObjectGraphVisitor(IObjectGraphVisitor nextVisitor) { this.nextVisitor = nextVisitor; } public virtual bool Enter(IObjectDescriptor value, IEmitter context) { return nextVisitor.Enter(value, context); } public virtual bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) { return nextVisitor.EnterMapping(key, value, context); } public virtual bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { return nextVisitor.EnterMapping(key, value, context); } public virtual void VisitScalar(IObjectDescriptor scalar, IEmitter context) { nextVisitor.VisitScalar(scalar, context); } public virtual void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) { nextVisitor.VisitMappingStart(mapping, keyType, valueType, context); } public virtual void VisitMappingEnd(IObjectDescriptor mapping, IEmitter context) { nextVisitor.VisitMappingEnd(mapping, context); } public virtual void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) { nextVisitor.VisitSequenceStart(sequence, elementType, context); } public virtual void VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context) { nextVisitor.VisitSequenceEnd(sequence, context); } } internal sealed class CommentsObjectGraphVisitor : ChainedObjectGraphVisitor { public CommentsObjectGraphVisitor(IObjectGraphVisitor nextVisitor) : base(nextVisitor) { } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { YamlMemberAttribute customAttribute = key.GetCustomAttribute(); if (customAttribute != null && customAttribute.Description != null) { context.Emit(new YamlDotNet.Core.Events.Comment(customAttribute.Description, isInline: false)); } return base.EnterMapping(key, value, context); } } internal sealed class CustomSerializationObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly IEnumerable typeConverters; private readonly ObjectSerializer nestedObjectSerializer; public CustomSerializationObjectGraphVisitor(IObjectGraphVisitor nextVisitor, IEnumerable typeConverters, ObjectSerializer nestedObjectSerializer) : base(nextVisitor) { IEnumerable enumerable; if (typeConverters == null) { enumerable = Enumerable.Empty(); } else { IEnumerable enumerable2 = typeConverters.ToList(); enumerable = enumerable2; } this.typeConverters = enumerable; this.nestedObjectSerializer = nestedObjectSerializer; } public override bool Enter(IObjectDescriptor value, IEmitter context) { IObjectDescriptor value2 = value; IYamlTypeConverter yamlTypeConverter = typeConverters.FirstOrDefault((IYamlTypeConverter t) => t.Accepts(value2.Type)); if (yamlTypeConverter != null) { yamlTypeConverter.WriteYaml(context, value2.Value, value2.Type); return false; } if (value2.Value is IYamlConvertible yamlConvertible) { yamlConvertible.Write(context, nestedObjectSerializer); return false; } if (value2.Value is IYamlSerializable yamlSerializable) { yamlSerializable.WriteYaml(context); return false; } return base.Enter(value2, context); } } internal sealed class DefaultExclusiveObjectGraphVisitor : ChainedObjectGraphVisitor { public DefaultExclusiveObjectGraphVisitor(IObjectGraphVisitor nextVisitor) : base(nextVisitor) { } private static object? GetDefault(Type type) { if (!type.IsValueType()) { return null; } return Activator.CreateInstance(type); } public override bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) { if (!object.Equals(value.Value, GetDefault(value.Type))) { return base.EnterMapping(key, value, context); } return false; } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { DefaultValueAttribute customAttribute = key.GetCustomAttribute(); object objB = ((customAttribute != null) ? customAttribute.Value : GetDefault(key.Type)); if (!object.Equals(value.Value, objB)) { return base.EnterMapping(key, value, context); } return false; } } internal sealed class DefaultValuesObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly DefaultValuesHandling handling; private readonly IObjectFactory factory; public DefaultValuesObjectGraphVisitor(DefaultValuesHandling handling, IObjectGraphVisitor nextVisitor, IObjectFactory factory) : base(nextVisitor) { this.handling = handling; this.factory = factory; } private object? GetDefault(Type type) { return factory.CreatePrimitive(type); } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { DefaultValuesHandling defaultValuesHandling = handling; YamlMemberAttribute customAttribute = key.GetCustomAttribute(); if (customAttribute != null && customAttribute.IsDefaultValuesHandlingSpecified) { defaultValuesHandling = customAttribute.DefaultValuesHandling; } if ((defaultValuesHandling & DefaultValuesHandling.OmitNull) != 0 && value.Value == null) { return false; } if ((defaultValuesHandling & DefaultValuesHandling.OmitEmptyCollections) != 0 && value.Value is IEnumerable enumerable) { IEnumerator enumerator = enumerable.GetEnumerator(); bool flag = enumerator.MoveNext(); if (enumerator is IDisposable disposable) { disposable.Dispose(); } if (!flag) { return false; } } if ((defaultValuesHandling & DefaultValuesHandling.OmitDefaults) != 0) { object objB = key.GetCustomAttribute()?.Value ?? GetDefault(key.Type); if (object.Equals(value.Value, objB)) { return false; } } return base.EnterMapping(key, value, context); } } internal sealed class EmittingObjectGraphVisitor : IObjectGraphVisitor { private readonly IEventEmitter eventEmitter; public EmittingObjectGraphVisitor(IEventEmitter eventEmitter) { this.eventEmitter = eventEmitter; } bool IObjectGraphVisitor.Enter(IObjectDescriptor value, IEmitter context) { return true; } bool IObjectGraphVisitor.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) { return true; } bool IObjectGraphVisitor.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { return true; } void IObjectGraphVisitor.VisitScalar(IObjectDescriptor scalar, IEmitter context) { eventEmitter.Emit(new ScalarEventInfo(scalar), context); } void IObjectGraphVisitor.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) { eventEmitter.Emit(new MappingStartEventInfo(mapping), context); } void IObjectGraphVisitor.VisitMappingEnd(IObjectDescriptor mapping, IEmitter context) { eventEmitter.Emit(new MappingEndEventInfo(mapping), context); } void IObjectGraphVisitor.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) { eventEmitter.Emit(new SequenceStartEventInfo(sequence), context); } void IObjectGraphVisitor.VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context) { eventEmitter.Emit(new SequenceEndEventInfo(sequence), context); } } internal abstract class PreProcessingPhaseObjectGraphVisitorSkeleton : IObjectGraphVisitor { protected readonly IEnumerable typeConverters; public PreProcessingPhaseObjectGraphVisitorSkeleton(IEnumerable typeConverters) { IEnumerable enumerable; if (typeConverters == null) { enumerable = Enumerable.Empty(); } else { IEnumerable enumerable2 = typeConverters.ToList(); enumerable = enumerable2; } this.typeConverters = enumerable; } bool IObjectGraphVisitor.Enter(IObjectDescriptor value, Nothing context) { IObjectDescriptor value2 = value; if (typeConverters.FirstOrDefault((IYamlTypeConverter t) => t.Accepts(value2.Type)) != null) { return false; } if (value2.Value is IYamlConvertible) { return false; } if (value2.Value is IYamlSerializable) { return false; } return Enter(value2); } bool IObjectGraphVisitor.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, Nothing context) { return EnterMapping(key, value); } bool IObjectGraphVisitor.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, Nothing context) { return EnterMapping(key, value); } void IObjectGraphVisitor.VisitMappingEnd(IObjectDescriptor mapping, Nothing context) { VisitMappingEnd(mapping); } void IObjectGraphVisitor.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, Nothing context) { VisitMappingStart(mapping, keyType, valueType); } void IObjectGraphVisitor.VisitScalar(IObjectDescriptor scalar, Nothing context) { VisitScalar(scalar); } void IObjectGraphVisitor.VisitSequenceEnd(IObjectDescriptor sequence, Nothing context) { VisitSequenceEnd(sequence); } void IObjectGraphVisitor.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, Nothing context) { VisitSequenceStart(sequence, elementType); } protected abstract bool Enter(IObjectDescriptor value); protected abstract bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value); protected abstract bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value); protected abstract void VisitMappingEnd(IObjectDescriptor mapping); protected abstract void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType); protected abstract void VisitScalar(IObjectDescriptor scalar); protected abstract void VisitSequenceEnd(IObjectDescriptor sequence); protected abstract void VisitSequenceStart(IObjectDescriptor sequence, Type elementType); } } namespace YamlDotNet.Serialization.ObjectGraphTraversalStrategies { internal class FullObjectGraphTraversalStrategy : IObjectGraphTraversalStrategy { protected struct ObjectPathSegment { public readonly object Name; public readonly IObjectDescriptor Value; public ObjectPathSegment(object name, IObjectDescriptor value) { Name = name; Value = value; } } private readonly int maxRecursion; private readonly ITypeInspector typeDescriptor; private readonly ITypeResolver typeResolver; private readonly INamingConvention namingConvention; private readonly IObjectFactory objectFactory; public FullObjectGraphTraversalStrategy(ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention, IObjectFactory objectFactory) { if (maxRecursion <= 0) { throw new ArgumentOutOfRangeException("maxRecursion", maxRecursion, "maxRecursion must be greater than 1"); } this.typeDescriptor = typeDescriptor ?? throw new ArgumentNullException("typeDescriptor"); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); this.maxRecursion = maxRecursion; this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } void IObjectGraphTraversalStrategy.Traverse(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context) { Traverse("", graph, visitor, context, new Stack(maxRecursion)); } protected virtual void Traverse(object name, IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { if (path.Count >= maxRecursion) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Too much recursion when traversing the object graph."); stringBuilder.AppendLine("The path to reach this recursion was:"); Stack> stack = new Stack>(path.Count); int num = 0; foreach (ObjectPathSegment item in path) { string text = item.Name?.ToString() ?? string.Empty; num = Math.Max(num, text.Length); stack.Push(new KeyValuePair(text, item.Value.Type.FullName)); } foreach (KeyValuePair item2 in stack) { stringBuilder.Append(" -> ").Append(item2.Key.PadRight(num)).Append(" [") .Append(item2.Value) .AppendLine("]"); } throw new MaximumRecursionLevelReachedException(stringBuilder.ToString()); } if (!visitor.Enter(value, context)) { return; } path.Push(new ObjectPathSegment(name, value)); try { TypeCode typeCode = value.Type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: case TypeCode.DateTime: case TypeCode.String: visitor.VisitScalar(value, context); return; case TypeCode.Empty: throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } if (value.IsDbNull()) { visitor.VisitScalar(new ObjectDescriptor(null, typeof(object), typeof(object)), context); } if (value.Value == null || value.Type == typeof(TimeSpan)) { visitor.VisitScalar(value, context); return; } Type underlyingType = Nullable.GetUnderlyingType(value.Type); if (underlyingType != null) { Traverse("Value", new ObjectDescriptor(value.Value, underlyingType, value.Type, value.ScalarStyle), visitor, context, path); } else { TraverseObject(value, visitor, context, path); } } finally { path.Pop(); } } protected virtual void TraverseObject(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { IDictionary dictionary; Type[] genericArguments; if (typeof(IDictionary).IsAssignableFrom(value.Type)) { TraverseDictionary(value, visitor, typeof(object), typeof(object), context, path); } else if (objectFactory.GetDictionary(value, out dictionary, out genericArguments)) { TraverseDictionary(new ObjectDescriptor(dictionary, value.Type, value.StaticType, value.ScalarStyle), visitor, genericArguments[0], genericArguments[1], context, path); } else if (typeof(IEnumerable).IsAssignableFrom(value.Type)) { TraverseList(value, visitor, context, path); } else { TraverseProperties(value, visitor, context, path); } } protected virtual void TraverseDictionary(IObjectDescriptor dictionary, IObjectGraphVisitor visitor, Type keyType, Type valueType, TContext context, Stack path) { visitor.VisitMappingStart(dictionary, keyType, valueType, context); bool flag = dictionary.Type.FullName.Equals("System.Dynamic.ExpandoObject"); foreach (DictionaryEntry? item in (IDictionary)dictionary.NonNullValue()) { DictionaryEntry value = item.Value; object obj = (flag ? namingConvention.Apply(value.Key.ToString()) : value.Key); IObjectDescriptor objectDescriptor = GetObjectDescriptor(obj, keyType); IObjectDescriptor objectDescriptor2 = GetObjectDescriptor(value.Value, valueType); if (visitor.EnterMapping(objectDescriptor, objectDescriptor2, context)) { Traverse(obj, objectDescriptor, visitor, context, path); Traverse(obj, objectDescriptor2, visitor, context, path); } } visitor.VisitMappingEnd(dictionary, context); } private void TraverseList(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { Type valueType = objectFactory.GetValueType(value.Type); visitor.VisitSequenceStart(value, valueType, context); int num = 0; foreach (object item in (IEnumerable)value.NonNullValue()) { Traverse(num, GetObjectDescriptor(item, valueType), visitor, context, path); num++; } visitor.VisitSequenceEnd(value, context); } protected virtual void TraverseProperties(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { visitor.VisitMappingStart(value, typeof(string), typeof(object), context); object obj = value.NonNullValue(); foreach (IPropertyDescriptor property in typeDescriptor.GetProperties(value.Type, obj)) { IObjectDescriptor value2 = property.Read(obj); if (visitor.EnterMapping(property, value2, context)) { Traverse(property.Name, new ObjectDescriptor(property.Name, typeof(string), typeof(string), ScalarStyle.Plain), visitor, context, path); Traverse(property.Name, value2, visitor, context, path); } } visitor.VisitMappingEnd(value, context); } private IObjectDescriptor GetObjectDescriptor(object? value, Type staticType) { return new ObjectDescriptor(value, typeResolver.Resolve(staticType, value), staticType); } } internal class RoundtripObjectGraphTraversalStrategy : FullObjectGraphTraversalStrategy { private readonly IEnumerable converters; private readonly Settings settings; public RoundtripObjectGraphTraversalStrategy(IEnumerable converters, ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention, Settings settings, IObjectFactory factory) : base(typeDescriptor, typeResolver, maxRecursion, namingConvention, factory) { this.converters = converters; this.settings = settings; } protected override void TraverseProperties(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { IObjectDescriptor value2 = value; if (!value2.Type.HasDefaultConstructor(settings.AllowPrivateConstructors) && !converters.Any((IYamlTypeConverter c) => c.Accepts(value2.Type))) { throw new InvalidOperationException($"Type '{value2.Type}' cannot be deserialized because it does not have a default constructor or a type converter."); } base.TraverseProperties(value2, visitor, context, path); } } } namespace YamlDotNet.Serialization.ObjectFactories { internal sealed class DefaultObjectFactory : ObjectFactoryBase { private readonly Dictionary DefaultGenericInterfaceImplementations = new Dictionary { { typeof(IEnumerable<>), typeof(List<>) }, { typeof(ICollection<>), typeof(List<>) }, { typeof(IList<>), typeof(List<>) }, { typeof(IDictionary<, >), typeof(Dictionary<, >) } }; private readonly Dictionary DefaultNonGenericInterfaceImplementations = new Dictionary { { typeof(IEnumerable), typeof(List) }, { typeof(ICollection), typeof(List) }, { typeof(IList), typeof(List) }, { typeof(IDictionary), typeof(Dictionary) } }; private readonly Settings settings; public DefaultObjectFactory() : this(new Dictionary(), new Settings()) { } public DefaultObjectFactory(IDictionary mappings) : this(mappings, new Settings()) { } public DefaultObjectFactory(IDictionary mappings, Settings settings) { foreach (KeyValuePair mapping in mappings) { if (!mapping.Key.IsAssignableFrom(mapping.Value)) { throw new InvalidOperationException($"Type '{mapping.Value}' does not implement type '{mapping.Key}'."); } DefaultNonGenericInterfaceImplementations.Add(mapping.Key, mapping.Value); } this.settings = settings; } public override object Create(Type type) { if (type.IsInterface()) { Type value2; if (type.IsGenericType()) { if (DefaultGenericInterfaceImplementations.TryGetValue(type.GetGenericTypeDefinition(), out Type value)) { type = value.MakeGenericType(type.GetGenericArguments()); } } else if (DefaultNonGenericInterfaceImplementations.TryGetValue(type, out value2)) { type = value2; } } try { return Activator.CreateInstance(type, settings.AllowPrivateConstructors); } catch (Exception innerException) { throw new InvalidOperationException("Failed to create an instance of type '" + type.FullName + "'.", innerException); } } } internal sealed class LambdaObjectFactory : ObjectFactoryBase { private readonly Func factory; public LambdaObjectFactory(Func factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public override object Create(Type type) { return factory(type); } } internal abstract class ObjectFactoryBase : IObjectFactory { public abstract object Create(Type type); public virtual object? CreatePrimitive(Type type) { if (!type.IsValueType()) { return null; } return Activator.CreateInstance(type); } public virtual bool GetDictionary(IObjectDescriptor descriptor, out IDictionary? dictionary, out Type[]? genericArguments) { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(descriptor.Type, typeof(IDictionary<, >)); if (implementedGenericInterface != null) { genericArguments = implementedGenericInterface.GetGenericArguments(); object obj = Activator.CreateInstance(typeof(GenericDictionaryToNonGenericAdapter<, >).MakeGenericType(genericArguments), descriptor.Value); dictionary = obj as IDictionary; return true; } genericArguments = null; dictionary = null; return false; } public virtual Type GetValueType(Type type) { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(type, typeof(IEnumerable<>)); if (!(implementedGenericInterface != null)) { return typeof(object); } return implementedGenericInterface.GetGenericArguments()[0]; } } internal abstract class StaticObjectFactory : IObjectFactory { public abstract object Create(Type type); public abstract Array CreateArray(Type type, int count); public abstract bool IsDictionary(Type type); public abstract bool IsArray(Type type); public abstract bool IsList(Type type); public abstract Type GetKeyType(Type type); public abstract Type GetValueType(Type type); public virtual object? CreatePrimitive(Type type) { return Type.GetTypeCode(type) switch { TypeCode.Boolean => false, TypeCode.Byte => (byte)0, TypeCode.Int16 => (short)0, TypeCode.Int32 => 0, TypeCode.Int64 => 0L, TypeCode.SByte => (sbyte)0, TypeCode.UInt16 => (ushort)0, TypeCode.UInt32 => 0u, TypeCode.UInt64 => 0uL, TypeCode.Single => 0f, TypeCode.Double => 0.0, TypeCode.Decimal => 0m, TypeCode.Char => '\0', TypeCode.DateTime => default(DateTime), _ => null, }; } public bool GetDictionary(IObjectDescriptor descriptor, out IDictionary? dictionary, out Type[]? genericArguments) { dictionary = null; genericArguments = null; return false; } } } namespace YamlDotNet.Serialization.NodeTypeResolvers { internal sealed class DefaultContainersNodeTypeResolver : INodeTypeResolver { bool INodeTypeResolver.Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (currentType == typeof(object)) { if (nodeEvent is SequenceStart) { currentType = typeof(List); return true; } if (nodeEvent is MappingStart) { currentType = typeof(Dictionary); return true; } } return false; } } internal class MappingNodeTypeResolver : INodeTypeResolver { private readonly IDictionary _mappings; public MappingNodeTypeResolver(IDictionary mappings) { if (mappings == null) { throw new ArgumentNullException("mappings"); } foreach (KeyValuePair mapping in mappings) { if (!mapping.Key.IsAssignableFrom(mapping.Value)) { throw new InvalidOperationException($"Type '{mapping.Value}' does not implement type '{mapping.Key}'."); } } _mappings = mappings; } public bool Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (_mappings.TryGetValue(currentType, out Type value)) { currentType = value; return true; } return false; } } internal class PreventUnknownTagsNodeTypeResolver : INodeTypeResolver { bool INodeTypeResolver.Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty) { Mark start = nodeEvent.Start; Mark end = nodeEvent.End; throw new YamlException(in start, in end, $"Encountered an unresolved tag '{nodeEvent.Tag}'"); } return false; } } internal sealed class TagNodeTypeResolver : INodeTypeResolver { private readonly IDictionary tagMappings; public TagNodeTypeResolver(IDictionary tagMappings) { this.tagMappings = tagMappings ?? throw new ArgumentNullException("tagMappings"); } bool INodeTypeResolver.Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty && tagMappings.TryGetValue(nodeEvent.Tag, out Type value)) { currentType = value; return true; } return false; } } [Obsolete("The mechanism that this class uses to specify type names is non-standard. Register the tags explicitly instead of using this convention.")] internal sealed class TypeNameInTagNodeTypeResolver : INodeTypeResolver { bool INodeTypeResolver.Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty) { Type type = Type.GetType(nodeEvent.Tag.Value.Substring(1), throwOnError: false); if (type != null) { currentType = type; return true; } } return false; } } internal sealed class YamlConvertibleTypeResolver : INodeTypeResolver { public bool Resolve(NodeEvent? nodeEvent, ref Type currentType) { return typeof(IYamlConvertible).IsAssignableFrom(currentType); } } internal sealed class YamlSerializableTypeResolver : INodeTypeResolver { public bool Resolve(NodeEvent? nodeEvent, ref Type currentType) { return typeof(IYamlSerializable).IsAssignableFrom(currentType); } } } namespace YamlDotNet.Serialization.NodeDeserializers { internal sealed class ArrayNodeDeserializer : INodeDeserializer { private sealed class ArrayList : IList, ICollection, IEnumerable { private object?[] data; public bool IsFixedSize => false; public bool IsReadOnly => false; public object? this[int index] { get { return data[index]; } set { data[index] = value; } } public int Count { get; private set; } public bool IsSynchronized => false; public object SyncRoot => data; public ArrayList() { Clear(); } public int Add(object? value) { if (Count == data.Length) { Array.Resize(ref data, data.Length * 2); } data[Count] = value; return Count++; } public void Clear() { data = new object[10]; Count = 0; } bool IList.Contains(object? value) { throw new NotSupportedException(); } int IList.IndexOf(object? value) { throw new NotSupportedException(); } void IList.Insert(int index, object? value) { throw new NotSupportedException(); } void IList.Remove(object? value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } public void CopyTo(Array array, int index) { Array.Copy(data, 0, array, index, Count); } public IEnumerator GetEnumerator() { int i = 0; while (i < Count) { yield return data[i]; int num = i + 1; i = num; } } } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (!expectedType.IsArray) { value = false; return false; } Type? elementType = expectedType.GetElementType(); ArrayList arrayList = new ArrayList(); CollectionNodeDeserializer.DeserializeHelper(elementType, parser, nestedObjectDeserializer, arrayList, canUpdate: true); Array array = Array.CreateInstance(elementType, arrayList.Count); arrayList.CopyTo(array, 0); value = array; return true; } } internal abstract class CollectionDeserializer { protected static void DeserializeHelper(Type tItem, IParser parser, Func nestedObjectDeserializer, IList result, bool canUpdate, IObjectFactory objectFactory) { IList result2 = result; parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { ParsingEvent current = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise valuePromise) { if (!canUpdate) { Mark start = current?.Start ?? Mark.Empty; Mark end = current?.End ?? Mark.Empty; throw new ForwardAnchorNotSupportedException(in start, in end, "Forward alias references are not allowed because this type does not implement IList<>"); } int index = result2.Add(objectFactory.CreatePrimitive(tItem)); valuePromise.ValueAvailable += delegate(object? v) { result2[index] = v; }; } else { result2.Add(obj); } } } } internal sealed class CollectionNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public CollectionNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { bool canUpdate = true; Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(ICollection<>)); Type type; IList list; if (implementedGenericInterface != null) { type = implementedGenericInterface.GetGenericArguments()[0]; value = objectFactory.Create(expectedType); list = value as IList; if (list == null) { canUpdate = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IList<>)) != null; list = (IList)Activator.CreateInstance(typeof(GenericCollectionToNonGenericAdapter<>).MakeGenericType(type), value); } } else { if (!typeof(IList).IsAssignableFrom(expectedType)) { value = null; return false; } type = typeof(object); value = objectFactory.Create(expectedType); list = (IList)value; } DeserializeHelper(type, parser, nestedObjectDeserializer, list, canUpdate); return true; } internal static void DeserializeHelper(Type tItem, IParser parser, Func nestedObjectDeserializer, IList result, bool canUpdate) { IList result2 = result; Type tItem2 = tItem; parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { ParsingEvent current = parser.Current; object obj = nestedObjectDeserializer(parser, tItem2); if (obj is IValuePromise valuePromise) { if (!canUpdate) { Mark start = current?.Start ?? Mark.Empty; Mark end = current?.End ?? Mark.Empty; throw new ForwardAnchorNotSupportedException(in start, in end, "Forward alias references are not allowed because this type does not implement IList<>"); } int index = result2.Add(tItem2.IsValueType() ? Activator.CreateInstance(tItem2) : null); valuePromise.ValueAvailable += delegate(object? v) { result2[index] = YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(v, tItem2); }; } else { result2.Add(YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(obj, tItem2)); } } } } internal abstract class DictionaryDeserializer { private readonly bool duplicateKeyChecking; public DictionaryDeserializer(bool duplicateKeyChecking) { this.duplicateKeyChecking = duplicateKeyChecking; } private void TryAssign(IDictionary result, object key, object value, MappingStart propertyName) { if (duplicateKeyChecking && result.Contains(key)) { Mark start = propertyName.Start; Mark end = propertyName.End; throw new YamlException(in start, in end, $"Encountered duplicate key {key}"); } result[key] = value; } protected virtual void Deserialize(Type tKey, Type tValue, IParser parser, Func nestedObjectDeserializer, IDictionary result) { IDictionary result2 = result; MappingStart property = parser.Consume(); MappingEnd @event; while (!parser.TryConsume(out @event)) { object key = nestedObjectDeserializer(parser, tKey); object value = nestedObjectDeserializer(parser, tValue); IValuePromise valuePromise = value as IValuePromise; if (key is IValuePromise valuePromise2) { if (valuePromise == null) { valuePromise2.ValueAvailable += delegate(object? v) { result2[v] = value; }; continue; } bool hasFirstPart = false; valuePromise2.ValueAvailable += delegate(object? v) { if (hasFirstPart) { TryAssign(result2, v, value, property); } else { key = v; hasFirstPart = true; } }; valuePromise.ValueAvailable += delegate(object? v) { if (hasFirstPart) { TryAssign(result2, key, v, property); } else { value = v; hasFirstPart = true; } }; continue; } if (key == null) { throw new ArgumentException("Empty key names are not supported yet.", "key"); } if (valuePromise == null) { TryAssign(result2, key, value, property); continue; } valuePromise.ValueAvailable += delegate(object? v) { result2[key] = v; }; } } } internal class DictionaryNodeDeserializer : DictionaryDeserializer, INodeDeserializer { private readonly IObjectFactory objectFactory; public DictionaryNodeDeserializer(IObjectFactory objectFactory, bool duplicateKeyChecking) : base(duplicateKeyChecking) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IDictionary<, >)); Type type; Type type2; IDictionary dictionary; if (implementedGenericInterface != null) { Type[] genericArguments = implementedGenericInterface.GetGenericArguments(); type = genericArguments[0]; type2 = genericArguments[1]; value = objectFactory.Create(expectedType); dictionary = value as IDictionary; if (dictionary == null) { dictionary = (IDictionary)Activator.CreateInstance(typeof(GenericDictionaryToNonGenericAdapter<, >).MakeGenericType(type, type2), value); } } else { if (!typeof(IDictionary).IsAssignableFrom(expectedType)) { value = null; return false; } type = typeof(object); type2 = typeof(object); value = objectFactory.Create(expectedType); dictionary = (IDictionary)value; } Deserialize(type, type2, parser, nestedObjectDeserializer, dictionary); return true; } } internal sealed class EnumerableNodeDeserializer : INodeDeserializer { public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { Type type; if (expectedType == typeof(IEnumerable)) { type = typeof(object); } else { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IEnumerable<>)); if (implementedGenericInterface != expectedType) { value = null; return false; } type = implementedGenericInterface.GetGenericArguments()[0]; } Type arg = typeof(List<>).MakeGenericType(type); value = nestedObjectDeserializer(parser, arg); return true; } } internal sealed class NullNodeDeserializer : INodeDeserializer { public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { value = null; if (parser.Accept(out var @event) && NodeIsNull(@event)) { parser.SkipThisAndNestedEvents(); return true; } return false; } private bool NodeIsNull(NodeEvent nodeEvent) { if (nodeEvent.Tag == "tag:yaml.org,2002:null") { return true; } if (nodeEvent is YamlDotNet.Core.Events.Scalar scalar && scalar.Style == ScalarStyle.Plain && !scalar.IsKey) { string value = scalar.Value; switch (value) { default: return value == "NULL"; case "": case "~": case "null": case "Null": return true; } } return false; } } internal sealed class ObjectNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; private readonly ITypeInspector typeDescriptor; private readonly bool ignoreUnmatched; private readonly bool duplicateKeyChecking; private readonly ITypeConverter typeConverter; public ObjectNodeDeserializer(IObjectFactory objectFactory, ITypeInspector typeDescriptor, bool ignoreUnmatched, bool duplicateKeyChecking, ITypeConverter typeConverter) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); this.typeDescriptor = typeDescriptor ?? throw new ArgumentNullException("typeDescriptor"); this.ignoreUnmatched = ignoreUnmatched; this.duplicateKeyChecking = duplicateKeyChecking; this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (!parser.TryConsume(out var _)) { value = null; return false; } Type type = Nullable.GetUnderlyingType(expectedType) ?? expectedType; value = objectFactory.Create(type); HashSet hashSet = new HashSet(StringComparer.Ordinal); MappingEnd event2; while (!parser.TryConsume(out event2)) { YamlDotNet.Core.Events.Scalar scalar = parser.Consume(); if (duplicateKeyChecking && !hashSet.Add(scalar.Value)) { Mark start = scalar.Start; Mark end = scalar.End; throw new YamlException(in start, in end, "Encountered duplicate key " + scalar.Value); } try { IPropertyDescriptor property = typeDescriptor.GetProperty(type, null, scalar.Value, ignoreUnmatched); if (property == null) { parser.SkipThisAndNestedEvents(); continue; } object obj = nestedObjectDeserializer(parser, property.Type); if (obj is IValuePromise valuePromise) { object valueRef = value; valuePromise.ValueAvailable += delegate(object? v) { object value3 = typeConverter.ChangeType(v, property.Type); property.Write(valueRef, value3); }; } else { object value2 = typeConverter.ChangeType(obj, property.Type); property.Write(value, value2); } } catch (SerializationException ex) { Mark start = scalar.Start; Mark end = scalar.End; throw new YamlException(in start, in end, ex.Message); } catch (YamlException) { throw; } catch (Exception innerException) { Mark start = scalar.Start; Mark end = scalar.End; throw new YamlException(in start, in end, "Exception during deserialization", innerException); } } return true; } } internal sealed class ScalarNodeDeserializer : INodeDeserializer { private const string BooleanTruePattern = "^(true|y|yes|on)$"; private const string BooleanFalsePattern = "^(false|n|no|off)$"; private readonly bool attemptUnknownTypeDeserialization; private readonly ITypeConverter typeConverter; public ScalarNodeDeserializer(bool attemptUnknownTypeDeserialization, ITypeConverter typeConverter) { this.attemptUnknownTypeDeserialization = attemptUnknownTypeDeserialization; this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (!parser.TryConsume(out var @event)) { value = null; return false; } Type type = Nullable.GetUnderlyingType(expectedType) ?? expectedType; if (type.IsEnum()) { value = Enum.Parse(type, @event.Value, ignoreCase: true); return true; } TypeCode typeCode = type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: value = DeserializeBooleanHelper(@event.Value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: value = DeserializeIntegerHelper(typeCode, @event.Value); break; case TypeCode.Single: value = float.Parse(@event.Value, YamlFormatter.NumberFormat); break; case TypeCode.Double: value = double.Parse(@event.Value, YamlFormatter.NumberFormat); break; case TypeCode.Decimal: value = decimal.Parse(@event.Value, YamlFormatter.NumberFormat); break; case TypeCode.String: value = @event.Value; break; case TypeCode.Char: value = @event.Value[0]; break; case TypeCode.DateTime: value = DateTime.Parse(@event.Value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); break; default: if (expectedType == typeof(object)) { if (!@event.IsKey && attemptUnknownTypeDeserialization) { value = AttemptUnknownTypeDeserialization(@event); } else { value = @event.Value; } } else { value = typeConverter.ChangeType(@event.Value, expectedType); } break; } return true; } private object DeserializeBooleanHelper(string value) { bool flag; if (Regex.IsMatch(value, "^(true|y|yes|on)$", RegexOptions.IgnoreCase)) { flag = true; } else { if (!Regex.IsMatch(value, "^(false|n|no|off)$", RegexOptions.IgnoreCase)) { throw new FormatException("The value \"" + value + "\" is not a valid YAML Boolean"); } flag = false; } return flag; } private static object DeserializeIntegerHelper(TypeCode typeCode, string value) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; int i = 0; bool flag = false; ulong num = 0uL; if (value[0] == '-') { i++; flag = true; } else if (value[0] == '+') { i++; } if (value[i] == '0') { int num2; if (i == value.Length - 1) { num2 = 10; num = 0uL; } else { i++; if (value[i] == 'b') { num2 = 2; i++; } else if (value[i] == 'x') { num2 = 16; i++; } else { num2 = 8; } } for (; i < value.Length; i++) { if (value[i] != '_') { builder.Append(value[i]); } } switch (num2) { case 2: case 8: num = Convert.ToUInt64(builder.ToString(), num2); break; case 16: num = ulong.Parse(builder.ToString(), NumberStyles.HexNumber, YamlFormatter.NumberFormat); break; } } else { string[] array = value.Substring(i).Split(new char[1] { ':' }); num = 0uL; for (int j = 0; j < array.Length; j++) { num *= 60; num += ulong.Parse(array[j].Replace("_", "")); } } if (!flag) { return CastInteger(num, typeCode); } long number = ((num != 9223372036854775808uL) ? checked(-(long)num) : long.MinValue); return CastInteger(number, typeCode); } finally { ((IDisposable)builderWrapper).Dispose(); } } private static object CastInteger(long number, TypeCode typeCode) { return checked(typeCode switch { TypeCode.Byte => (byte)number, TypeCode.Int16 => (short)number, TypeCode.Int32 => (int)number, TypeCode.Int64 => number, TypeCode.SByte => (sbyte)number, TypeCode.UInt16 => (ushort)number, TypeCode.UInt32 => (uint)number, TypeCode.UInt64 => (ulong)number, _ => number, }); } private static object CastInteger(ulong number, TypeCode typeCode) { return checked(typeCode switch { TypeCode.Byte => (byte)number, TypeCode.Int16 => (short)number, TypeCode.Int32 => (int)number, TypeCode.Int64 => (long)number, TypeCode.SByte => (sbyte)number, TypeCode.UInt16 => (ushort)number, TypeCode.UInt32 => (uint)number, TypeCode.UInt64 => number, _ => number, }); } private static object? AttemptUnknownTypeDeserialization(YamlDotNet.Core.Events.Scalar value) { if (value.Style == ScalarStyle.SingleQuoted || value.Style == ScalarStyle.DoubleQuoted || value.Style == ScalarStyle.Folded) { return value.Value; } string v = value.Value; switch (v) { case "": case "~": case "null": case "Null": case "NULL": return null; case "true": case "True": case "TRUE": return true; case "false": case "False": case "FALSE": return false; default: { object value2; if (Regex.IsMatch(v, "0x[0-9a-fA-F]+")) { if (!TryAndSwallow(() => Convert.ToByte(v, 16), out value2) && !TryAndSwallow(() => Convert.ToInt16(v, 16), out value2) && !TryAndSwallow(() => Convert.ToInt32(v, 16), out value2) && !TryAndSwallow(() => Convert.ToInt64(v, 16), out value2) && !TryAndSwallow(() => Convert.ToUInt64(v, 16), out value2)) { return v; } } else if (Regex.IsMatch(v, "0o[0-9a-fA-F]+")) { if (!TryAndSwallow(() => Convert.ToByte(v, 8), out value2) && !TryAndSwallow(() => Convert.ToInt16(v, 8), out value2) && !TryAndSwallow(() => Convert.ToInt32(v, 8), out value2) && !TryAndSwallow(() => Convert.ToInt64(v, 8), out value2) && !TryAndSwallow(() => Convert.ToUInt64(v, 8), out value2)) { return v; } } else { if (!Regex.IsMatch(v, "[-+]?(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?")) { if (Regex.IsMatch(v, "^[-+]?(\\.inf|\\.Inf|\\.INF)$")) { if (v.StartsWith("-")) { return float.NegativeInfinity; } return float.PositiveInfinity; } if (Regex.IsMatch(v, "^(\\.nan|\\.NaN|\\.NAN)$")) { return float.NaN; } return v; } if (!TryAndSwallow(() => byte.Parse(v), out value2) && !TryAndSwallow(() => short.Parse(v), out value2) && !TryAndSwallow(() => int.Parse(v), out value2) && !TryAndSwallow(() => long.Parse(v), out value2) && !TryAndSwallow(() => ulong.Parse(v), out value2) && !TryAndSwallow(() => float.Parse(v), out value2) && !TryAndSwallow(() => double.Parse(v), out value2)) { return v; } } return value2; } } } private static bool TryAndSwallow(Func attempt, out object? value) { try { value = attempt(); return true; } catch { value = null; return false; } } } internal sealed class StaticArrayNodeDeserializer : INodeDeserializer { private sealed class ArrayList : IList, ICollection, IEnumerable { private object?[] data; public bool IsFixedSize => false; public bool IsReadOnly => false; public object? this[int index] { get { return data[index]; } set { data[index] = value; } } public int Count { get; private set; } public bool IsSynchronized => false; public object SyncRoot => data; public ArrayList() { Clear(); } public int Add(object? value) { if (Count == data.Length) { Array.Resize(ref data, data.Length * 2); } data[Count] = value; return Count++; } public void Clear() { data = new object[10]; Count = 0; } bool IList.Contains(object? value) { throw new NotSupportedException(); } int IList.IndexOf(object? value) { throw new NotSupportedException(); } void IList.Insert(int index, object? value) { throw new NotSupportedException(); } void IList.Remove(object? value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } public void CopyTo(Array array, int index) { Array.Copy(data, 0, array, index, Count); } public IEnumerator GetEnumerator() { int i = 0; while (i < Count) { yield return data[i]; int num = i + 1; i = num; } } } private readonly StaticObjectFactory factory; public StaticArrayNodeDeserializer(StaticObjectFactory factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (!factory.IsArray(expectedType)) { value = false; return false; } Type valueType = factory.GetValueType(expectedType); ArrayList arrayList = new ArrayList(); StaticCollectionNodeDeserializer.DeserializeHelper(valueType, parser, nestedObjectDeserializer, arrayList, factory); Array array = factory.CreateArray(expectedType, arrayList.Count); arrayList.CopyTo(array, 0); value = array; return true; } } internal sealed class StaticCollectionNodeDeserializer : INodeDeserializer { private readonly StaticObjectFactory factory; public StaticCollectionNodeDeserializer(StaticObjectFactory factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (!factory.IsList(expectedType)) { value = null; return false; } DeserializeHelper(result: (IList)(value = factory.Create(expectedType) as IList), tItem: factory.GetValueType(expectedType), parser: parser, nestedObjectDeserializer: nestedObjectDeserializer, factory: factory); return true; } internal static void DeserializeHelper(Type tItem, IParser parser, Func nestedObjectDeserializer, IList result, IObjectFactory factory) { IList result2 = result; parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { _ = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise valuePromise) { int index = result2.Add(factory.CreatePrimitive(tItem)); valuePromise.ValueAvailable += delegate(object? v) { result2[index] = v; }; } else { result2.Add(obj); } } } } internal class StaticDictionaryNodeDeserializer : DictionaryDeserializer, INodeDeserializer { private readonly StaticObjectFactory _objectFactory; public StaticDictionaryNodeDeserializer(StaticObjectFactory objectFactory, bool duplicateKeyChecking) : base(duplicateKeyChecking) { _objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } public bool Deserialize(IParser reader, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (_objectFactory.IsDictionary(expectedType)) { if (!(_objectFactory.Create(expectedType) is IDictionary dictionary)) { value = null; return false; } Type keyType = _objectFactory.GetKeyType(expectedType); Type valueType = _objectFactory.GetValueType(expectedType); value = dictionary; base.Deserialize(keyType, valueType, reader, nestedObjectDeserializer, dictionary); return true; } value = null; return false; } } internal sealed class TypeConverterNodeDeserializer : INodeDeserializer { private readonly IEnumerable converters; public TypeConverterNodeDeserializer(IEnumerable converters) { this.converters = converters ?? throw new ArgumentNullException("converters"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { Type expectedType2 = expectedType; IYamlTypeConverter yamlTypeConverter = converters.FirstOrDefault((IYamlTypeConverter c) => c.Accepts(expectedType2)); if (yamlTypeConverter == null) { value = null; return false; } value = yamlTypeConverter.ReadYaml(parser, expectedType2); return true; } } internal sealed class YamlConvertibleNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public YamlConvertibleNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory; } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { Func nestedObjectDeserializer2 = nestedObjectDeserializer; IParser parser2 = parser; if (typeof(IYamlConvertible).IsAssignableFrom(expectedType)) { IYamlConvertible yamlConvertible = (IYamlConvertible)objectFactory.Create(expectedType); yamlConvertible.Read(parser2, expectedType, (Type type) => nestedObjectDeserializer2(parser2, type)); value = yamlConvertible; return true; } value = null; return false; } } internal sealed class YamlSerializableNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public YamlSerializableNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory; } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (typeof(IYamlSerializable).IsAssignableFrom(expectedType)) { IYamlSerializable yamlSerializable = (IYamlSerializable)objectFactory.Create(expectedType); yamlSerializable.ReadYaml(parser); value = yamlSerializable; return true; } value = null; return false; } } } namespace YamlDotNet.Serialization.NamingConventions { internal sealed class CamelCaseNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new CamelCaseNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public CamelCaseNamingConvention() { } public string Apply(string value) { return value.ToCamelCase(); } } internal sealed class HyphenatedNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new HyphenatedNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public HyphenatedNamingConvention() { } public string Apply(string value) { return value.FromCamelCase("-"); } } internal sealed class LowerCaseNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new LowerCaseNamingConvention(); private LowerCaseNamingConvention() { } public string Apply(string value) { return value.ToCamelCase().ToLower(); } } internal sealed class NullNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new NullNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public NullNamingConvention() { } public string Apply(string value) { return value; } } internal sealed class PascalCaseNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new PascalCaseNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public PascalCaseNamingConvention() { } public string Apply(string value) { return value.ToPascalCase(); } } internal sealed class UnderscoredNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new UnderscoredNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public UnderscoredNamingConvention() { } public string Apply(string value) { return value.FromCamelCase("_"); } } } namespace YamlDotNet.Serialization.EventEmitters { internal abstract class ChainedEventEmitter : IEventEmitter { protected readonly IEventEmitter nextEmitter; protected ChainedEventEmitter(IEventEmitter nextEmitter) { this.nextEmitter = nextEmitter ?? throw new ArgumentNullException("nextEmitter"); } public virtual void Emit(AliasEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(MappingEndEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } } internal sealed class JsonEventEmitter : ChainedEventEmitter { public JsonEventEmitter(IEventEmitter nextEmitter) : base(nextEmitter) { } public override void Emit(AliasEventInfo eventInfo, IEmitter emitter) { eventInfo.NeedsExpansion = true; } public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { eventInfo.IsPlainImplicit = true; eventInfo.Style = ScalarStyle.Plain; object value = eventInfo.Source.Value; if (value == null) { eventInfo.RenderedValue = "null"; } else { TypeCode typeCode = eventInfo.Source.Type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: eventInfo.RenderedValue = YamlFormatter.FormatBoolean(value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: if (eventInfo.Source.Type.IsEnum()) { eventInfo.RenderedValue = value.ToString(); eventInfo.Style = ScalarStyle.DoubleQuoted; } else { eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); } break; case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); break; case TypeCode.Char: case TypeCode.String: eventInfo.RenderedValue = value.ToString(); eventInfo.Style = ScalarStyle.DoubleQuoted; break; case TypeCode.DateTime: eventInfo.RenderedValue = YamlFormatter.FormatDateTime(value); break; case TypeCode.Empty: eventInfo.RenderedValue = "null"; break; default: if (eventInfo.Source.Type == typeof(TimeSpan)) { eventInfo.RenderedValue = YamlFormatter.FormatTimeSpan(value); break; } throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } } base.Emit(eventInfo, emitter); } public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { eventInfo.Style = MappingStyle.Flow; base.Emit(eventInfo, emitter); } public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { eventInfo.Style = SequenceStyle.Flow; base.Emit(eventInfo, emitter); } } internal sealed class TypeAssigningEventEmitter : ChainedEventEmitter { private readonly bool requireTagWhenStaticAndActualTypesAreDifferent; private readonly IDictionary tagMappings; private readonly bool quoteNecessaryStrings; private readonly Regex? isSpecialStringValue_Regex; private static readonly string SpecialStrings_Pattern = "^(null|Null|NULL|\\~|true|True|TRUE|false|False|FALSE|[-+]?[0-9]+|0o[0-7]+|0x[0-9a-fA-F]+|[-+]?(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?|[-+]?(\\.inf|\\.Inf|\\.INF)|\\.nan|\\.NaN|\\.NAN)$"; private static readonly string CombinedYaml1_1SpecialStrings_Pattern = "^(null|Null|NULL|\\~|true|True|TRUE|false|False|FALSE|y|Y|yes|Yes|YES|n|N|no|No|NO|on|On|ON|off|Off|OFF|[-+]?0b[0-1_]+|[-+]?0o?[0-7_]+|[-+]?(0|[1-9][0-9_]*)|[-+]?0x[0-9a-fA-F_]+|[-+]?[1-9][0-9_]*(:[0-5]?[0-9])+|[-+]?([0-9][0-9_]*)?\\.[0-9_]*([eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(inf|Inf|INF)|\\.(nan|NaN|NAN))$"; public TypeAssigningEventEmitter(IEventEmitter nextEmitter, bool requireTagWhenStaticAndActualTypesAreDifferent, IDictionary tagMappings, bool quoteNecessaryStrings, bool quoteYaml1_1Strings) : this(nextEmitter, requireTagWhenStaticAndActualTypesAreDifferent, tagMappings) { this.quoteNecessaryStrings = quoteNecessaryStrings; isSpecialStringValue_Regex = new Regex(quoteYaml1_1Strings ? CombinedYaml1_1SpecialStrings_Pattern : SpecialStrings_Pattern, RegexOptions.Compiled); } public TypeAssigningEventEmitter(IEventEmitter nextEmitter, bool requireTagWhenStaticAndActualTypesAreDifferent, IDictionary tagMappings, bool quoteNecessaryStrings) : this(nextEmitter, requireTagWhenStaticAndActualTypesAreDifferent, tagMappings) { this.quoteNecessaryStrings = quoteNecessaryStrings; isSpecialStringValue_Regex = new Regex(SpecialStrings_Pattern, RegexOptions.Compiled); } public TypeAssigningEventEmitter(IEventEmitter nextEmitter, bool requireTagWhenStaticAndActualTypesAreDifferent, IDictionary tagMappings) : base(nextEmitter) { this.requireTagWhenStaticAndActualTypesAreDifferent = requireTagWhenStaticAndActualTypesAreDifferent; this.tagMappings = tagMappings ?? throw new ArgumentNullException("tagMappings"); } public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { ScalarStyle style = ScalarStyle.Plain; object value = eventInfo.Source.Value; if (value == null) { eventInfo.Tag = JsonSchema.Tags.Null; eventInfo.RenderedValue = ""; } else { TypeCode typeCode = eventInfo.Source.Type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: eventInfo.Tag = JsonSchema.Tags.Bool; eventInfo.RenderedValue = YamlFormatter.FormatBoolean(value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: if (eventInfo.Source.Type.IsEnum) { eventInfo.Tag = FailsafeSchema.Tags.Str; eventInfo.RenderedValue = value.ToString(); style = ((quoteNecessaryStrings && IsSpecialStringValue(eventInfo.RenderedValue)) ? ScalarStyle.DoubleQuoted : ScalarStyle.Any); } else { eventInfo.Tag = JsonSchema.Tags.Int; eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); } break; case TypeCode.Single: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = YamlFormatter.FormatNumber((float)value); break; case TypeCode.Double: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = YamlFormatter.FormatNumber((double)value); break; case TypeCode.Decimal: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); break; case TypeCode.Char: case TypeCode.String: eventInfo.Tag = FailsafeSchema.Tags.Str; eventInfo.RenderedValue = value.ToString(); style = ((quoteNecessaryStrings && IsSpecialStringValue(eventInfo.RenderedValue)) ? ScalarStyle.DoubleQuoted : ScalarStyle.Any); break; case TypeCode.DateTime: eventInfo.Tag = DefaultSchema.Tags.Timestamp; eventInfo.RenderedValue = YamlFormatter.FormatDateTime(value); break; case TypeCode.Empty: eventInfo.Tag = JsonSchema.Tags.Null; eventInfo.RenderedValue = ""; break; default: if (eventInfo.Source.Type == typeof(TimeSpan)) { eventInfo.RenderedValue = YamlFormatter.FormatTimeSpan(value); break; } throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } } eventInfo.IsPlainImplicit = true; if (eventInfo.Style == ScalarStyle.Any) { eventInfo.Style = style; } base.Emit(eventInfo, emitter); } public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { AssignTypeIfNeeded(eventInfo); base.Emit(eventInfo, emitter); } public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { AssignTypeIfNeeded(eventInfo); base.Emit(eventInfo, emitter); } private void AssignTypeIfNeeded(ObjectEventInfo eventInfo) { if (tagMappings.TryGetValue(eventInfo.Source.Type, out var value)) { eventInfo.Tag = value; } else if (requireTagWhenStaticAndActualTypesAreDifferent && eventInfo.Source.Value != null && eventInfo.Source.Type != eventInfo.Source.StaticType) { throw new YamlException("Cannot serialize type '" + eventInfo.Source.Type.FullName + "' where a '" + eventInfo.Source.StaticType.FullName + "' was expected because no tag mapping has been registered for '" + eventInfo.Source.Type.FullName + "', which means that it won't be possible to deserialize the document.\nRegister a tag mapping using the SerializerBuilder.WithTagMapping method.\n\nE.g: builder.WithTagMapping(\"!" + eventInfo.Source.Type.Name + "\", typeof(" + eventInfo.Source.Type.FullName + "));"); } } private bool IsSpecialStringValue(string value) { if (value.Trim() == string.Empty) { return true; } return isSpecialStringValue_Regex?.IsMatch(value) ?? false; } } internal sealed class WriterEventEmitter : IEventEmitter { void IEventEmitter.Emit(AliasEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new YamlDotNet.Core.Events.AnchorAlias(eventInfo.Alias)); } void IEventEmitter.Emit(ScalarEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new YamlDotNet.Core.Events.Scalar(eventInfo.Anchor, eventInfo.Tag, eventInfo.RenderedValue, eventInfo.Style, eventInfo.IsPlainImplicit, eventInfo.IsQuotedImplicit)); } void IEventEmitter.Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new MappingStart(eventInfo.Anchor, eventInfo.Tag, eventInfo.IsImplicit, eventInfo.Style)); } void IEventEmitter.Emit(MappingEndEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new MappingEnd()); } void IEventEmitter.Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new SequenceStart(eventInfo.Anchor, eventInfo.Tag, eventInfo.IsImplicit, eventInfo.Style)); } void IEventEmitter.Emit(SequenceEndEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new SequenceEnd()); } } } namespace YamlDotNet.Serialization.Converters { internal class DateTimeConverter : IYamlTypeConverter { private readonly DateTimeKind kind; private readonly IFormatProvider provider; private readonly bool doubleQuotes; private readonly string[] formats; public DateTimeConverter(DateTimeKind kind = DateTimeKind.Utc, IFormatProvider? provider = null, bool doubleQuotes = false, params string[] formats) { this.kind = ((kind == DateTimeKind.Unspecified) ? DateTimeKind.Utc : kind); this.provider = provider ?? CultureInfo.InvariantCulture; this.doubleQuotes = doubleQuotes; this.formats = formats.DefaultIfEmpty("G").ToArray(); } public bool Accepts(Type type) { return type == typeof(DateTime); } public object ReadYaml(IParser parser, Type type) { return EnsureDateTimeKind(DateTime.ParseExact(parser.Consume().Value, style: (kind == DateTimeKind.Local) ? DateTimeStyles.AssumeLocal : DateTimeStyles.AssumeUniversal, formats: formats, provider: provider), kind); } public void WriteYaml(IEmitter emitter, object? value, Type type) { DateTime dateTime = (DateTime)value; string value2 = ((kind == DateTimeKind.Local) ? dateTime.ToLocalTime() : dateTime.ToUniversalTime()).ToString(formats.First(), provider); emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, value2, doubleQuotes ? ScalarStyle.DoubleQuoted : ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } private static DateTime EnsureDateTimeKind(DateTime dt, DateTimeKind kind) { if (dt.Kind == DateTimeKind.Local && kind == DateTimeKind.Utc) { return dt.ToUniversalTime(); } if (dt.Kind == DateTimeKind.Utc && kind == DateTimeKind.Local) { return dt.ToLocalTime(); } return dt; } } internal class GuidConverter : IYamlTypeConverter { private readonly bool jsonCompatible; public GuidConverter(bool jsonCompatible) { this.jsonCompatible = jsonCompatible; } public bool Accepts(Type type) { return type == typeof(Guid); } public object ReadYaml(IParser parser, Type type) { return new Guid(parser.Consume().Value); } public void WriteYaml(IEmitter emitter, object? value, Type type) { Guid guid = (Guid)value; emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, guid.ToString("D"), jsonCompatible ? ScalarStyle.DoubleQuoted : ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } } internal class SystemTypeConverter : IYamlTypeConverter { public bool Accepts(Type type) { return typeof(Type).IsAssignableFrom(type); } public object ReadYaml(IParser parser, Type type) { return Type.GetType(parser.Consume().Value, throwOnError: true); } public void WriteYaml(IEmitter emitter, object? value, Type type) { Type type2 = (Type)value; emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, type2.AssemblyQualifiedName, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } } } namespace YamlDotNet.Serialization.BufferedDeserialization { internal interface ITypeDiscriminatingNodeDeserializerOptions { void AddTypeDiscriminator(ITypeDiscriminator discriminator); void AddKeyValueTypeDiscriminator(string discriminatorKey, IDictionary valueTypeMapping); void AddUniqueKeyTypeDiscriminator(IDictionary uniqueKeyTypeMapping); } internal class ParserBuffer : IParser { private readonly LinkedList buffer; private LinkedListNode? current; public ParsingEvent? Current => current?.Value; public ParserBuffer(IParser parserToBuffer, int maxDepth, int maxLength) { buffer = new LinkedList(); buffer.AddLast(parserToBuffer.Consume()); int num = 0; do { ParsingEvent parsingEvent = parserToBuffer.Consume(); num += parsingEvent.NestingIncrease; buffer.AddLast(parsingEvent); if (maxDepth > -1 && num > maxDepth) { throw new ArgumentOutOfRangeException("parserToBuffer", "Parser buffer exceeded max depth"); } if (maxLength > -1 && buffer.Count > maxLength) { throw new ArgumentOutOfRangeException("parserToBuffer", "Parser buffer exceeded max length"); } } while (num >= 0); current = buffer.First; } public bool MoveNext() { current = current?.Next; return current != null; } public void Reset() { current = buffer.First; } } internal class TypeDiscriminatingNodeDeserializer : INodeDeserializer { private readonly IList innerDeserializers; private readonly IList typeDiscriminators; private readonly int maxDepthToBuffer; private readonly int maxLengthToBuffer; public TypeDiscriminatingNodeDeserializer(IList innerDeserializers, IList typeDiscriminators, int maxDepthToBuffer, int maxLengthToBuffer) { this.innerDeserializers = innerDeserializers; this.typeDiscriminators = typeDiscriminators; this.maxDepthToBuffer = maxDepthToBuffer; this.maxLengthToBuffer = maxLengthToBuffer; } public bool Deserialize(IParser reader, Type expectedType, Func nestedObjectDeserializer, out object? value) { Type expectedType2 = expectedType; if (!reader.Accept(out var _)) { value = null; return false; } IEnumerable enumerable = typeDiscriminators.Where((ITypeDiscriminator t) => t.BaseType.IsAssignableFrom(expectedType2)); if (!enumerable.Any()) { value = null; return false; } Mark start = reader.Current.Start; Type expectedType3 = expectedType2; ParserBuffer parserBuffer; try { parserBuffer = new ParserBuffer(reader, maxDepthToBuffer, maxLengthToBuffer); } catch (Exception innerException) { Mark end = reader.Current.End; throw new YamlException(in start, in end, "Failed to buffer yaml node", innerException); } try { foreach (ITypeDiscriminator item in enumerable) { parserBuffer.Reset(); if (item.TryDiscriminate(parserBuffer, out Type suggestedType)) { expectedType3 = suggestedType; break; } } } catch (Exception innerException2) { Mark end = reader.Current.End; throw new YamlException(in start, in end, "Failed to discriminate type", innerException2); } parserBuffer.Reset(); foreach (INodeDeserializer innerDeserializer in innerDeserializers) { if (innerDeserializer.Deserialize(parserBuffer, expectedType3, nestedObjectDeserializer, out value)) { return true; } } value = null; return false; } } internal class TypeDiscriminatingNodeDeserializerOptions : ITypeDiscriminatingNodeDeserializerOptions { internal readonly List discriminators = new List(); public void AddTypeDiscriminator(ITypeDiscriminator discriminator) { discriminators.Add(discriminator); } public void AddKeyValueTypeDiscriminator(string discriminatorKey, IDictionary valueTypeMapping) { discriminators.Add(new KeyValueTypeDiscriminator(typeof(T), discriminatorKey, valueTypeMapping)); } public void AddUniqueKeyTypeDiscriminator(IDictionary uniqueKeyTypeMapping) { discriminators.Add(new UniqueKeyTypeDiscriminator(typeof(T), uniqueKeyTypeMapping)); } } } namespace YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators { internal interface ITypeDiscriminator { Type BaseType { get; } bool TryDiscriminate(IParser buffer, out Type? suggestedType); } internal class KeyValueTypeDiscriminator : ITypeDiscriminator { private readonly string targetKey; private readonly IDictionary typeMapping; public Type BaseType { get; private set; } public KeyValueTypeDiscriminator(Type baseType, string targetKey, IDictionary typeMapping) { foreach (KeyValuePair item in typeMapping) { if (!baseType.IsAssignableFrom(item.Value)) { throw new ArgumentOutOfRangeException("typeMapping", $"{item.Value} is not a assignable to {baseType}"); } } BaseType = baseType; this.targetKey = targetKey; this.typeMapping = typeMapping; } public bool TryDiscriminate(IParser parser, out Type? suggestedType) { if (parser.TryFindMappingEntry((YamlDotNet.Core.Events.Scalar scalar) => targetKey == scalar.Value, out YamlDotNet.Core.Events.Scalar _, out ParsingEvent value) && value is YamlDotNet.Core.Events.Scalar scalar2 && typeMapping.TryGetValue(scalar2.Value, out Type value2)) { suggestedType = value2; return true; } suggestedType = null; return false; } } internal class UniqueKeyTypeDiscriminator : ITypeDiscriminator { private readonly IDictionary typeMapping; public Type BaseType { get; private set; } public UniqueKeyTypeDiscriminator(Type baseType, IDictionary typeMapping) { foreach (KeyValuePair item in typeMapping) { if (!baseType.IsAssignableFrom(item.Value)) { throw new ArgumentOutOfRangeException("typeMapping", $"{item.Value} is not a assignable to {baseType}"); } } BaseType = baseType; this.typeMapping = typeMapping; } public bool TryDiscriminate(IParser parser, out Type? suggestedType) { if (parser.TryFindMappingEntry((YamlDotNet.Core.Events.Scalar scalar) => typeMapping.ContainsKey(scalar.Value), out YamlDotNet.Core.Events.Scalar key, out ParsingEvent _)) { suggestedType = typeMapping[key.Value]; return true; } suggestedType = null; return false; } } } namespace YamlDotNet.RepresentationModel { internal class DocumentLoadingState { private readonly IDictionary anchors = new Dictionary(); private readonly IList nodesWithUnresolvedAliases = new List(); public void AddAnchor(YamlNode node) { if (node.Anchor.IsEmpty) { throw new ArgumentException("The specified node does not have an anchor"); } if (anchors.ContainsKey(node.Anchor)) { anchors[node.Anchor] = node; } else { anchors.Add(node.Anchor, node); } } public YamlNode GetNode(AnchorName anchor, Mark start, Mark end) { if (anchors.TryGetValue(anchor, out YamlNode value)) { return value; } throw new AnchorNotFoundException(in start, in end, $"The anchor '{anchor}' does not exists"); } public bool TryGetNode(AnchorName anchor, [NotNullWhen(true)] out YamlNode? node) { return anchors.TryGetValue(anchor, out node); } public void AddNodeWithUnresolvedAliases(YamlNode node) { nodesWithUnresolvedAliases.Add(node); } public void ResolveAliases() { foreach (YamlNode nodesWithUnresolvedAlias in nodesWithUnresolvedAliases) { nodesWithUnresolvedAlias.ResolveAliases(this); } } } internal class EmitterState { public HashSet EmittedAnchors { get; } = new HashSet(); } internal interface IYamlVisitor { void Visit(YamlStream stream); void Visit(YamlDocument document); void Visit(YamlScalarNode scalar); void Visit(YamlSequenceNode sequence); void Visit(YamlMappingNode mapping); } internal class LibYamlEventStream { private readonly IParser parser; public LibYamlEventStream(IParser iParser) { parser = iParser ?? throw new ArgumentNullException("iParser"); } public void WriteTo(TextWriter textWriter) { while (parser.MoveNext()) { ParsingEvent current = parser.Current; if (!(current is YamlDotNet.Core.Events.AnchorAlias anchorAlias)) { if (!(current is YamlDotNet.Core.Events.DocumentEnd documentEnd)) { if (!(current is YamlDotNet.Core.Events.DocumentStart documentStart)) { if (!(current is MappingEnd)) { if (!(current is MappingStart nodeEvent)) { if (!(current is YamlDotNet.Core.Events.Scalar scalar)) { if (!(current is SequenceEnd)) { if (!(current is SequenceStart nodeEvent2)) { if (!(current is YamlDotNet.Core.Events.StreamEnd)) { if (current is YamlDotNet.Core.Events.StreamStart) { textWriter.Write("+STR"); } } else { textWriter.Write("-STR"); } } else { textWriter.Write("+SEQ"); WriteAnchorAndTag(textWriter, nodeEvent2); } } else { textWriter.Write("-SEQ"); } } else { textWriter.Write("=VAL"); WriteAnchorAndTag(textWriter, scalar); switch (scalar.Style) { case ScalarStyle.DoubleQuoted: textWriter.Write(" \""); break; case ScalarStyle.SingleQuoted: textWriter.Write(" '"); break; case ScalarStyle.Folded: textWriter.Write(" >"); break; case ScalarStyle.Literal: textWriter.Write(" |"); break; default: textWriter.Write(" :"); break; } string value = scalar.Value; foreach (char c in value) { switch (c) { case '\b': textWriter.Write("\\b"); break; case '\t': textWriter.Write("\\t"); break; case '\n': textWriter.Write("\\n"); break; case '\r': textWriter.Write("\\r"); break; case '\\': textWriter.Write("\\\\"); break; default: textWriter.Write(c); break; } } } } else { textWriter.Write("+MAP"); WriteAnchorAndTag(textWriter, nodeEvent); } } else { textWriter.Write("-MAP"); } } else { textWriter.Write("+DOC"); if (!documentStart.IsImplicit) { textWriter.Write(" ---"); } } } else { textWriter.Write("-DOC"); if (!documentEnd.IsImplicit) { textWriter.Write(" ..."); } } } else { textWriter.Write("=ALI *"); textWriter.Write(anchorAlias.Value); } textWriter.WriteLine(); } } private void WriteAnchorAndTag(TextWriter textWriter, NodeEvent nodeEvent) { if (!nodeEvent.Anchor.IsEmpty) { textWriter.Write(" &"); textWriter.Write(nodeEvent.Anchor); } if (!nodeEvent.Tag.IsEmpty) { textWriter.Write(" <"); textWriter.Write(nodeEvent.Tag.Value); textWriter.Write(">"); } } } internal class YamlAliasNode : YamlNode { public override YamlNodeType NodeType => YamlNodeType.Alias; internal YamlAliasNode(AnchorName anchor) { base.Anchor = anchor; } internal override void ResolveAliases(DocumentLoadingState state) { throw new NotSupportedException("Resolving an alias on an alias node does not make sense"); } internal override void Emit(IEmitter emitter, EmitterState state) { throw new NotSupportedException("A YamlAliasNode is an implementation detail and should never be saved."); } public override void Accept(IYamlVisitor visitor) { throw new NotSupportedException("A YamlAliasNode is an implementation detail and should never be visited."); } public override bool Equals(object? obj) { if (obj is YamlAliasNode yamlAliasNode && Equals(yamlAliasNode)) { return object.Equals(base.Anchor, yamlAliasNode.Anchor); } return false; } public override int GetHashCode() { return base.GetHashCode(); } internal override string ToString(RecursionLevel level) { return "*" + base.Anchor.ToString(); } internal override IEnumerable SafeAllNodes(RecursionLevel level) { yield return this; } } internal class YamlDocument { private class AnchorAssigningVisitor : YamlVisitorBase { private readonly HashSet existingAnchors = new HashSet(); private readonly Dictionary visitedNodes = new Dictionary(); public void AssignAnchors(YamlDocument document) { existingAnchors.Clear(); visitedNodes.Clear(); document.Accept(this); Random random = new Random(); foreach (KeyValuePair visitedNode in visitedNodes) { if (!visitedNode.Value) { continue; } AnchorName anchorName; if (!visitedNode.Key.Anchor.IsEmpty && !existingAnchors.Contains(visitedNode.Key.Anchor)) { anchorName = visitedNode.Key.Anchor; } else { do { anchorName = new AnchorName(random.Next().ToString(CultureInfo.InvariantCulture)); } while (existingAnchors.Contains(anchorName)); } existingAnchors.Add(anchorName); visitedNode.Key.Anchor = anchorName; } } private bool VisitNodeAndFindDuplicates(YamlNode node) { if (visitedNodes.TryGetValue(node, out var value)) { if (!value) { visitedNodes[node] = true; } return !value; } visitedNodes.Add(node, value: false); return false; } public override void Visit(YamlScalarNode scalar) { VisitNodeAndFindDuplicates(scalar); } public override void Visit(YamlMappingNode mapping) { if (!VisitNodeAndFindDuplicates(mapping)) { base.Visit(mapping); } } public override void Visit(YamlSequenceNode sequence) { if (!VisitNodeAndFindDuplicates(sequence)) { base.Visit(sequence); } } } public YamlNode RootNode { get; private set; } public IEnumerable AllNodes => RootNode.AllNodes; public YamlDocument(YamlNode rootNode) { RootNode = rootNode; } public YamlDocument(string rootNode) { RootNode = new YamlScalarNode(rootNode); } internal YamlDocument(IParser parser) { DocumentLoadingState documentLoadingState = new DocumentLoadingState(); parser.Consume(); YamlDotNet.Core.Events.DocumentEnd @event; while (!parser.TryConsume(out @event)) { RootNode = YamlNode.ParseNode(parser, documentLoadingState); if (RootNode is YamlAliasNode) { throw new YamlException("A document cannot contain only an alias"); } } documentLoadingState.ResolveAliases(); if (RootNode == null) { throw new ArgumentException("Atempted to parse an empty document"); } } private void AssignAnchors() { new AnchorAssigningVisitor().AssignAnchors(this); } internal void Save(IEmitter emitter, bool assignAnchors = true) { if (assignAnchors) { AssignAnchors(); } emitter.Emit(new YamlDotNet.Core.Events.DocumentStart()); RootNode.Save(emitter, new EmitterState()); emitter.Emit(new YamlDotNet.Core.Events.DocumentEnd(isImplicit: false)); } public void Accept(IYamlVisitor visitor) { visitor.Visit(this); } } internal sealed class YamlMappingNode : YamlNode, IEnumerable>, IEnumerable, IYamlConvertible { private readonly OrderedDictionary children = new OrderedDictionary(); public IOrderedDictionary Children => children; public MappingStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Mapping; internal YamlMappingNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { MappingStart mappingStart = parser.Consume(); Load(mappingStart, state); Style = mappingStart.Style; bool flag = false; MappingEnd @event; while (!parser.TryConsume(out @event)) { YamlNode yamlNode = YamlNode.ParseNode(parser, state); YamlNode yamlNode2 = YamlNode.ParseNode(parser, state); try { children.Add(yamlNode, yamlNode2); } catch (ArgumentException innerException) { Mark start = yamlNode.Start; Mark end = yamlNode.End; throw new YamlException(in start, in end, "Duplicate key", innerException); } flag = flag || yamlNode is YamlAliasNode || yamlNode2 is YamlAliasNode; } if (flag) { state.AddNodeWithUnresolvedAliases(this); } } public YamlMappingNode() { } public YamlMappingNode(params KeyValuePair[] children) : this((IEnumerable>)children) { } public YamlMappingNode(IEnumerable> children) { foreach (KeyValuePair child in children) { this.children.Add(child); } } public YamlMappingNode(params YamlNode[] children) : this((IEnumerable)children) { } public YamlMappingNode(IEnumerable children) { using IEnumerator enumerator = children.GetEnumerator(); while (enumerator.MoveNext()) { YamlNode current = enumerator.Current; if (!enumerator.MoveNext()) { throw new ArgumentException("When constructing a mapping node with a sequence, the number of elements of the sequence must be even."); } Add(current, enumerator.Current); } } public void Add(YamlNode key, YamlNode value) { children.Add(key, value); } public void Add(string key, YamlNode value) { children.Add(new YamlScalarNode(key), value); } public void Add(YamlNode key, string value) { children.Add(key, new YamlScalarNode(value)); } public void Add(string key, string value) { children.Add(new YamlScalarNode(key), new YamlScalarNode(value)); } internal override void ResolveAliases(DocumentLoadingState state) { Dictionary dictionary = null; Dictionary dictionary2 = null; foreach (KeyValuePair child in children) { if (child.Key is YamlAliasNode) { if (dictionary == null) { dictionary = new Dictionary(); } dictionary.Add(child.Key, state.GetNode(child.Key.Anchor, child.Key.Start, child.Key.End)); } if (child.Value is YamlAliasNode) { if (dictionary2 == null) { dictionary2 = new Dictionary(); } dictionary2.Add(child.Key, state.GetNode(child.Value.Anchor, child.Value.Start, child.Value.End)); } } if (dictionary2 != null) { foreach (KeyValuePair item in dictionary2) { children[item.Key] = item.Value; } } if (dictionary == null) { return; } foreach (KeyValuePair item2 in dictionary) { YamlNode value = children[item2.Key]; children.Remove(item2.Key); children.Add(item2.Value, value); } } internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new MappingStart(base.Anchor, base.Tag, isImplicit: true, Style)); foreach (KeyValuePair child in children) { child.Key.Save(emitter, state); child.Value.Save(emitter, state); } emitter.Emit(new MappingEnd()); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } public override bool Equals(object? obj) { if (!(obj is YamlMappingNode yamlMappingNode) || !object.Equals(base.Tag, yamlMappingNode.Tag) || children.Count != yamlMappingNode.children.Count) { return false; } foreach (KeyValuePair child in children) { if (!yamlMappingNode.children.TryGetValue(child.Key, out YamlNode value) || !object.Equals(child.Value, value)) { return false; } } return true; } public override int GetHashCode() { int num = base.GetHashCode(); foreach (KeyValuePair child in children) { num = YamlDotNet.Core.HashCode.CombineHashCodes(num, child.Key); num = YamlDotNet.Core.HashCode.CombineHashCodes(num, child.Value); } return num; } internal override IEnumerable SafeAllNodes(RecursionLevel level) { level.Increment(); yield return this; foreach (KeyValuePair child in children) { foreach (YamlNode item in child.Key.SafeAllNodes(level)) { yield return item; } foreach (YamlNode item2 in child.Value.SafeAllNodes(level)) { yield return item2; } } level.Decrement(); } internal override string ToString(RecursionLevel level) { if (!level.TryIncrement()) { return "WARNING! INFINITE RECURSION!"; } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; builder.Append("{ "); foreach (KeyValuePair child in children) { if (builder.Length > 2) { builder.Append(", "); } builder.Append("{ ").Append(child.Key.ToString(level)).Append(", ") .Append(child.Value.ToString(level)) .Append(" }"); } builder.Append(" }"); level.Decrement(); return builder.ToString(); } finally { ((IDisposable)builderWrapper).Dispose(); } } public IEnumerator> GetEnumerator() { return children.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new DocumentLoadingState()); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new EmitterState()); } public static YamlMappingNode FromObject(object mapping) { if (mapping == null) { throw new ArgumentNullException("mapping"); } YamlMappingNode yamlMappingNode = new YamlMappingNode(); foreach (PropertyInfo publicProperty in mapping.GetType().GetPublicProperties()) { if (publicProperty.CanRead && publicProperty.GetGetMethod(nonPublic: false).GetParameters().Length == 0) { object value = publicProperty.GetValue(mapping, null); YamlNode yamlNode = value as YamlNode; if (yamlNode == null) { yamlNode = Convert.ToString(value) ?? string.Empty; } yamlMappingNode.Add(publicProperty.Name, yamlNode); } } return yamlMappingNode; } } internal abstract class YamlNode { private const int MaximumRecursionLevel = 1000; internal const string MaximumRecursionLevelReachedToStringValue = "WARNING! INFINITE RECURSION!"; public AnchorName Anchor { get; set; } public TagName Tag { get; set; } public Mark Start { get; private set; } = Mark.Empty; public Mark End { get; private set; } = Mark.Empty; public IEnumerable AllNodes { get { RecursionLevel level = new RecursionLevel(1000); return SafeAllNodes(level); } } public abstract YamlNodeType NodeType { get; } public YamlNode this[int index] { get { if (!(this is YamlSequenceNode yamlSequenceNode)) { throw new ArgumentException($"Accessed '{NodeType}' with an invalid index: {index}. Only Sequences can be indexed by number."); } return yamlSequenceNode.Children[index]; } } public YamlNode this[YamlNode key] { get { if (!(this is YamlMappingNode yamlMappingNode)) { throw new ArgumentException($"Accessed '{NodeType}' with an invalid index: {key}. Only Mappings can be indexed by key."); } return yamlMappingNode.Children[key]; } } internal void Load(NodeEvent yamlEvent, DocumentLoadingState state) { Tag = yamlEvent.Tag; if (!yamlEvent.Anchor.IsEmpty) { Anchor = yamlEvent.Anchor; state.AddAnchor(this); } Start = yamlEvent.Start; End = yamlEvent.End; } internal static YamlNode ParseNode(IParser parser, DocumentLoadingState state) { if (parser.Accept(out var _)) { return new YamlScalarNode(parser, state); } if (parser.Accept(out var _)) { return new YamlSequenceNode(parser, state); } if (parser.Accept(out var _)) { return new YamlMappingNode(parser, state); } if (parser.TryConsume(out var event4)) { if (!state.TryGetNode(event4.Value, out YamlNode node)) { return new YamlAliasNode(event4.Value); } return node; } throw new ArgumentException("The current event is of an unsupported type.", "parser"); } internal abstract void ResolveAliases(DocumentLoadingState state); internal void Save(IEmitter emitter, EmitterState state) { if (!Anchor.IsEmpty && !state.EmittedAnchors.Add(Anchor)) { emitter.Emit(new YamlDotNet.Core.Events.AnchorAlias(Anchor)); } else { Emit(emitter, state); } } internal abstract void Emit(IEmitter emitter, EmitterState state); public abstract void Accept(IYamlVisitor visitor); public override string ToString() { RecursionLevel recursionLevel = new RecursionLevel(1000); return ToString(recursionLevel); } internal abstract string ToString(RecursionLevel level); internal abstract IEnumerable SafeAllNodes(RecursionLevel level); public static implicit operator YamlNode(string value) { return new YamlScalarNode(value); } public static implicit operator YamlNode(string[] sequence) { return new YamlSequenceNode(((IEnumerable)sequence).Select((Func)((string i) => i))); } public static explicit operator string?(YamlNode node) { if (!(node is YamlScalarNode yamlScalarNode)) { throw new ArgumentException($"Attempted to convert a '{node.NodeType}' to string. This conversion is valid only for Scalars."); } return yamlScalarNode.Value; } } internal sealed class YamlNodeIdentityEqualityComparer : IEqualityComparer { public bool Equals([AllowNull] YamlNode x, [AllowNull] YamlNode y) { return x == y; } public int GetHashCode(YamlNode obj) { return obj.GetHashCode(); } } internal enum YamlNodeType { Alias, Mapping, Scalar, Sequence } [DebuggerDisplay("{Value}")] internal sealed class YamlScalarNode : YamlNode, IYamlConvertible { public string? Value { get; set; } public ScalarStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Scalar; internal YamlScalarNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { YamlDotNet.Core.Events.Scalar scalar = parser.Consume(); Load(scalar, state); Value = scalar.Value; Style = scalar.Style; } public YamlScalarNode() { } public YamlScalarNode(string? value) { Value = value; } internal override void ResolveAliases(DocumentLoadingState state) { throw new NotSupportedException("Resolving an alias on a scalar node does not make sense"); } internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new YamlDotNet.Core.Events.Scalar(base.Anchor, base.Tag, Value ?? string.Empty, Style, base.Tag.IsEmpty, isQuotedImplicit: false)); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } public override bool Equals(object? obj) { if (obj is YamlScalarNode yamlScalarNode && object.Equals(base.Tag, yamlScalarNode.Tag)) { return object.Equals(Value, yamlScalarNode.Value); } return false; } public override int GetHashCode() { return YamlDotNet.Core.HashCode.CombineHashCodes(base.Tag.GetHashCode(), Value); } public static explicit operator string?(YamlScalarNode value) { return value.Value; } internal override string ToString(RecursionLevel level) { return Value ?? string.Empty; } internal override IEnumerable SafeAllNodes(RecursionLevel level) { yield return this; } void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new DocumentLoadingState()); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new EmitterState()); } } [DebuggerDisplay("Count = {children.Count}")] internal sealed class YamlSequenceNode : YamlNode, IEnumerable, IEnumerable, IYamlConvertible { private readonly IList children = new List(); public IList Children => children; public SequenceStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Sequence; internal YamlSequenceNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { SequenceStart sequenceStart = parser.Consume(); Load(sequenceStart, state); Style = sequenceStart.Style; bool flag = false; SequenceEnd @event; while (!parser.TryConsume(out @event)) { YamlNode yamlNode = YamlNode.ParseNode(parser, state); children.Add(yamlNode); flag = flag || yamlNode is YamlAliasNode; } if (flag) { state.AddNodeWithUnresolvedAliases(this); } } public YamlSequenceNode() { } public YamlSequenceNode(params YamlNode[] children) : this((IEnumerable)children) { } public YamlSequenceNode(IEnumerable children) { foreach (YamlNode child in children) { this.children.Add(child); } } public void Add(YamlNode child) { children.Add(child); } public void Add(string child) { children.Add(new YamlScalarNode(child)); } internal override void ResolveAliases(DocumentLoadingState state) { for (int i = 0; i < children.Count; i++) { if (children[i] is YamlAliasNode) { children[i] = state.GetNode(children[i].Anchor, children[i].Start, children[i].End); } } } internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new SequenceStart(base.Anchor, base.Tag, base.Tag.IsEmpty, Style)); foreach (YamlNode child in children) { child.Save(emitter, state); } emitter.Emit(new SequenceEnd()); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } public override bool Equals(object? obj) { if (!(obj is YamlSequenceNode yamlSequenceNode) || !object.Equals(base.Tag, yamlSequenceNode.Tag) || children.Count != yamlSequenceNode.children.Count) { return false; } for (int i = 0; i < children.Count; i++) { if (!object.Equals(children[i], yamlSequenceNode.children[i])) { return false; } } return true; } public override int GetHashCode() { int h = 0; foreach (YamlNode child in children) { h = YamlDotNet.Core.HashCode.CombineHashCodes(h, child); } return YamlDotNet.Core.HashCode.CombineHashCodes(h, base.Tag); } internal override IEnumerable SafeAllNodes(RecursionLevel level) { level.Increment(); yield return this; foreach (YamlNode child in children) { foreach (YamlNode item in child.SafeAllNodes(level)) { yield return item; } } level.Decrement(); } internal override string ToString(RecursionLevel level) { if (!level.TryIncrement()) { return "WARNING! INFINITE RECURSION!"; } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; builder.Append("[ "); foreach (YamlNode child in children) { if (builder.Length > 2) { builder.Append(", "); } builder.Append(child.ToString(level)); } builder.Append(" ]"); level.Decrement(); return builder.ToString(); } finally { ((IDisposable)builderWrapper).Dispose(); } } public IEnumerator GetEnumerator() { return Children.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new DocumentLoadingState()); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new EmitterState()); } } internal class YamlStream : IEnumerable, IEnumerable { private readonly IList documents = new List(); public IList Documents => documents; public YamlStream() { } public YamlStream(params YamlDocument[] documents) : this((IEnumerable)documents) { } public YamlStream(IEnumerable documents) { foreach (YamlDocument document in documents) { this.documents.Add(document); } } public void Add(YamlDocument document) { documents.Add(document); } public void Load(TextReader input) { Load(new Parser(input)); } public void Load(IParser parser) { documents.Clear(); parser.Consume(); YamlDotNet.Core.Events.StreamEnd @event; while (!parser.TryConsume(out @event)) { YamlDocument item = new YamlDocument(parser); documents.Add(item); } } public void Save(TextWriter output) { Save(output, assignAnchors: true); } public void Save(TextWriter output, bool assignAnchors) { Save(new Emitter(output), assignAnchors); } public void Save(IEmitter emitter, bool assignAnchors) { emitter.Emit(new YamlDotNet.Core.Events.StreamStart()); foreach (YamlDocument document in documents) { document.Save(emitter, assignAnchors); } emitter.Emit(new YamlDotNet.Core.Events.StreamEnd()); } public void Accept(IYamlVisitor visitor) { visitor.Visit(this); } public IEnumerator GetEnumerator() { return documents.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [Obsolete("Use YamlVisitorBase")] internal abstract class YamlVisitor : IYamlVisitor { protected virtual void Visit(YamlStream stream) { } protected virtual void Visited(YamlStream stream) { } protected virtual void Visit(YamlDocument document) { } protected virtual void Visited(YamlDocument document) { } protected virtual void Visit(YamlScalarNode scalar) { } protected virtual void Visited(YamlScalarNode scalar) { } protected virtual void Visit(YamlSequenceNode sequence) { } protected virtual void Visited(YamlSequenceNode sequence) { } protected virtual void Visit(YamlMappingNode mapping) { } protected virtual void Visited(YamlMappingNode mapping) { } protected virtual void VisitChildren(YamlStream stream) { foreach (YamlDocument document in stream.Documents) { document.Accept(this); } } protected virtual void VisitChildren(YamlDocument document) { if (document.RootNode != null) { document.RootNode.Accept(this); } } protected virtual void VisitChildren(YamlSequenceNode sequence) { foreach (YamlNode child in sequence.Children) { child.Accept(this); } } protected virtual void VisitChildren(YamlMappingNode mapping) { foreach (KeyValuePair child in mapping.Children) { child.Key.Accept(this); child.Value.Accept(this); } } void IYamlVisitor.Visit(YamlStream stream) { Visit(stream); VisitChildren(stream); Visited(stream); } void IYamlVisitor.Visit(YamlDocument document) { Visit(document); VisitChildren(document); Visited(document); } void IYamlVisitor.Visit(YamlScalarNode scalar) { Visit(scalar); Visited(scalar); } void IYamlVisitor.Visit(YamlSequenceNode sequence) { Visit(sequence); VisitChildren(sequence); Visited(sequence); } void IYamlVisitor.Visit(YamlMappingNode mapping) { Visit(mapping); VisitChildren(mapping); Visited(mapping); } } internal abstract class YamlVisitorBase : IYamlVisitor { public virtual void Visit(YamlStream stream) { VisitChildren(stream); } public virtual void Visit(YamlDocument document) { VisitChildren(document); } public virtual void Visit(YamlScalarNode scalar) { } public virtual void Visit(YamlSequenceNode sequence) { VisitChildren(sequence); } public virtual void Visit(YamlMappingNode mapping) { VisitChildren(mapping); } protected virtual void VisitPair(YamlNode key, YamlNode value) { key.Accept(this); value.Accept(this); } protected virtual void VisitChildren(YamlStream stream) { foreach (YamlDocument document in stream.Documents) { document.Accept(this); } } protected virtual void VisitChildren(YamlDocument document) { if (document.RootNode != null) { document.RootNode.Accept(this); } } protected virtual void VisitChildren(YamlSequenceNode sequence) { foreach (YamlNode child in sequence.Children) { child.Accept(this); } } protected virtual void VisitChildren(YamlMappingNode mapping) { foreach (KeyValuePair child in mapping.Children) { VisitPair(child.Key, child.Value); } } } } namespace YamlDotNet.Helpers { [DebuggerStepThrough] internal sealed class ConcurrentObjectPool where T : class { [DebuggerDisplay("{value,nq}")] private struct Element { internal T? value; } internal delegate T Factory(); private T? firstItem; private readonly Element[] items; private readonly Factory factory; internal ConcurrentObjectPool(Factory factory) : this(factory, Environment.ProcessorCount * 2) { } internal ConcurrentObjectPool(Factory factory, int size) { this.factory = factory; items = new Element[size - 1]; } private T CreateInstance() { return factory(); } internal T Allocate() { T val = firstItem; if (val == null || val != Interlocked.CompareExchange(ref firstItem, null, val)) { val = AllocateSlow(); } return val; } private T AllocateSlow() { Element[] array = items; for (int i = 0; i < array.Length; i++) { T value = array[i].value; if (value != null && value == Interlocked.CompareExchange(ref array[i].value, null, value)) { return value; } } return CreateInstance(); } internal void Free(T obj) { if (firstItem == null) { firstItem = obj; } else { FreeSlow(obj); } } private void FreeSlow(T obj) { Element[] array = items; for (int i = 0; i < array.Length; i++) { if (array[i].value == null) { array[i].value = obj; break; } } } [Conditional("DEBUG")] private void Validate(object obj) { Element[] array = items; for (int i = 0; i < array.Length && array[i].value != null; i++) { } } } internal static class ExpressionExtensions { public static PropertyInfo AsProperty(this LambdaExpression propertyAccessor) { PropertyInfo propertyInfo = TryGetMemberExpression(propertyAccessor); if (propertyInfo == null) { throw new ArgumentException("Expected a lambda expression in the form: x => x.SomeProperty", "propertyAccessor"); } return propertyInfo; } [return: MaybeNull] private static TMemberInfo TryGetMemberExpression(LambdaExpression lambdaExpression) where TMemberInfo : MemberInfo { if (lambdaExpression.Parameters.Count != 1) { return null; } Expression expression = lambdaExpression.Body; if (expression is UnaryExpression unaryExpression) { if (unaryExpression.NodeType != ExpressionType.Convert) { return null; } expression = unaryExpression.Operand; } if (expression is MemberExpression memberExpression) { if (memberExpression.Expression != lambdaExpression.Parameters[0]) { return null; } return memberExpression.Member as TMemberInfo; } return null; } } internal sealed class GenericCollectionToNonGenericAdapter : IList, ICollection, IEnumerable { private readonly ICollection genericCollection; public bool IsFixedSize { get { throw new NotSupportedException(); } } public bool IsReadOnly { get { throw new NotSupportedException(); } } public object? this[int index] { get { throw new NotSupportedException(); } set { ((IList)genericCollection)[index] = (T)value; } } public int Count { get { throw new NotSupportedException(); } } public bool IsSynchronized { get { throw new NotSupportedException(); } } public object SyncRoot { get { throw new NotSupportedException(); } } public GenericCollectionToNonGenericAdapter(ICollection genericCollection) { this.genericCollection = genericCollection ?? throw new ArgumentNullException("genericCollection"); } public int Add(object? value) { int count = genericCollection.Count; genericCollection.Add((T)value); return count; } public void Clear() { genericCollection.Clear(); } public bool Contains(object? value) { throw new NotSupportedException(); } public int IndexOf(object? value) { throw new NotSupportedException(); } public void Insert(int index, object? value) { throw new NotSupportedException(); } public void Remove(object? value) { throw new NotSupportedException(); } public void RemoveAt(int index) { throw new NotSupportedException(); } public void CopyTo(Array array, int index) { throw new NotSupportedException(); } public IEnumerator GetEnumerator() { return genericCollection.GetEnumerator(); } } internal sealed class GenericDictionaryToNonGenericAdapter : IDictionary, ICollection, IEnumerable where TKey : notnull { private class DictionaryEnumerator : IDictionaryEnumerator, IEnumerator { private readonly IEnumerator> enumerator; public DictionaryEntry Entry => new DictionaryEntry(Key, Value); public object Key => enumerator.Current.Key; public object? Value => enumerator.Current.Value; public object Current => Entry; public DictionaryEnumerator(IEnumerator> enumerator) { this.enumerator = enumerator; } public bool MoveNext() { return enumerator.MoveNext(); } public void Reset() { enumerator.Reset(); } } private readonly IDictionary genericDictionary; public bool IsFixedSize { get { throw new NotSupportedException(); } } public bool IsReadOnly { get { throw new NotSupportedException(); } } public ICollection Keys { get { throw new NotSupportedException(); } } public ICollection Values { get { throw new NotSupportedException(); } } public object? this[object key] { get { throw new NotSupportedException(); } set { genericDictionary[(TKey)key] = (TValue)value; } } public int Count { get { throw new NotSupportedException(); } } public bool IsSynchronized { get { throw new NotSupportedException(); } } public object SyncRoot { get { throw new NotSupportedException(); } } public GenericDictionaryToNonGenericAdapter(IDictionary genericDictionary) { this.genericDictionary = genericDictionary ?? throw new ArgumentNullException("genericDictionary"); } public void Add(object key, object? value) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(object key) { throw new NotSupportedException(); } public IDictionaryEnumerator GetEnumerator() { return new DictionaryEnumerator(genericDictionary.GetEnumerator()); } public void Remove(object key) { throw new NotSupportedException(); } public void CopyTo(Array array, int index) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal interface IOrderedDictionary : IDictionary, ICollection>, IEnumerable>, IEnumerable where TKey : notnull { KeyValuePair this[int index] { get; set; } void Insert(int index, TKey key, TValue value); void RemoveAt(int index); } internal static class NumberExtensions { public static bool IsPowerOfTwo(this int value) { return (value & (value - 1)) == 0; } } [Serializable] internal sealed class OrderedDictionary : IOrderedDictionary, IDictionary, ICollection>, IEnumerable>, IEnumerable where TKey : notnull { private class KeyCollection : ICollection, IEnumerable, IEnumerable { private readonly OrderedDictionary orderedDictionary; public int Count => orderedDictionary.list.Count; public bool IsReadOnly => true; public void Add(TKey item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(TKey item) { return orderedDictionary.dictionary.Keys.Contains(item); } public KeyCollection(OrderedDictionary orderedDictionary) { this.orderedDictionary = orderedDictionary; } public void CopyTo(TKey[] array, int arrayIndex) { for (int i = 0; i < orderedDictionary.list.Count; i++) { array[i] = orderedDictionary.list[i + arrayIndex].Key; } } public IEnumerator GetEnumerator() { return orderedDictionary.list.Select((KeyValuePair kvp) => kvp.Key).GetEnumerator(); } public bool Remove(TKey item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private class ValueCollection : ICollection, IEnumerable, IEnumerable { private readonly OrderedDictionary orderedDictionary; public int Count => orderedDictionary.list.Count; public bool IsReadOnly => true; public void Add(TValue item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(TValue item) { return orderedDictionary.dictionary.Values.Contains(item); } public ValueCollection(OrderedDictionary orderedDictionary) { this.orderedDictionary = orderedDictionary; } public void CopyTo(TValue[] array, int arrayIndex) { for (int i = 0; i < orderedDictionary.list.Count; i++) { array[i] = orderedDictionary.list[i + arrayIndex].Value; } } public IEnumerator GetEnumerator() { return orderedDictionary.list.Select((KeyValuePair kvp) => kvp.Value).GetEnumerator(); } public bool Remove(TValue item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [NonSerialized] private Dictionary dictionary; private readonly List> list; private readonly IEqualityComparer comparer; public TValue this[TKey key] { get { return dictionary[key]; } set { TKey key2 = key; if (dictionary.ContainsKey(key2)) { int index = list.FindIndex((KeyValuePair kvp) => comparer.Equals(kvp.Key, key2)); dictionary[key2] = value; list[index] = new KeyValuePair(key2, value); } else { Add(key2, value); } } } public ICollection Keys => new KeyCollection(this); public ICollection Values => new ValueCollection(this); public int Count => dictionary.Count; public bool IsReadOnly => false; public KeyValuePair this[int index] { get { return list[index]; } set { list[index] = value; } } public OrderedDictionary() : this((IEqualityComparer)EqualityComparer.Default) { } public OrderedDictionary(IEqualityComparer comparer) { list = new List>(); dictionary = new Dictionary(comparer); this.comparer = comparer; } public void Add(TKey key, TValue value) { Add(new KeyValuePair(key, value)); } public void Add(KeyValuePair item) { dictionary.Add(item.Key, item.Value); list.Add(item); } public void Clear() { dictionary.Clear(); list.Clear(); } public bool Contains(KeyValuePair item) { return dictionary.Contains(item); } public bool ContainsKey(TKey key) { return dictionary.ContainsKey(key); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { list.CopyTo(array, arrayIndex); } public IEnumerator> GetEnumerator() { return list.GetEnumerator(); } public void Insert(int index, TKey key, TValue value) { dictionary.Add(key, value); list.Insert(index, new KeyValuePair(key, value)); } public bool Remove(TKey key) { TKey key2 = key; if (dictionary.ContainsKey(key2)) { int index = list.FindIndex((KeyValuePair kvp) => comparer.Equals(kvp.Key, key2)); list.RemoveAt(index); if (!dictionary.Remove(key2)) { throw new InvalidOperationException(); } return true; } return false; } public bool Remove(KeyValuePair item) { return Remove(item.Key); } public void RemoveAt(int index) { TKey key = list[index].Key; dictionary.Remove(key); list.RemoveAt(index); } public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { return dictionary.TryGetValue(key, out value); } IEnumerator IEnumerable.GetEnumerator() { return list.GetEnumerator(); } [OnDeserialized] internal void OnDeserializedMethod(StreamingContext context) { dictionary = new Dictionary(); foreach (KeyValuePair item in list) { dictionary[item.Key] = item.Value; } } } [DebuggerStepThrough] internal static class StringBuilderPool { internal readonly struct BuilderWrapper : IDisposable { public readonly StringBuilder Builder; private readonly ConcurrentObjectPool _pool; public BuilderWrapper(StringBuilder builder, ConcurrentObjectPool pool) { Builder = builder; _pool = pool; } public override string ToString() { return Builder.ToString(); } public void Dispose() { StringBuilder builder = Builder; if (builder.Capacity <= 1024) { builder.Length = 0; _pool.Free(builder); } } } private static readonly ConcurrentObjectPool Pool; static StringBuilderPool() { Pool = new ConcurrentObjectPool(() => new StringBuilder()); } public static BuilderWrapper Rent() { return new BuilderWrapper(Pool.Allocate(), Pool); } } internal static class ThrowHelper { [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentOutOfRangeException(string paramName, string message) { throw new ArgumentOutOfRangeException(paramName, message); } } internal static class Lazy { public static Lazy FromValue(T value) { T value2 = value; Lazy lazy = new Lazy(() => value2, isThreadSafe: false); _ = lazy.Value; return lazy; } } internal static class ReadOnlyCollectionExtensions { public static IReadOnlyList AsReadonlyList(this List list) { return list; } public static IReadOnlyDictionary AsReadonlyDictionary(this Dictionary dictionary) where TKey : notnull { return dictionary; } } } namespace YamlDotNet.Core { internal struct AnchorName : IEquatable { public static readonly AnchorName Empty = default(AnchorName); private static readonly Regex AnchorPattern = new Regex("^[^\\[\\]\\{\\},]+$", RegexOptions.Compiled); private readonly string? value; public string Value => value ?? throw new InvalidOperationException("Cannot read the Value of an empty anchor"); public bool IsEmpty => value == null; public AnchorName(string value) { this.value = value ?? throw new ArgumentNullException("value"); if (!AnchorPattern.IsMatch(value)) { throw new ArgumentException("Anchor cannot be empty or contain disallowed characters: []{},\nThe value was '" + value + "'.", "value"); } } public override string ToString() { return value ?? "[empty]"; } public bool Equals(AnchorName other) { return object.Equals(value, other.value); } public override bool Equals(object? obj) { if (obj is AnchorName other) { return Equals(other); } return false; } public override int GetHashCode() { return value?.GetHashCode() ?? 0; } public static bool operator ==(AnchorName left, AnchorName right) { return left.Equals(right); } public static bool operator !=(AnchorName left, AnchorName right) { return !(left == right); } public static implicit operator AnchorName(string? value) { if (value != null) { return new AnchorName(value); } return Empty; } } internal class AnchorNotFoundException : YamlException { public AnchorNotFoundException(string message) : base(message) { } public AnchorNotFoundException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public AnchorNotFoundException(string message, Exception inner) : base(message, inner) { } } [DebuggerStepThrough] internal sealed class CharacterAnalyzer where TBuffer : class, ILookAheadBuffer { public TBuffer Buffer { get; } public bool EndOfInput => Buffer.EndOfInput; public CharacterAnalyzer(TBuffer buffer) { Buffer = buffer ?? throw new ArgumentNullException("buffer"); } public char Peek(int offset) { return Buffer.Peek(offset); } public void Skip(int length) { Buffer.Skip(length); } public bool IsAlphaNumericDashOrUnderscore(int offset = 0) { char c = Buffer.Peek(offset); if ((c < '0' || c > '9') && (c < 'A' || c > 'Z') && (c < 'a' || c > 'z') && c != '_') { return c == '-'; } return true; } public bool IsAscii(int offset = 0) { return Buffer.Peek(offset) <= '\u007f'; } public bool IsPrintable(int offset = 0) { char c = Buffer.Peek(offset); switch (c) { default: if (c != '\u0085' && (c < '\u00a0' || c > '\ud7ff')) { if (c >= '\ue000') { return c <= '\ufffd'; } return false; } break; case '\t': case '\n': case '\r': case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case '\\': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': break; } return true; } public bool IsDigit(int offset = 0) { char c = Buffer.Peek(offset); if (c >= '0') { return c <= '9'; } return false; } public int AsDigit(int offset = 0) { return Buffer.Peek(offset) - 48; } public bool IsHex(int offset) { char c = Buffer.Peek(offset); if ((c < '0' || c > '9') && (c < 'A' || c > 'F')) { if (c >= 'a') { return c <= 'f'; } return false; } return true; } public int AsHex(int offset) { char c = Buffer.Peek(offset); if (c <= '9') { return c - 48; } if (c <= 'F') { return c - 65 + 10; } return c - 97 + 10; } public bool IsSpace(int offset = 0) { return Check(' ', offset); } public bool IsZero(int offset = 0) { return Check('\0', offset); } public bool IsTab(int offset = 0) { return Check('\t', offset); } public bool IsWhite(int offset = 0) { if (!IsSpace(offset)) { return IsTab(offset); } return true; } public bool IsBreak(int offset = 0) { return Check("\r\n\u0085\u2028\u2029", offset); } public bool IsCrLf(int offset = 0) { if (Check('\r', offset)) { return Check('\n', offset + 1); } return false; } public bool IsBreakOrZero(int offset = 0) { if (!IsBreak(offset)) { return IsZero(offset); } return true; } public bool IsWhiteBreakOrZero(int offset = 0) { if (!IsWhite(offset)) { return IsBreakOrZero(offset); } return true; } public bool Check(char expected, int offset = 0) { return Buffer.Peek(offset) == expected; } public bool Check(string expectedCharacters, int offset = 0) { char value = Buffer.Peek(offset); return expectedCharacters.IndexOf(value) != -1; } } internal static class Constants { public static readonly TagDirective[] DefaultTagDirectives = new TagDirective[2] { new TagDirective("!", "!"), new TagDirective("!!", "tag:yaml.org,2002:") }; public const int MajorVersion = 1; public const int MinorVersion = 3; } [DebuggerStepThrough] internal sealed class Cursor { public int Index { get; private set; } public int Line { get; private set; } public int LineOffset { get; private set; } public Cursor() { Line = 1; } public Cursor(Cursor cursor) { Index = cursor.Index; Line = cursor.Line; LineOffset = cursor.LineOffset; } public Mark Mark() { return new Mark(Index, Line, LineOffset + 1); } public void Skip() { Index++; LineOffset++; } public void SkipLineByOffset(int offset) { Index += offset; Line++; LineOffset = 0; } public void ForceSkipLineAfterNonBreak() { if (LineOffset != 0) { Line++; LineOffset = 0; } } } internal class Emitter : IEmitter { private class AnchorData { public AnchorName Anchor; public bool IsAlias; } private class TagData { public string? Handle; public string? Suffix; } private class ScalarData { public string Value = string.Empty; public bool IsMultiline; public bool IsFlowPlainAllowed; public bool IsBlockPlainAllowed; public bool IsSingleQuotedAllowed; public bool IsBlockAllowed; public bool HasSingleQuotes; public ScalarStyle Style; } private static readonly Regex UriReplacer = new Regex("[^0-9A-Za-z_\\-;?@=$~\\\\\\)\\]/:&+,\\.\\*\\(\\[!]", RegexOptions.Compiled | RegexOptions.Singleline); private static readonly string[] newLineSeparators = new string[3] { "\r\n", "\r", "\n" }; private readonly TextWriter output; private readonly bool outputUsesUnicodeEncoding; private readonly int maxSimpleKeyLength; private readonly bool isCanonical; private readonly bool skipAnchorName; private readonly int bestIndent; private readonly int bestWidth; private EmitterState state; private readonly Stack states = new Stack(); private readonly Queue events = new Queue(); private readonly Stack indents = new Stack(); private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection(); private int indent; private int flowLevel; private bool isMappingContext; private bool isSimpleKeyContext; private int column; private bool isWhitespace; private bool isIndentation; private readonly bool forceIndentLess; private readonly string newLine; private bool isDocumentEndWritten; private readonly AnchorData anchorData = new AnchorData(); private readonly TagData tagData = new TagData(); private readonly ScalarData scalarData = new ScalarData(); public Emitter(TextWriter output) : this(output, EmitterSettings.Default) { } public Emitter(TextWriter output, int bestIndent) : this(output, bestIndent, int.MaxValue) { } public Emitter(TextWriter output, int bestIndent, int bestWidth) : this(output, bestIndent, bestWidth, isCanonical: false) { } public Emitter(TextWriter output, int bestIndent, int bestWidth, bool isCanonical) : this(output, new EmitterSettings(bestIndent, bestWidth, isCanonical, 1024)) { } public Emitter(TextWriter output, EmitterSettings settings) { bestIndent = settings.BestIndent; bestWidth = settings.BestWidth; isCanonical = settings.IsCanonical; maxSimpleKeyLength = settings.MaxSimpleKeyLength; skipAnchorName = settings.SkipAnchorName; forceIndentLess = !settings.IndentSequences; newLine = settings.NewLine; this.output = output; outputUsesUnicodeEncoding = IsUnicode(output.Encoding); } public void Emit(ParsingEvent @event) { events.Enqueue(@event); while (!NeedMoreEvents()) { ParsingEvent evt = events.Peek(); try { AnalyzeEvent(evt); StateMachine(evt); } finally { events.Dequeue(); } } } private bool NeedMoreEvents() { if (events.Count == 0) { return true; } int num; switch (events.Peek().Type) { case EventType.DocumentStart: num = 1; break; case EventType.SequenceStart: num = 2; break; case EventType.MappingStart: num = 3; break; default: return false; } if (events.Count > num) { return false; } int num2 = 0; using (Queue.Enumerator enumerator = events.GetEnumerator()) { while (enumerator.MoveNext()) { switch (enumerator.Current.Type) { case EventType.DocumentStart: case EventType.SequenceStart: case EventType.MappingStart: num2++; break; case EventType.DocumentEnd: case EventType.SequenceEnd: case EventType.MappingEnd: num2--; break; } if (num2 == 0) { return false; } } } return true; } private void AnalyzeEvent(ParsingEvent evt) { anchorData.Anchor = AnchorName.Empty; tagData.Handle = null; tagData.Suffix = null; if (evt is YamlDotNet.Core.Events.AnchorAlias anchorAlias) { AnalyzeAnchor(anchorAlias.Value, isAlias: true); } else if (evt is NodeEvent nodeEvent) { if (evt is YamlDotNet.Core.Events.Scalar scalar) { AnalyzeScalar(scalar); } AnalyzeAnchor(nodeEvent.Anchor, isAlias: false); if (!nodeEvent.Tag.IsEmpty && (isCanonical || nodeEvent.IsCanonical)) { AnalyzeTag(nodeEvent.Tag); } } } private void AnalyzeAnchor(AnchorName anchor, bool isAlias) { anchorData.Anchor = anchor; anchorData.IsAlias = isAlias; } private void AnalyzeScalar(YamlDotNet.Core.Events.Scalar scalar) { string value = scalar.Value; scalarData.Value = value; if (value.Length == 0) { if (scalar.Tag == "tag:yaml.org,2002:null") { scalarData.IsMultiline = false; scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = true; scalarData.IsSingleQuotedAllowed = false; scalarData.IsBlockAllowed = false; } else { scalarData.IsMultiline = false; scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = true; scalarData.IsBlockAllowed = false; } return; } bool flag = false; bool flag2 = false; if (value.StartsWith("---", StringComparison.Ordinal) || value.StartsWith("...", StringComparison.Ordinal)) { flag = true; flag2 = true; } CharacterAnalyzer characterAnalyzer = new CharacterAnalyzer(new StringLookAheadBuffer(value)); bool flag3 = true; bool flag4 = characterAnalyzer.IsWhiteBreakOrZero(1); bool flag5 = false; bool flag6 = false; bool flag7 = false; bool flag8 = false; bool flag9 = false; bool flag10 = false; bool flag11 = false; bool flag12 = false; bool flag13 = false; bool flag14 = false; bool flag15 = false; bool flag16 = !ValueIsRepresentableInOutputEncoding(value); bool flag17 = false; bool flag18 = false; bool flag19 = true; while (!characterAnalyzer.EndOfInput) { if (flag19) { if (characterAnalyzer.Check("#,[]{}&*!|>\\\"%@`'")) { flag = true; flag2 = true; flag9 = characterAnalyzer.Check('\''); flag17 |= characterAnalyzer.Check('\''); } if (characterAnalyzer.Check("?:")) { flag = true; if (flag4) { flag2 = true; } } if (characterAnalyzer.Check('-') && flag4) { flag = true; flag2 = true; } } else { if (characterAnalyzer.Check(",?[]{}")) { flag = true; } if (characterAnalyzer.Check(':')) { flag = true; if (flag4) { flag2 = true; } } if (characterAnalyzer.Check('#') && flag3) { flag = true; flag2 = true; } flag17 |= characterAnalyzer.Check('\''); } if (!flag16 && !characterAnalyzer.IsPrintable()) { flag16 = true; } if (characterAnalyzer.IsBreak()) { flag15 = true; } if (characterAnalyzer.IsSpace()) { if (flag19) { flag5 = true; } if (characterAnalyzer.Buffer.Position >= characterAnalyzer.Buffer.Length - 1) { flag7 = true; } if (flag13) { flag10 = true; flag14 = true; } flag12 = true; flag13 = false; } else if (characterAnalyzer.IsBreak()) { if (flag19) { flag6 = true; } if (characterAnalyzer.Buffer.Position >= characterAnalyzer.Buffer.Length - 1) { flag8 = true; } if (flag12) { flag11 = true; } if (flag14) { flag18 = true; } flag12 = false; flag13 = true; } else { flag12 = false; flag13 = false; flag14 = false; } flag3 = characterAnalyzer.IsWhiteBreakOrZero(); characterAnalyzer.Skip(1); if (!characterAnalyzer.EndOfInput) { flag4 = characterAnalyzer.IsWhiteBreakOrZero(1); } flag19 = false; } scalarData.IsFlowPlainAllowed = true; scalarData.IsBlockPlainAllowed = true; scalarData.IsSingleQuotedAllowed = true; scalarData.IsBlockAllowed = true; if (flag5 || flag6 || flag7 || flag8 || flag9) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; } if (flag7) { scalarData.IsBlockAllowed = false; } if (flag10) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = false; } if (flag11 || flag16) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = false; } if (flag18) { scalarData.IsBlockAllowed = false; } scalarData.IsMultiline = flag15; if (flag15) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; } if (flag) { scalarData.IsFlowPlainAllowed = false; } if (flag2) { scalarData.IsBlockPlainAllowed = false; } scalarData.HasSingleQuotes = flag17; } private bool ValueIsRepresentableInOutputEncoding(string value) { if (outputUsesUnicodeEncoding) { return true; } try { byte[] bytes = output.Encoding.GetBytes(value); return output.Encoding.GetString(bytes, 0, bytes.Length).Equals(value); } catch (EncoderFallbackException) { return false; } catch (ArgumentOutOfRangeException) { return false; } } private bool IsUnicode(Encoding encoding) { if (!(encoding is UTF8Encoding) && !(encoding is UnicodeEncoding)) { return encoding is UTF7Encoding; } return true; } private void AnalyzeTag(TagName tag) { tagData.Handle = tag.Value; foreach (TagDirective tagDirective in tagDirectives) { if (tag.Value.StartsWith(tagDirective.Prefix, StringComparison.Ordinal)) { tagData.Handle = tagDirective.Handle; tagData.Suffix = tag.Value.Substring(tagDirective.Prefix.Length); break; } } } private void StateMachine(ParsingEvent evt) { if (evt is YamlDotNet.Core.Events.Comment comment) { EmitComment(comment); return; } switch (state) { case EmitterState.StreamStart: EmitStreamStart(evt); break; case EmitterState.FirstDocumentStart: EmitDocumentStart(evt, isFirst: true); break; case EmitterState.DocumentStart: EmitDocumentStart(evt, isFirst: false); break; case EmitterState.DocumentContent: EmitDocumentContent(evt); break; case EmitterState.DocumentEnd: EmitDocumentEnd(evt); break; case EmitterState.FlowSequenceFirstItem: EmitFlowSequenceItem(evt, isFirst: true); break; case EmitterState.FlowSequenceItem: EmitFlowSequenceItem(evt, isFirst: false); break; case EmitterState.FlowMappingFirstKey: EmitFlowMappingKey(evt, isFirst: true); break; case EmitterState.FlowMappingKey: EmitFlowMappingKey(evt, isFirst: false); break; case EmitterState.FlowMappingSimpleValue: EmitFlowMappingValue(evt, isSimple: true); break; case EmitterState.FlowMappingValue: EmitFlowMappingValue(evt, isSimple: false); break; case EmitterState.BlockSequenceFirstItem: EmitBlockSequenceItem(evt, isFirst: true); break; case EmitterState.BlockSequenceItem: EmitBlockSequenceItem(evt, isFirst: false); break; case EmitterState.BlockMappingFirstKey: EmitBlockMappingKey(evt, isFirst: true); break; case EmitterState.BlockMappingKey: EmitBlockMappingKey(evt, isFirst: false); break; case EmitterState.BlockMappingSimpleValue: EmitBlockMappingValue(evt, isSimple: true); break; case EmitterState.BlockMappingValue: EmitBlockMappingValue(evt, isSimple: false); break; case EmitterState.StreamEnd: throw new YamlException("Expected nothing after STREAM-END"); default: throw new InvalidOperationException(); } } private void EmitComment(YamlDotNet.Core.Events.Comment comment) { if (flowLevel > 0 || state == EmitterState.FlowMappingFirstKey || state == EmitterState.FlowSequenceFirstItem) { return; } string[] array = comment.Value.Split(newLineSeparators, StringSplitOptions.None); if (comment.IsInline) { Write(" # "); Write(string.Join(" ", array)); } else { bool flag = state == EmitterState.BlockMappingFirstKey; if (flag) { IncreaseIndent(isFlow: false, isIndentless: false); } string[] array2 = array; foreach (string value in array2) { WriteIndent(); Write("# "); Write(value); WriteBreak(); } if (flag) { indent = indents.Pop(); } } isIndentation = true; } private void EmitStreamStart(ParsingEvent evt) { if (!(evt is YamlDotNet.Core.Events.StreamStart)) { throw new ArgumentException("Expected STREAM-START.", "evt"); } indent = -1; column = 0; isWhitespace = true; isIndentation = true; state = EmitterState.FirstDocumentStart; } private void EmitDocumentStart(ParsingEvent evt, bool isFirst) { if (evt is YamlDotNet.Core.Events.DocumentStart documentStart) { bool flag = documentStart.IsImplicit && isFirst && !isCanonical; TagDirectiveCollection tagDirectiveCollection = NonDefaultTagsAmong(documentStart.Tags); if (!isFirst && !isDocumentEndWritten && (documentStart.Version != null || tagDirectiveCollection.Count > 0)) { isDocumentEndWritten = false; WriteIndicator("...", needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); } if (documentStart.Version != null) { AnalyzeVersionDirective(documentStart.Version); Version version = documentStart.Version.Version; flag = false; WriteIndicator("%YAML", needWhitespace: true, whitespace: false, indentation: false); WriteIndicator(string.Format(CultureInfo.InvariantCulture, "{0}.{1}", version.Major, version.Minor), needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); } foreach (TagDirective item in tagDirectiveCollection) { AppendTagDirectiveTo(item, allowDuplicates: false, tagDirectives); } TagDirective[] defaultTagDirectives = Constants.DefaultTagDirectives; for (int i = 0; i < defaultTagDirectives.Length; i++) { AppendTagDirectiveTo(defaultTagDirectives[i], allowDuplicates: true, tagDirectives); } if (tagDirectiveCollection.Count > 0) { flag = false; defaultTagDirectives = Constants.DefaultTagDirectives; for (int i = 0; i < defaultTagDirectives.Length; i++) { AppendTagDirectiveTo(defaultTagDirectives[i], allowDuplicates: true, tagDirectiveCollection); } foreach (TagDirective item2 in tagDirectiveCollection) { WriteIndicator("%TAG", needWhitespace: true, whitespace: false, indentation: false); WriteTagHandle(item2.Handle); WriteTagContent(item2.Prefix, needsWhitespace: true); WriteIndent(); } } if (CheckEmptyDocument()) { flag = false; } if (!flag) { WriteIndent(); WriteIndicator("---", needWhitespace: true, whitespace: false, indentation: false); if (isCanonical) { WriteIndent(); } } state = EmitterState.DocumentContent; } else { if (!(evt is YamlDotNet.Core.Events.StreamEnd)) { throw new YamlException("Expected DOCUMENT-START or STREAM-END"); } state = EmitterState.StreamEnd; } } private TagDirectiveCollection NonDefaultTagsAmong(IEnumerable? tagCollection) { TagDirectiveCollection tagDirectiveCollection = new TagDirectiveCollection(); if (tagCollection == null) { return tagDirectiveCollection; } foreach (TagDirective item2 in tagCollection) { AppendTagDirectiveTo(item2, allowDuplicates: false, tagDirectiveCollection); } TagDirective[] defaultTagDirectives = Constants.DefaultTagDirectives; foreach (TagDirective item in defaultTagDirectives) { tagDirectiveCollection.Remove(item); } return tagDirectiveCollection; } private void AnalyzeVersionDirective(VersionDirective versionDirective) { if (versionDirective.Version.Major != 1 || versionDirective.Version.Minor > 3) { throw new YamlException("Incompatible %YAML directive"); } } private static void AppendTagDirectiveTo(TagDirective value, bool allowDuplicates, TagDirectiveCollection tagDirectives) { if (tagDirectives.Contains(value)) { if (!allowDuplicates) { throw new YamlException("Duplicate %TAG directive."); } } else { tagDirectives.Add(value); } } private void EmitDocumentContent(ParsingEvent evt) { states.Push(EmitterState.DocumentEnd); EmitNode(evt, isMapping: false, isSimpleKey: false); } private void EmitNode(ParsingEvent evt, bool isMapping, bool isSimpleKey) { isMappingContext = isMapping; isSimpleKeyContext = isSimpleKey; switch (evt.Type) { case EventType.Alias: EmitAlias(); break; case EventType.Scalar: EmitScalar(evt); break; case EventType.SequenceStart: EmitSequenceStart(evt); break; case EventType.MappingStart: EmitMappingStart(evt); break; default: throw new YamlException($"Expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, got {evt.Type}"); } } private void EmitAlias() { ProcessAnchor(); state = states.Pop(); } private void EmitScalar(ParsingEvent evt) { SelectScalarStyle(evt); ProcessAnchor(); ProcessTag(); IncreaseIndent(isFlow: true, isIndentless: false); ProcessScalar(); indent = indents.Pop(); state = states.Pop(); } private void SelectScalarStyle(ParsingEvent evt) { YamlDotNet.Core.Events.Scalar scalar = (YamlDotNet.Core.Events.Scalar)evt; ScalarStyle scalarStyle = scalar.Style; bool flag = tagData.Handle == null && tagData.Suffix == null; if (flag && !scalar.IsPlainImplicit && !scalar.IsQuotedImplicit) { throw new YamlException("Neither tag nor isImplicit flags are specified."); } if (scalarStyle == ScalarStyle.Any) { scalarStyle = ((!scalarData.IsMultiline) ? ScalarStyle.Plain : ScalarStyle.Folded); } if (isCanonical) { scalarStyle = ScalarStyle.DoubleQuoted; } if (isSimpleKeyContext && scalarData.IsMultiline) { scalarStyle = ScalarStyle.DoubleQuoted; } if (scalarStyle == ScalarStyle.Plain) { if ((flowLevel != 0 && !scalarData.IsFlowPlainAllowed) || (flowLevel == 0 && !scalarData.IsBlockPlainAllowed)) { scalarStyle = ((scalarData.IsSingleQuotedAllowed && !scalarData.HasSingleQuotes) ? ScalarStyle.SingleQuoted : ScalarStyle.DoubleQuoted); } if (string.IsNullOrEmpty(scalarData.Value) && (flowLevel != 0 || isSimpleKeyContext)) { scalarStyle = ScalarStyle.SingleQuoted; } if (flag && !scalar.IsPlainImplicit) { scalarStyle = ScalarStyle.SingleQuoted; } } if (scalarStyle == ScalarStyle.SingleQuoted && !scalarData.IsSingleQuotedAllowed) { scalarStyle = ScalarStyle.DoubleQuoted; } if ((scalarStyle == ScalarStyle.Literal || scalarStyle == ScalarStyle.Folded) && (!scalarData.IsBlockAllowed || flowLevel != 0 || isSimpleKeyContext)) { scalarStyle = ScalarStyle.DoubleQuoted; } scalarData.Style = scalarStyle; } private void ProcessScalar() { switch (scalarData.Style) { case ScalarStyle.Plain: WritePlainScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.SingleQuoted: WriteSingleQuotedScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.DoubleQuoted: WriteDoubleQuotedScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.Literal: WriteLiteralScalar(scalarData.Value); break; case ScalarStyle.Folded: WriteFoldedScalar(scalarData.Value); break; default: throw new InvalidOperationException(); } } private void WritePlainScalar(string value, bool allowBreaks) { if (!isWhitespace) { Write(' '); } bool flag = false; bool flag2 = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsSpace(c)) { if (allowBreaks && !flag && column > bestWidth && i + 1 < value.Length && value[i + 1] != ' ') { WriteIndent(); } else { Write(c); } flag = true; continue; } if (IsBreak(c, out var breakChar)) { if (!flag2 && c == '\n') { WriteBreak(); } WriteBreak(breakChar); isIndentation = true; flag2 = true; continue; } if (flag2) { WriteIndent(); } Write(c); isIndentation = false; flag = false; flag2 = false; } isWhitespace = false; isIndentation = false; } private void WriteSingleQuotedScalar(string value, bool allowBreaks) { WriteIndicator("'", needWhitespace: true, whitespace: false, indentation: false); bool flag = false; bool flag2 = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (c == ' ') { if (allowBreaks && !flag && column > bestWidth && i != 0 && i + 1 < value.Length && value[i + 1] != ' ') { WriteIndent(); } else { Write(c); } flag = true; continue; } if (IsBreak(c, out var breakChar)) { if (!flag2 && c == '\n') { WriteBreak(); } WriteBreak(breakChar); isIndentation = true; flag2 = true; continue; } if (flag2) { WriteIndent(); } if (c == '\'') { Write(c); } Write(c); isIndentation = false; flag = false; flag2 = false; } WriteIndicator("'", needWhitespace: false, whitespace: false, indentation: false); isWhitespace = false; isIndentation = false; } private void WriteDoubleQuotedScalar(string value, bool allowBreaks) { WriteIndicator("\"", needWhitespace: true, whitespace: false, indentation: false); bool flag = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsPrintable(c) && !IsBreak(c, out var _)) { switch (c) { case '"': case '\\': break; case ' ': if (allowBreaks && !flag && column > bestWidth && i > 0 && i + 1 < value.Length) { WriteIndent(); if (value[i + 1] == ' ') { Write('\\'); } } else { Write(c); } flag = true; continue; default: Write(c); flag = false; continue; } } Write('\\'); switch (c) { case '\0': Write('0'); break; case '\a': Write('a'); break; case '\b': Write('b'); break; case '\t': Write('t'); break; case '\n': Write('n'); break; case '\v': Write('v'); break; case '\f': Write('f'); break; case '\r': Write('r'); break; case '\u001b': Write('e'); break; case '"': Write('"'); break; case '\\': Write('\\'); break; case '\u0085': Write('N'); break; case '\u00a0': Write('_'); break; case '\u2028': Write('L'); break; case '\u2029': Write('P'); break; default: { ushort num = c; if (num <= 255) { Write('x'); Write(num.ToString("X02", CultureInfo.InvariantCulture)); } else if (IsHighSurrogate(c)) { if (i + 1 >= value.Length || !IsLowSurrogate(value[i + 1])) { throw new SyntaxErrorException("While writing a quoted scalar, found an orphaned high surrogate."); } Write('U'); Write(char.ConvertToUtf32(c, value[i + 1]).ToString("X08", CultureInfo.InvariantCulture)); i++; } else { Write('u'); Write(num.ToString("X04", CultureInfo.InvariantCulture)); } break; } } flag = false; } WriteIndicator("\"", needWhitespace: false, whitespace: false, indentation: false); isWhitespace = false; isIndentation = false; } private void WriteLiteralScalar(string value) { bool flag = true; WriteIndicator("|", needWhitespace: true, whitespace: false, indentation: false); WriteBlockScalarHints(value); WriteBreak(); isIndentation = true; isWhitespace = true; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (c == '\r' && i + 1 < value.Length && value[i + 1] == '\n') { continue; } if (IsBreak(c, out var breakChar)) { WriteBreak(breakChar); isIndentation = true; flag = true; continue; } if (flag) { WriteIndent(); } Write(c); isIndentation = false; flag = false; } } private void WriteFoldedScalar(string value) { bool flag = true; bool flag2 = true; WriteIndicator(">", needWhitespace: true, whitespace: false, indentation: false); WriteBlockScalarHints(value); WriteBreak(); isIndentation = true; isWhitespace = true; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsBreak(c, out var breakChar)) { if (c == '\r' && i + 1 < value.Length && value[i + 1] == '\n') { continue; } if (!flag && !flag2 && breakChar == '\n') { int j; char breakChar2; for (j = 0; i + j < value.Length && IsBreak(value[i + j], out breakChar2); j++) { } if (i + j < value.Length && !IsBlank(value[i + j]) && !IsBreak(value[i + j], out breakChar2)) { WriteBreak(); } } WriteBreak(breakChar); isIndentation = true; flag = true; } else { if (flag) { WriteIndent(); flag2 = IsBlank(c); } if (!flag && c == ' ' && i + 1 < value.Length && value[i + 1] != ' ' && column > bestWidth) { WriteIndent(); } else { Write(c); } isIndentation = false; flag = false; } } } private static bool IsSpace(char character) { return character == ' '; } private static bool IsBreak(char character, out char breakChar) { switch (character) { case '\n': case '\r': case '\u0085': breakChar = '\n'; return true; case '\u2028': case '\u2029': breakChar = character; return true; default: breakChar = '\0'; return false; } } private static bool IsBlank(char character) { if (character != ' ') { return character == '\t'; } return true; } private static bool IsPrintable(char character) { switch (character) { default: if (character != '\u0085' && (character < '\u00a0' || character > '\ud7ff')) { if (character >= '\ue000') { return character <= '\ufffd'; } return false; } break; case '\t': case '\n': case '\r': case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case '\\': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': break; } return true; } private static bool IsHighSurrogate(char c) { if ('\ud800' <= c) { return c <= '\udbff'; } return false; } private static bool IsLowSurrogate(char c) { if ('\udc00' <= c) { return c <= '\udfff'; } return false; } private void EmitSequenceStart(ParsingEvent evt) { ProcessAnchor(); ProcessTag(); SequenceStart sequenceStart = (SequenceStart)evt; if (flowLevel != 0 || isCanonical || sequenceStart.Style == SequenceStyle.Flow || CheckEmptySequence()) { state = EmitterState.FlowSequenceFirstItem; } else { state = EmitterState.BlockSequenceFirstItem; } } private void EmitMappingStart(ParsingEvent evt) { ProcessAnchor(); ProcessTag(); MappingStart mappingStart = (MappingStart)evt; if (flowLevel != 0 || isCanonical || mappingStart.Style == MappingStyle.Flow || CheckEmptyMapping()) { state = EmitterState.FlowMappingFirstKey; } else { state = EmitterState.BlockMappingFirstKey; } } private void ProcessAnchor() { if (!anchorData.Anchor.IsEmpty && !skipAnchorName) { WriteIndicator(anchorData.IsAlias ? "*" : "&", needWhitespace: true, whitespace: false, indentation: false); WriteAnchor(anchorData.Anchor); } } private void ProcessTag() { if (tagData.Handle == null && tagData.Suffix == null) { return; } if (tagData.Handle != null) { WriteTagHandle(tagData.Handle); if (tagData.Suffix != null) { WriteTagContent(tagData.Suffix, needsWhitespace: false); } } else { WriteIndicator("!<", needWhitespace: true, whitespace: false, indentation: false); WriteTagContent(tagData.Suffix, needsWhitespace: false); WriteIndicator(">", needWhitespace: false, whitespace: false, indentation: false); } } private void EmitDocumentEnd(ParsingEvent evt) { if (evt is YamlDotNet.Core.Events.DocumentEnd documentEnd) { WriteIndent(); if (!documentEnd.IsImplicit) { WriteIndicator("...", needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); isDocumentEndWritten = true; } state = EmitterState.DocumentStart; tagDirectives.Clear(); return; } throw new YamlException("Expected DOCUMENT-END."); } private void EmitFlowSequenceItem(ParsingEvent evt, bool isFirst) { if (isFirst) { WriteIndicator("[", needWhitespace: true, whitespace: true, indentation: false); IncreaseIndent(isFlow: true, isIndentless: false); flowLevel++; } if (evt is SequenceEnd) { flowLevel--; indent = indents.Pop(); if (isCanonical && !isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); WriteIndent(); } WriteIndicator("]", needWhitespace: false, whitespace: false, indentation: false); state = states.Pop(); } else { if (!isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); } if (isCanonical || column > bestWidth) { WriteIndent(); } states.Push(EmitterState.FlowSequenceItem); EmitNode(evt, isMapping: false, isSimpleKey: false); } } private void EmitFlowMappingKey(ParsingEvent evt, bool isFirst) { if (isFirst) { WriteIndicator("{", needWhitespace: true, whitespace: true, indentation: false); IncreaseIndent(isFlow: true, isIndentless: false); flowLevel++; } if (evt is MappingEnd) { flowLevel--; indent = indents.Pop(); if (isCanonical && !isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); WriteIndent(); } WriteIndicator("}", needWhitespace: false, whitespace: false, indentation: false); state = states.Pop(); return; } if (!isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); } if (isCanonical || column > bestWidth) { WriteIndent(); } if (!isCanonical && CheckSimpleKey()) { states.Push(EmitterState.FlowMappingSimpleValue); EmitNode(evt, isMapping: true, isSimpleKey: true); } else { WriteIndicator("?", needWhitespace: true, whitespace: false, indentation: false); states.Push(EmitterState.FlowMappingValue); EmitNode(evt, isMapping: true, isSimpleKey: false); } } private void EmitFlowMappingValue(ParsingEvent evt, bool isSimple) { if (isSimple) { WriteIndicator(":", needWhitespace: false, whitespace: false, indentation: false); } else { if (isCanonical || column > bestWidth) { WriteIndent(); } WriteIndicator(":", needWhitespace: true, whitespace: false, indentation: false); } states.Push(EmitterState.FlowMappingKey); EmitNode(evt, isMapping: true, isSimpleKey: false); } private void EmitBlockSequenceItem(ParsingEvent evt, bool isFirst) { if (isFirst) { IncreaseIndent(isFlow: false, isMappingContext && !isIndentation); } if (evt is SequenceEnd) { indent = indents.Pop(); state = states.Pop(); return; } WriteIndent(); WriteIndicator("-", needWhitespace: true, whitespace: false, indentation: true); states.Push(EmitterState.BlockSequenceItem); EmitNode(evt, isMapping: false, isSimpleKey: false); } private void EmitBlockMappingKey(ParsingEvent evt, bool isFirst) { if (isFirst) { IncreaseIndent(isFlow: false, isIndentless: false); } if (evt is MappingEnd) { indent = indents.Pop(); state = states.Pop(); return; } WriteIndent(); if (CheckSimpleKey()) { states.Push(EmitterState.BlockMappingSimpleValue); EmitNode(evt, isMapping: true, isSimpleKey: true); } else { WriteIndicator("?", needWhitespace: true, whitespace: false, indentation: true); states.Push(EmitterState.BlockMappingValue); EmitNode(evt, isMapping: true, isSimpleKey: false); } } private void EmitBlockMappingValue(ParsingEvent evt, bool isSimple) { if (isSimple) { WriteIndicator(":", needWhitespace: false, whitespace: false, indentation: false); } else { WriteIndent(); WriteIndicator(":", needWhitespace: true, whitespace: false, indentation: true); } states.Push(EmitterState.BlockMappingKey); EmitNode(evt, isMapping: true, isSimpleKey: false); } private void IncreaseIndent(bool isFlow, bool isIndentless) { indents.Push(indent); if (indent < 0) { indent = (isFlow ? bestIndent : 0); } else if (!isIndentless || !forceIndentLess) { indent += bestIndent; } } private bool CheckEmptyDocument() { int num = 0; foreach (ParsingEvent @event in events) { num++; if (num == 2) { if (@event is YamlDotNet.Core.Events.Scalar scalar) { return string.IsNullOrEmpty(scalar.Value); } break; } } return false; } private bool CheckSimpleKey() { if (events.Count < 1) { return false; } int num; switch (events.Peek().Type) { case EventType.Alias: num = AnchorNameLength(anchorData.Anchor); break; case EventType.Scalar: if (scalarData.IsMultiline) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix) + SafeStringLength(scalarData.Value); break; case EventType.SequenceStart: if (!CheckEmptySequence()) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix); break; case EventType.MappingStart: if (!CheckEmptySequence()) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix); break; default: return false; } return num <= maxSimpleKeyLength; } private int AnchorNameLength(AnchorName value) { if (!value.IsEmpty) { return value.Value.Length; } return 0; } private int SafeStringLength(string? value) { return value?.Length ?? 0; } private bool CheckEmptySequence() { return CheckEmptyStructure(); } private bool CheckEmptyMapping() { return CheckEmptyStructure(); } private bool CheckEmptyStructure() where TStart : NodeEvent where TEnd : ParsingEvent { if (events.Count < 2) { return false; } using Queue.Enumerator enumerator = events.GetEnumerator(); return enumerator.MoveNext() && enumerator.Current is TStart && enumerator.MoveNext() && enumerator.Current is TEnd; } private void WriteBlockScalarHints(string value) { CharacterAnalyzer characterAnalyzer = new CharacterAnalyzer(new StringLookAheadBuffer(value)); if (characterAnalyzer.IsSpace() || characterAnalyzer.IsBreak()) { int num = bestIndent; string indicator = num.ToString(CultureInfo.InvariantCulture); WriteIndicator(indicator, needWhitespace: false, whitespace: false, indentation: false); } string text = null; if (value.Length == 0 || !characterAnalyzer.IsBreak(value.Length - 1)) { text = "-"; } else if (value.Length >= 2 && characterAnalyzer.IsBreak(value.Length - 2)) { text = "+"; } if (text != null) { WriteIndicator(text, needWhitespace: false, whitespace: false, indentation: false); } } private void WriteIndicator(string indicator, bool needWhitespace, bool whitespace, bool indentation) { if (needWhitespace && !isWhitespace) { Write(' '); } Write(indicator); isWhitespace = whitespace; isIndentation &= indentation; } private void WriteIndent() { int num = Math.Max(indent, 0); if (!isIndentation || column > num || (column == num && !isWhitespace)) { WriteBreak(); } while (column < num) { Write(' '); } isWhitespace = true; isIndentation = true; } private void WriteAnchor(AnchorName value) { Write(value.Value); isWhitespace = false; isIndentation = false; } private void WriteTagHandle(string value) { if (!isWhitespace) { Write(' '); } Write(value); isWhitespace = false; isIndentation = false; } private void WriteTagContent(string value, bool needsWhitespace) { if (needsWhitespace && !isWhitespace) { Write(' '); } Write(UrlEncode(value)); isWhitespace = false; isIndentation = false; } private static string UrlEncode(string text) { return UriReplacer.Replace(text, delegate(Match match) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; byte[] bytes = Encoding.UTF8.GetBytes(match.Value); foreach (byte b in bytes) { builder.AppendFormat("%{0:X02}", b); } return builder.ToString(); } finally { ((IDisposable)builderWrapper).Dispose(); } }); } private void Write(char value) { output.Write(value); column++; } private void Write(string value) { output.Write(value); column += value.Length; } private void WriteBreak(char breakCharacter = '\n') { if (breakCharacter == '\n') { output.Write(newLine); } else { output.Write(breakCharacter); } column = 0; } } internal sealed class EmitterSettings { public static readonly EmitterSettings Default = new EmitterSettings(); public int BestIndent { get; } = 2; public int BestWidth { get; } = int.MaxValue; public string NewLine { get; } = Environment.NewLine; public bool IsCanonical { get; } public bool SkipAnchorName { get; private set; } public int MaxSimpleKeyLength { get; } = 1024; public bool IndentSequences { get; } public EmitterSettings() { } public EmitterSettings(int bestIndent, int bestWidth, bool isCanonical, int maxSimpleKeyLength, bool skipAnchorName = false, bool indentSequences = false, string? newLine = null) { if (bestIndent < 2 || bestIndent > 9) { throw new ArgumentOutOfRangeException("bestIndent", "BestIndent must be between 2 and 9, inclusive"); } if (bestWidth <= bestIndent * 2) { throw new ArgumentOutOfRangeException("bestWidth", "BestWidth must be greater than BestIndent x 2."); } if (maxSimpleKeyLength < 0) { throw new ArgumentOutOfRangeException("maxSimpleKeyLength", "MaxSimpleKeyLength must be >= 0"); } BestIndent = bestIndent; BestWidth = bestWidth; IsCanonical = isCanonical; MaxSimpleKeyLength = maxSimpleKeyLength; SkipAnchorName = skipAnchorName; IndentSequences = indentSequences; NewLine = newLine ?? Environment.NewLine; } public EmitterSettings WithBestIndent(int bestIndent) { return new EmitterSettings(bestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine); } public EmitterSettings WithBestWidth(int bestWidth) { return new EmitterSettings(BestIndent, bestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine); } public EmitterSettings WithMaxSimpleKeyLength(int maxSimpleKeyLength) { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, maxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine); } public EmitterSettings WithNewLine(string newLine) { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, newLine); } public EmitterSettings Canonical() { return new EmitterSettings(BestIndent, BestWidth, isCanonical: true, MaxSimpleKeyLength, SkipAnchorName); } public EmitterSettings WithoutAnchorName() { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, skipAnchorName: true, IndentSequences, NewLine); } public EmitterSettings WithIndentedSequences() { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, indentSequences: true, NewLine); } } internal enum EmitterState { StreamStart, StreamEnd, FirstDocumentStart, DocumentStart, DocumentContent, DocumentEnd, FlowSequenceFirstItem, FlowSequenceItem, FlowMappingFirstKey, FlowMappingKey, FlowMappingSimpleValue, FlowMappingValue, BlockSequenceFirstItem, BlockSequenceItem, BlockMappingFirstKey, BlockMappingKey, BlockMappingSimpleValue, BlockMappingValue } internal sealed class ForwardAnchorNotSupportedException : YamlException { public ForwardAnchorNotSupportedException(string message) : base(message) { } public ForwardAnchorNotSupportedException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public ForwardAnchorNotSupportedException(string message, Exception inner) : base(message, inner) { } } internal static class HashCode { public static int CombineHashCodes(int h1, int h2) { return ((h1 << 5) + h1) ^ h2; } public static int CombineHashCodes(int h1, object? o2) { return CombineHashCodes(h1, GetHashCode(o2)); } private static int GetHashCode(object? obj) { return obj?.GetHashCode() ?? 0; } } internal interface IEmitter { void Emit(ParsingEvent @event); } internal interface ILookAheadBuffer { bool EndOfInput { get; } char Peek(int offset); void Skip(int length); } internal sealed class InsertionQueue : IEnumerable, IEnumerable { private const int DefaultInitialCapacity = 128; private T[] items; private int readPtr; private int writePtr; private int mask; private int count; public int Count => count; public int Capacity => items.Length; public InsertionQueue(int initialCapacity = 128) { if (initialCapacity <= 0) { throw new ArgumentOutOfRangeException("initialCapacity", "The initial capacity must be a positive number."); } if (!initialCapacity.IsPowerOfTwo()) { throw new ArgumentException("The initial capacity must be a power of 2.", "initialCapacity"); } items = new T[initialCapacity]; readPtr = initialCapacity / 2; writePtr = initialCapacity / 2; mask = initialCapacity - 1; } public void Enqueue(T item) { ResizeIfNeeded(); items[writePtr] = item; writePtr = (writePtr - 1) & mask; count++; } public T Dequeue() { if (count == 0) { throw new InvalidOperationException("The queue is empty"); } T result = items[readPtr]; readPtr = (readPtr - 1) & mask; count--; return result; } public void Insert(int index, T item) { if (index > count) { throw new InvalidOperationException("Cannot insert outside of the bounds of the queue"); } ResizeIfNeeded(); CalculateInsertionParameters(mask, count, index, ref readPtr, ref writePtr, out var insertPtr, out var copyIndex, out var copyOffset, out var copyLength); if (copyLength != 0) { Array.Copy(items, copyIndex, items, copyIndex + copyOffset, copyLength); } items[insertPtr] = item; count++; } private void ResizeIfNeeded() { int num = items.Length; if (count == num) { T[] destinationArray = new T[num * 2]; int num2 = readPtr + 1; if (num2 > 0) { Array.Copy(items, 0, destinationArray, 0, num2); } writePtr += num; int num3 = num - num2; if (num3 > 0) { Array.Copy(items, readPtr + 1, destinationArray, writePtr + 1, num3); } items = destinationArray; mask = mask * 2 + 1; } } internal static void CalculateInsertionParameters(int mask, int count, int index, ref int readPtr, ref int writePtr, out int insertPtr, out int copyIndex, out int copyOffset, out int copyLength) { int num = (readPtr + 1) & mask; if (index == 0) { insertPtr = (readPtr = num); copyIndex = 0; copyOffset = 0; copyLength = 0; return; } insertPtr = (readPtr - index) & mask; if (index == count) { writePtr = (writePtr - 1) & mask; copyIndex = 0; copyOffset = 0; copyLength = 0; return; } int num2 = ((num >= insertPtr) ? (readPtr - insertPtr) : int.MaxValue); int num3 = ((writePtr <= insertPtr) ? (insertPtr - writePtr) : int.MaxValue); if (num2 <= num3) { insertPtr++; readPtr++; copyIndex = insertPtr; copyOffset = 1; copyLength = num2; } else { copyIndex = writePtr + 1; copyOffset = -1; copyLength = num3; writePtr = (writePtr - 1) & mask; } } public IEnumerator GetEnumerator() { int ptr = readPtr; for (int i = 0; i < Count; i++) { yield return items[ptr]; ptr = (ptr - 1) & mask; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal interface IParser { ParsingEvent? Current { get; } bool MoveNext(); } internal interface IScanner { Mark CurrentPosition { get; } Token? Current { get; } bool MoveNext(); bool MoveNextWithoutConsuming(); void ConsumeCurrent(); } [DebuggerStepThrough] internal sealed class LookAheadBuffer : ILookAheadBuffer { private readonly TextReader input; private readonly char[] buffer; private readonly int blockSize; private readonly int mask; private int firstIndex; private int writeOffset; private int count; private bool endOfInput; public bool EndOfInput { get { if (endOfInput) { return count == 0; } return false; } } public LookAheadBuffer(TextReader input, int capacity) { if (capacity < 1) { throw new ArgumentOutOfRangeException("capacity", "The capacity must be positive."); } if (!capacity.IsPowerOfTwo()) { throw new ArgumentException("The capacity must be a power of 2.", "capacity"); } this.input = input ?? throw new ArgumentNullException("input"); blockSize = capacity; buffer = new char[capacity * 2]; mask = capacity * 2 - 1; } private int GetIndexForOffset(int offset) { return (firstIndex + offset) & mask; } public char Peek(int offset) { if (offset >= count) { FillBuffer(); } if (offset < count) { return buffer[(firstIndex + offset) & mask]; } return '\0'; } public void Cache(int length) { if (length >= count) { FillBuffer(); } } private void FillBuffer() { if (endOfInput) { return; } int num = blockSize; do { int num2 = input.Read(buffer, writeOffset, num); if (num2 == 0) { endOfInput = true; return; } num -= num2; writeOffset += num2; count += num2; } while (num > 0); if (writeOffset == buffer.Length) { writeOffset = 0; } } public void Skip(int length) { if (length < 1 || length > blockSize) { throw new ArgumentOutOfRangeException("length", "The length must be between 1 and the number of characters in the buffer. Use the Peek() and / or Cache() methods to fill the buffer."); } firstIndex = GetIndexForOffset(length); count -= length; } } internal readonly struct Mark : IEquatable, IComparable, IComparable { public static readonly Mark Empty = new Mark(0, 1, 1); public int Index { get; } public int Line { get; } public int Column { get; } public Mark(int index, int line, int column) { if (index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException("index", "Index must be greater than or equal to zero."); } if (line < 1) { ThrowHelper.ThrowArgumentOutOfRangeException("line", "Line must be greater than or equal to 1."); } if (column < 1) { ThrowHelper.ThrowArgumentOutOfRangeException("column", "Column must be greater than or equal to 1."); } Index = index; Line = line; Column = column; } public override string ToString() { return $"Line: {Line}, Col: {Column}, Idx: {Index}"; } public override bool Equals(object? obj) { return Equals((Mark)(obj ?? ((object)Empty))); } public bool Equals(Mark other) { if (Index == other.Index && Line == other.Line) { return Column == other.Column; } return false; } public override int GetHashCode() { return HashCode.CombineHashCodes(Index.GetHashCode(), HashCode.CombineHashCodes(Line.GetHashCode(), Column.GetHashCode())); } public int CompareTo(object? obj) { return CompareTo((Mark)(obj ?? ((object)Empty))); } public int CompareTo(Mark other) { int num = Line.CompareTo(other.Line); if (num == 0) { num = Column.CompareTo(other.Column); } return num; } } internal sealed class MaximumRecursionLevelReachedException : YamlException { public MaximumRecursionLevelReachedException(string message) : base(message) { } public MaximumRecursionLevelReachedException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public MaximumRecursionLevelReachedException(string message, Exception inner) : base(message, inner) { } } internal sealed class MergingParser : IParser { private sealed class ParsingEventCollection : IEnumerable>, IEnumerable { private readonly LinkedList events; private readonly HashSet> deleted; private readonly Dictionary> references; public ParsingEventCollection() { events = new LinkedList(); deleted = new HashSet>(); references = new Dictionary>(); } public void AddAfter(LinkedListNode node, IEnumerable items) { foreach (ParsingEvent item in items) { node = events.AddAfter(node, item); } } public void Add(ParsingEvent item) { LinkedListNode node = events.AddLast(item); AddReference(item, node); } public void MarkDeleted(LinkedListNode node) { deleted.Add(node); } public void CleanMarked() { foreach (LinkedListNode item in deleted) { events.Remove(item); } } public IEnumerable> FromAnchor(AnchorName anchor) { LinkedListNode next = references[anchor].Next; return Enumerate(next); } public IEnumerator> GetEnumerator() { return Enumerate(events.First).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private IEnumerable> Enumerate(LinkedListNode? node) { while (node != null) { yield return node; node = node.Next; } } private void AddReference(ParsingEvent item, LinkedListNode node) { if (item is MappingStart mappingStart) { AnchorName anchor = mappingStart.Anchor; if (!anchor.IsEmpty) { references[anchor] = node; } } } } private sealed class ParsingEventCloner : IParsingEventVisitor { private ParsingEvent? clonedEvent; public ParsingEvent Clone(ParsingEvent e) { e.Accept(this); if (clonedEvent == null) { throw new InvalidOperationException($"Could not clone event of type '{e.Type}'"); } return clonedEvent; } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.AnchorAlias e) { clonedEvent = new YamlDotNet.Core.Events.AnchorAlias(e.Value, e.Start, e.End); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.StreamStart e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.StreamEnd e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.DocumentStart e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.DocumentEnd e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.Scalar e) { clonedEvent = new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, e.Tag, e.Value, e.Style, e.IsPlainImplicit, e.IsQuotedImplicit, e.Start, e.End); } void IParsingEventVisitor.Visit(SequenceStart e) { clonedEvent = new SequenceStart(AnchorName.Empty, e.Tag, e.IsImplicit, e.Style, e.Start, e.End); } void IParsingEventVisitor.Visit(SequenceEnd e) { Mark start = e.Start; Mark end = e.End; clonedEvent = new SequenceEnd(in start, in end); } void IParsingEventVisitor.Visit(MappingStart e) { clonedEvent = new MappingStart(AnchorName.Empty, e.Tag, e.IsImplicit, e.Style, e.Start, e.End); } void IParsingEventVisitor.Visit(MappingEnd e) { Mark start = e.Start; Mark end = e.End; clonedEvent = new MappingEnd(in start, in end); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.Comment e) { throw new NotSupportedException(); } } private readonly ParsingEventCollection events; private readonly IParser innerParser; private IEnumerator> iterator; private bool merged; public ParsingEvent? Current => iterator.Current?.Value; public MergingParser(IParser innerParser) { events = new ParsingEventCollection(); merged = false; iterator = events.GetEnumerator(); this.innerParser = innerParser; } public bool MoveNext() { if (!merged) { Merge(); events.CleanMarked(); iterator = events.GetEnumerator(); merged = true; } return iterator.MoveNext(); } private void Merge() { while (innerParser.MoveNext()) { events.Add(innerParser.Current); } foreach (LinkedListNode @event in events) { if (IsMergeToken(@event)) { events.MarkDeleted(@event); if (!HandleMerge(@event.Next)) { Mark start = @event.Value.Start; Mark end = @event.Value.End; throw new SemanticErrorException(in start, in end, "Unrecognized merge key pattern"); } } } } private bool HandleMerge(LinkedListNode? node) { if (node == null) { return false; } if (node.Value is YamlDotNet.Core.Events.AnchorAlias anchorAlias) { return HandleAnchorAlias(node, node, anchorAlias); } if (node.Value is SequenceStart) { return HandleSequence(node); } return false; } private bool HandleMergeSequence(LinkedListNode sequenceStart, LinkedListNode? node) { if (node == null) { return false; } if (node.Value is YamlDotNet.Core.Events.AnchorAlias anchorAlias) { return HandleAnchorAlias(sequenceStart, node, anchorAlias); } if (node.Value is SequenceStart) { return HandleSequence(node); } return false; } private bool IsMergeToken(LinkedListNode node) { if (node.Value is YamlDotNet.Core.Events.Scalar scalar) { return scalar.Value == "<<"; } return false; } private bool HandleAnchorAlias(LinkedListNode node, LinkedListNode anchorNode, YamlDotNet.Core.Events.AnchorAlias anchorAlias) { IEnumerable mappingEvents = GetMappingEvents(anchorAlias.Value); events.AddAfter(node, mappingEvents); events.MarkDeleted(anchorNode); return true; } private bool HandleSequence(LinkedListNode node) { events.MarkDeleted(node); LinkedListNode linkedListNode = node; while (linkedListNode != null) { if (linkedListNode.Value is SequenceEnd && linkedListNode.Value.Start.Line >= node.Value.Start.Line) { events.MarkDeleted(linkedListNode); return true; } LinkedListNode next = linkedListNode.Next; HandleMergeSequence(node, next); linkedListNode = next; } return true; } private IEnumerable GetMappingEvents(AnchorName anchor) { ParsingEventCloner cloner = new ParsingEventCloner(); int nesting = 0; return from e in (from e in events.FromAnchor(anchor) select e.Value).TakeWhile((ParsingEvent e) => (nesting += e.NestingIncrease) >= 0) select cloner.Clone(e); } } internal class Parser : IParser { private class EventQueue { private readonly Queue highPriorityEvents = new Queue(); private readonly Queue normalPriorityEvents = new Queue(); public int Count => highPriorityEvents.Count + normalPriorityEvents.Count; public void Enqueue(ParsingEvent @event) { EventType type = @event.Type; if (type == EventType.StreamStart || type == EventType.DocumentStart) { highPriorityEvents.Enqueue(@event); } else { normalPriorityEvents.Enqueue(@event); } } public ParsingEvent Dequeue() { if (highPriorityEvents.Count <= 0) { return normalPriorityEvents.Dequeue(); } return highPriorityEvents.Dequeue(); } } private readonly Stack states = new Stack(); private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection(); private ParserState state; private readonly IScanner scanner; private Token? currentToken; private VersionDirective? version; private readonly EventQueue pendingEvents = new EventQueue(); public ParsingEvent? Current { get; private set; } private Token? GetCurrentToken() { if (currentToken == null) { while (scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (!(currentToken is YamlDotNet.Core.Tokens.Comment comment)) { break; } pendingEvents.Enqueue(new YamlDotNet.Core.Events.Comment(comment.Value, comment.IsInline, comment.Start, comment.End)); scanner.ConsumeCurrent(); } } return currentToken; } public Parser(TextReader input) : this(new Scanner(input)) { } public Parser(IScanner scanner) { this.scanner = scanner; } public bool MoveNext() { if (state == ParserState.StreamEnd) { Current = null; return false; } if (pendingEvents.Count == 0) { pendingEvents.Enqueue(StateMachine()); } Current = pendingEvents.Dequeue(); return true; } private ParsingEvent StateMachine() { return state switch { ParserState.StreamStart => ParseStreamStart(), ParserState.ImplicitDocumentStart => ParseDocumentStart(isImplicit: true), ParserState.DocumentStart => ParseDocumentStart(isImplicit: false), ParserState.DocumentContent => ParseDocumentContent(), ParserState.DocumentEnd => ParseDocumentEnd(), ParserState.BlockNode => ParseNode(isBlock: true, isIndentlessSequence: false), ParserState.BlockNodeOrIndentlessSequence => ParseNode(isBlock: true, isIndentlessSequence: true), ParserState.FlowNode => ParseNode(isBlock: false, isIndentlessSequence: false), ParserState.BlockSequenceFirstEntry => ParseBlockSequenceEntry(isFirst: true), ParserState.BlockSequenceEntry => ParseBlockSequenceEntry(isFirst: false), ParserState.IndentlessSequenceEntry => ParseIndentlessSequenceEntry(), ParserState.BlockMappingFirstKey => ParseBlockMappingKey(isFirst: true), ParserState.BlockMappingKey => ParseBlockMappingKey(isFirst: false), ParserState.BlockMappingValue => ParseBlockMappingValue(), ParserState.FlowSequenceFirstEntry => ParseFlowSequenceEntry(isFirst: true), ParserState.FlowSequenceEntry => ParseFlowSequenceEntry(isFirst: false), ParserState.FlowSequenceEntryMappingKey => ParseFlowSequenceEntryMappingKey(), ParserState.FlowSequenceEntryMappingValue => ParseFlowSequenceEntryMappingValue(), ParserState.FlowSequenceEntryMappingEnd => ParseFlowSequenceEntryMappingEnd(), ParserState.FlowMappingFirstKey => ParseFlowMappingKey(isFirst: true), ParserState.FlowMappingKey => ParseFlowMappingKey(isFirst: false), ParserState.FlowMappingValue => ParseFlowMappingValue(isEmpty: false), ParserState.FlowMappingEmptyValue => ParseFlowMappingValue(isEmpty: true), _ => throw new InvalidOperationException(), }; } private void Skip() { if (currentToken != null) { currentToken = null; scanner.ConsumeCurrent(); } } private ParsingEvent ParseStreamStart() { Token token = GetCurrentToken(); Mark start; Mark end; if (!(token is YamlDotNet.Core.Tokens.StreamStart streamStart)) { start = token?.Start ?? Mark.Empty; end = token?.End ?? Mark.Empty; throw new SemanticErrorException(in start, in end, "Did not find expected ."); } Skip(); state = ParserState.ImplicitDocumentStart; start = streamStart.Start; end = streamStart.End; return new YamlDotNet.Core.Events.StreamStart(in start, in end); } private ParsingEvent ParseDocumentStart(bool isImplicit) { if (currentToken is VersionDirective) { throw new SyntaxErrorException("While parsing a document start node, could not find document end marker before version directive."); } Token token = GetCurrentToken(); if (!isImplicit) { while (token is YamlDotNet.Core.Tokens.DocumentEnd) { Skip(); token = GetCurrentToken(); } } if (token == null) { throw new SyntaxErrorException("Reached the end of the stream while parsing a document start."); } if (token is YamlDotNet.Core.Tokens.Scalar && (state == ParserState.ImplicitDocumentStart || state == ParserState.DocumentStart)) { isImplicit = true; } if ((isImplicit && !(token is VersionDirective) && !(token is TagDirective) && !(token is YamlDotNet.Core.Tokens.DocumentStart) && !(token is YamlDotNet.Core.Tokens.StreamEnd) && !(token is YamlDotNet.Core.Tokens.DocumentEnd)) || token is BlockMappingStart) { TagDirectiveCollection tags = new TagDirectiveCollection(); ProcessDirectives(tags); states.Push(ParserState.DocumentEnd); state = ParserState.BlockNode; return new YamlDotNet.Core.Events.DocumentStart(null, tags, isImplicit: true, token.Start, token.End); } Mark start2; Mark end; if (!(token is YamlDotNet.Core.Tokens.StreamEnd) && !(token is YamlDotNet.Core.Tokens.DocumentEnd)) { Mark start = token.Start; TagDirectiveCollection tags2 = new TagDirectiveCollection(); VersionDirective? versionDirective = ProcessDirectives(tags2); token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document start"); if (!(token is YamlDotNet.Core.Tokens.DocumentStart)) { start2 = token.Start; end = token.End; throw new SemanticErrorException(in start2, in end, "Did not find expected ."); } states.Push(ParserState.DocumentEnd); state = ParserState.DocumentContent; Mark end2 = token.End; Skip(); return new YamlDotNet.Core.Events.DocumentStart(versionDirective, tags2, isImplicit: false, start, end2); } if (token is YamlDotNet.Core.Tokens.DocumentEnd) { Skip(); } state = ParserState.StreamEnd; token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document start"); start2 = token.Start; end = token.End; YamlDotNet.Core.Events.StreamEnd result = new YamlDotNet.Core.Events.StreamEnd(in start2, in end); if (scanner.MoveNextWithoutConsuming()) { throw new InvalidOperationException("The scanner should contain no more tokens."); } return result; } private VersionDirective? ProcessDirectives(TagDirectiveCollection tags) { bool flag = false; VersionDirective result = null; while (true) { if (GetCurrentToken() is VersionDirective versionDirective) { if (version != null) { Mark start = versionDirective.Start; Mark end = versionDirective.End; throw new SemanticErrorException(in start, in end, "Found duplicate %YAML directive."); } if (versionDirective.Version.Major != 1 || versionDirective.Version.Minor > 3) { Mark start = versionDirective.Start; Mark end = versionDirective.End; throw new SemanticErrorException(in start, in end, "Found incompatible YAML document."); } result = (version = versionDirective); flag = true; } else { if (!(GetCurrentToken() is TagDirective tagDirective)) { break; } if (tags.Contains(tagDirective.Handle)) { Mark start = tagDirective.Start; Mark end = tagDirective.End; throw new SemanticErrorException(in start, in end, "Found duplicate %TAG directive."); } tags.Add(tagDirective); flag = true; } Skip(); } if (GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart && (version == null || (version.Version.Major == 1 && version.Version.Minor > 1))) { if (GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart && version == null) { version = new VersionDirective(new Version(1, 2)); } flag = true; } AddTagDirectives(tags, Constants.DefaultTagDirectives); if (flag) { tagDirectives.Clear(); } AddTagDirectives(tagDirectives, tags); return result; } private static void AddTagDirectives(TagDirectiveCollection directives, IEnumerable source) { foreach (TagDirective item in source) { if (!directives.Contains(item)) { directives.Add(item); } } } private ParsingEvent ParseDocumentContent() { if (GetCurrentToken() is VersionDirective || GetCurrentToken() is TagDirective || GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart || GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentEnd || GetCurrentToken() is YamlDotNet.Core.Tokens.StreamEnd) { state = states.Pop(); Mark position = scanner.CurrentPosition; return ProcessEmptyScalar(in position); } return ParseNode(isBlock: true, isIndentlessSequence: false); } private static ParsingEvent ProcessEmptyScalar(in Mark position) { return new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, string.Empty, ScalarStyle.Plain, isPlainImplicit: true, isQuotedImplicit: false, position, position); } private ParsingEvent ParseNode(bool isBlock, bool isIndentlessSequence) { Mark start; Mark end; if (GetCurrentToken() is Error error) { start = error.Start; end = error.End; throw new SemanticErrorException(in start, in end, error.Value); } Token token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a node"); if (token is YamlDotNet.Core.Tokens.AnchorAlias anchorAlias) { state = states.Pop(); YamlDotNet.Core.Events.AnchorAlias result = new YamlDotNet.Core.Events.AnchorAlias(anchorAlias.Value, anchorAlias.Start, anchorAlias.End); Skip(); return result; } Mark start2 = token.Start; AnchorName anchor = AnchorName.Empty; TagName tag = TagName.Empty; Anchor anchor2 = null; Tag tag2 = null; while (true) { if (anchor.IsEmpty && token is Anchor anchor3) { anchor2 = anchor3; anchor = anchor3.Value; Skip(); } else { if (!tag.IsEmpty || !(token is Tag tag3)) { if (token is Anchor anchor4) { start = anchor4.Start; end = anchor4.End; throw new SemanticErrorException(in start, in end, "While parsing a node, found more than one anchor."); } if (token is YamlDotNet.Core.Tokens.AnchorAlias anchorAlias2) { start = anchorAlias2.Start; end = anchorAlias2.End; throw new SemanticErrorException(in start, in end, "While parsing a node, did not find expected token."); } if (!(token is Error error2)) { break; } if (tag2 != null && anchor2 != null && !anchor.IsEmpty) { return new YamlDotNet.Core.Events.Scalar(anchor, default(TagName), string.Empty, ScalarStyle.Any, isPlainImplicit: false, isQuotedImplicit: false, anchor2.Start, anchor2.End); } start = error2.Start; end = error2.End; throw new SemanticErrorException(in start, in end, error2.Value); } tag2 = tag3; if (string.IsNullOrEmpty(tag3.Handle)) { tag = new TagName(tag3.Suffix); } else { if (!tagDirectives.Contains(tag3.Handle)) { start = tag3.Start; end = tag3.End; throw new SemanticErrorException(in start, in end, "While parsing a node, found undefined tag handle."); } tag = new TagName(tagDirectives[tag3.Handle].Prefix + tag3.Suffix); } Skip(); } token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a node"); } bool isEmpty = tag.IsEmpty; if (isIndentlessSequence && GetCurrentToken() is BlockEntry) { state = ParserState.IndentlessSequenceEntry; return new SequenceStart(anchor, tag, isEmpty, SequenceStyle.Block, start2, token.End); } if (token is YamlDotNet.Core.Tokens.Scalar scalar) { bool isPlainImplicit = false; bool isQuotedImplicit = false; if ((scalar.Style == ScalarStyle.Plain && tag.IsEmpty) || tag.IsNonSpecific) { isPlainImplicit = true; } else if (tag.IsEmpty) { isQuotedImplicit = true; } state = states.Pop(); Skip(); YamlDotNet.Core.Events.Scalar result2 = new YamlDotNet.Core.Events.Scalar(anchor, tag, scalar.Value, scalar.Style, isPlainImplicit, isQuotedImplicit, start2, scalar.End, scalar.IsKey); if (!anchor.IsEmpty && scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (currentToken is Error) { Error error3 = currentToken as Error; start = error3.Start; end = error3.End; throw new SemanticErrorException(in start, in end, error3.Value); } } if (state == ParserState.FlowMappingKey && scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (currentToken != null && !(currentToken is FlowEntry) && !(currentToken is FlowMappingEnd)) { start = currentToken.Start; end = currentToken.End; throw new SemanticErrorException(in start, in end, "While parsing a flow mapping, did not find expected ',' or '}'."); } } return result2; } if (token is FlowSequenceStart flowSequenceStart) { state = ParserState.FlowSequenceFirstEntry; return new SequenceStart(anchor, tag, isEmpty, SequenceStyle.Flow, start2, flowSequenceStart.End); } if (token is FlowMappingStart flowMappingStart) { state = ParserState.FlowMappingFirstKey; return new MappingStart(anchor, tag, isEmpty, MappingStyle.Flow, start2, flowMappingStart.End); } if (isBlock) { if (token is BlockSequenceStart blockSequenceStart) { state = ParserState.BlockSequenceFirstEntry; return new SequenceStart(anchor, tag, isEmpty, SequenceStyle.Block, start2, blockSequenceStart.End); } if (token is BlockMappingStart blockMappingStart) { state = ParserState.BlockMappingFirstKey; return new MappingStart(anchor, tag, isEmpty, MappingStyle.Block, start2, blockMappingStart.End); } } if (!anchor.IsEmpty || !tag.IsEmpty) { state = states.Pop(); return new YamlDotNet.Core.Events.Scalar(anchor, tag, string.Empty, ScalarStyle.Plain, isEmpty, isQuotedImplicit: false, start2, token.End); } start = token.Start; end = token.End; throw new SemanticErrorException(in start, in end, "While parsing a node, did not find expected node content."); } private ParsingEvent ParseDocumentEnd() { Token token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document end"); bool isImplicit = true; Mark start = token.Start; Mark end = start; if (token is YamlDotNet.Core.Tokens.DocumentEnd) { end = token.End; Skip(); isImplicit = false; } else if (!(currentToken is YamlDotNet.Core.Tokens.StreamEnd) && !(currentToken is YamlDotNet.Core.Tokens.DocumentStart) && !(currentToken is FlowSequenceEnd) && !(currentToken is VersionDirective) && (!(Current is YamlDotNet.Core.Events.Scalar) || !(currentToken is Error))) { throw new SemanticErrorException(in start, in end, "Did not find expected ."); } if (version != null && version.Version.Major == 1 && version.Version.Minor > 1) { version = null; } state = ParserState.DocumentStart; return new YamlDotNet.Core.Events.DocumentEnd(isImplicit, start, end); } private ParsingEvent ParseBlockSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); if (token is BlockEntry blockEntry) { Mark position = blockEntry.End; Skip(); token = GetCurrentToken(); if (!(token is BlockEntry) && !(token is BlockEnd)) { states.Push(ParserState.BlockSequenceEntry); return ParseNode(isBlock: true, isIndentlessSequence: false); } state = ParserState.BlockSequenceEntry; return ProcessEmptyScalar(in position); } Mark start; Mark end; if (token is BlockEnd blockEnd) { state = states.Pop(); start = blockEnd.Start; end = blockEnd.End; SequenceEnd result = new SequenceEnd(in start, in end); Skip(); return result; } start = token?.Start ?? Mark.Empty; end = token?.End ?? Mark.Empty; throw new SemanticErrorException(in start, in end, "While parsing a block collection, did not find expected '-' indicator."); } private ParsingEvent ParseIndentlessSequenceEntry() { Token token = GetCurrentToken(); if (token is BlockEntry blockEntry) { Mark position = blockEntry.End; Skip(); token = GetCurrentToken(); if (!(token is BlockEntry) && !(token is Key) && !(token is Value) && !(token is BlockEnd)) { states.Push(ParserState.IndentlessSequenceEntry); return ParseNode(isBlock: true, isIndentlessSequence: false); } state = ParserState.IndentlessSequenceEntry; return ProcessEmptyScalar(in position); } state = states.Pop(); Mark start = token?.Start ?? Mark.Empty; Mark end = token?.End ?? Mark.Empty; return new SequenceEnd(in start, in end); } private ParsingEvent ParseBlockMappingKey(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); if (token is Key key) { Mark position = key.End; Skip(); token = GetCurrentToken(); if (!(token is Key) && !(token is Value) && !(token is BlockEnd)) { states.Push(ParserState.BlockMappingValue); return ParseNode(isBlock: true, isIndentlessSequence: true); } state = ParserState.BlockMappingValue; return ProcessEmptyScalar(in position); } Mark position2; if (token is Value value) { Skip(); position2 = value.End; return ProcessEmptyScalar(in position2); } if (token is YamlDotNet.Core.Tokens.AnchorAlias anchorAlias) { Skip(); return new YamlDotNet.Core.Events.AnchorAlias(anchorAlias.Value, anchorAlias.Start, anchorAlias.End); } Mark end; if (token is BlockEnd blockEnd) { state = states.Pop(); position2 = blockEnd.Start; end = blockEnd.End; MappingEnd result = new MappingEnd(in position2, in end); Skip(); return result; } if (GetCurrentToken() is Error error) { position2 = error.Start; end = error.End; throw new SyntaxErrorException(in position2, in end, error.Value); } position2 = token?.Start ?? Mark.Empty; end = token?.End ?? Mark.Empty; throw new SemanticErrorException(in position2, in end, "While parsing a block mapping, did not find expected key."); } private ParsingEvent ParseBlockMappingValue() { Token token = GetCurrentToken(); if (token is Value value) { Mark position = value.End; Skip(); token = GetCurrentToken(); if (!(token is Key) && !(token is Value) && !(token is BlockEnd)) { states.Push(ParserState.BlockMappingKey); return ParseNode(isBlock: true, isIndentlessSequence: true); } state = ParserState.BlockMappingKey; return ProcessEmptyScalar(in position); } Mark start; if (token is Error error) { start = error.Start; Mark end = error.End; throw new SemanticErrorException(in start, in end, error.Value); } state = ParserState.BlockMappingKey; start = token?.Start ?? Mark.Empty; return ProcessEmptyScalar(in start); } private ParsingEvent ParseFlowSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); Mark start; Mark end; if (!(token is FlowSequenceEnd)) { if (!isFirst) { if (!(token is FlowEntry)) { start = token?.Start ?? Mark.Empty; end = token?.End ?? Mark.Empty; throw new SemanticErrorException(in start, in end, "While parsing a flow sequence, did not find expected ',' or ']'."); } Skip(); token = GetCurrentToken(); } if (token is Key) { state = ParserState.FlowSequenceEntryMappingKey; MappingStart result = new MappingStart(AnchorName.Empty, TagName.Empty, isImplicit: true, MappingStyle.Flow); Skip(); return result; } if (!(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntry); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = states.Pop(); start = token?.Start ?? Mark.Empty; end = token?.End ?? Mark.Empty; SequenceEnd result2 = new SequenceEnd(in start, in end); Skip(); return result2; } private ParsingEvent ParseFlowSequenceEntryMappingKey() { Token token = GetCurrentToken(); if (!(token is Value) && !(token is FlowEntry) && !(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntryMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } Mark position = token?.End ?? Mark.Empty; Skip(); state = ParserState.FlowSequenceEntryMappingValue; return ProcessEmptyScalar(in position); } private ParsingEvent ParseFlowSequenceEntryMappingValue() { Token token = GetCurrentToken(); if (token is Value) { Skip(); token = GetCurrentToken(); if (!(token is FlowEntry) && !(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntryMappingEnd); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = ParserState.FlowSequenceEntryMappingEnd; Mark position = token?.Start ?? Mark.Empty; return ProcessEmptyScalar(in position); } private ParsingEvent ParseFlowSequenceEntryMappingEnd() { state = ParserState.FlowSequenceEntry; Token token = GetCurrentToken(); Mark start = token?.Start ?? Mark.Empty; Mark end = token?.End ?? Mark.Empty; return new MappingEnd(in start, in end); } private ParsingEvent ParseFlowMappingKey(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); Mark start; Mark end; if (!(token is FlowMappingEnd)) { if (!isFirst) { if (token is FlowEntry) { Skip(); token = GetCurrentToken(); } else if (!(token is YamlDotNet.Core.Tokens.Scalar)) { start = token?.Start ?? Mark.Empty; end = token?.End ?? Mark.Empty; throw new SemanticErrorException(in start, in end, "While parsing a flow mapping, did not find expected ',' or '}'."); } } if (token is Key) { Skip(); token = GetCurrentToken(); if (!(token is Value) && !(token is FlowEntry) && !(token is FlowMappingEnd)) { states.Push(ParserState.FlowMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } state = ParserState.FlowMappingValue; start = token?.Start ?? Mark.Empty; return ProcessEmptyScalar(in start); } if (token is YamlDotNet.Core.Tokens.Scalar) { states.Push(ParserState.FlowMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } if (!(token is FlowMappingEnd)) { states.Push(ParserState.FlowMappingEmptyValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = states.Pop(); Skip(); start = token?.Start ?? Mark.Empty; end = token?.End ?? Mark.Empty; return new MappingEnd(in start, in end); } private ParsingEvent ParseFlowMappingValue(bool isEmpty) { Token token = GetCurrentToken(); if (!isEmpty && token is Value) { Skip(); token = GetCurrentToken(); if (!(token is FlowEntry) && !(token is FlowMappingEnd)) { states.Push(ParserState.FlowMappingKey); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = ParserState.FlowMappingKey; if (!isEmpty && token is YamlDotNet.Core.Tokens.Scalar scalar) { Skip(); return new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, scalar.Value, scalar.Style, isPlainImplicit: false, isQuotedImplicit: false, token.Start, scalar.End); } Mark position = token?.Start ?? Mark.Empty; return ProcessEmptyScalar(in position); } } internal static class ParserExtensions { public static T Consume(this IParser parser) where T : ParsingEvent { T result = parser.Require(); parser.MoveNext(); return result; } public static bool TryConsume(this IParser parser, [MaybeNullWhen(false)] out T @event) where T : ParsingEvent { if (parser.Accept(out @event)) { parser.MoveNext(); return true; } return false; } public static T Require(this IParser parser) where T : ParsingEvent { if (!parser.Accept(out var @event)) { ParsingEvent current = parser.Current; if (current == null) { throw new YamlException("Expected '" + typeof(T).Name + "', got nothing."); } Mark start = current.Start; Mark end = current.End; throw new YamlException(in start, in end, $"Expected '{typeof(T).Name}', got '{current.GetType().Name}' (at {current.Start})."); } return @event; } public static bool Accept(this IParser parser, [MaybeNullWhen(false)] out T @event) where T : ParsingEvent { if (parser.Current == null && !parser.MoveNext()) { throw new EndOfStreamException(); } if (parser.Current is T val) { @event = val; return true; } @event = null; return false; } public static void SkipThisAndNestedEvents(this IParser parser) { int num = 0; do { ParsingEvent parsingEvent = parser.Consume(); num += parsingEvent.NestingIncrease; } while (num > 0); } [Obsolete("Please use Consume() instead")] public static T Expect(this IParser parser) where T : ParsingEvent { return parser.Consume(); } [Obsolete("Please use TryConsume(out var evt) instead")] [return: MaybeNull] public static T? Allow(this IParser parser) where T : ParsingEvent { if (!parser.TryConsume(out var @event)) { return null; } return @event; } [Obsolete("Please use Accept(out var evt) instead")] [return: MaybeNull] public static T? Peek(this IParser parser) where T : ParsingEvent { if (!parser.Accept(out var @event)) { return null; } return @event; } [Obsolete("Please use TryConsume(out var evt) or Accept(out var evt) instead")] public static bool Accept(this IParser parser) where T : ParsingEvent { T @event; return parser.Accept(out @event); } public static bool TryFindMappingEntry(this IParser parser, Func selector, [MaybeNullWhen(false)] out YamlDotNet.Core.Events.Scalar? key, [MaybeNullWhen(false)] out ParsingEvent? value) { if (parser.TryConsume(out var _)) { while (parser.Current != null) { ParsingEvent current = parser.Current; if (!(current is YamlDotNet.Core.Events.Scalar scalar)) { if (current is MappingStart || current is SequenceStart) { parser.SkipThisAndNestedEvents(); } else { parser.MoveNext(); } continue; } bool num = selector(scalar); parser.MoveNext(); if (num) { value = parser.Current; key = scalar; return true; } parser.SkipThisAndNestedEvents(); } } key = null; value = null; return false; } } internal enum ParserState { StreamStart, StreamEnd, ImplicitDocumentStart, DocumentStart, DocumentContent, DocumentEnd, BlockNode, BlockNodeOrIndentlessSequence, FlowNode, BlockSequenceFirstEntry, BlockSequenceEntry, IndentlessSequenceEntry, BlockMappingFirstKey, BlockMappingKey, BlockMappingValue, FlowSequenceFirstEntry, FlowSequenceEntry, FlowSequenceEntryMappingKey, FlowSequenceEntryMappingValue, FlowSequenceEntryMappingEnd, FlowMappingFirstKey, FlowMappingKey, FlowMappingValue, FlowMappingEmptyValue } internal sealed class RecursionLevel { private int current; public int Maximum { get; } public RecursionLevel(int maximum) { Maximum = maximum; } public void Increment() { if (!TryIncrement()) { throw new MaximumRecursionLevelReachedException("Maximum level of recursion reached"); } } public bool TryIncrement() { if (current < Maximum) { current++; return true; } return false; } public void Decrement() { if (current == 0) { throw new InvalidOperationException("Attempted to decrement RecursionLevel to a negative value"); } current--; } } internal enum ScalarStyle { Any, Plain, SingleQuoted, DoubleQuoted, Literal, Folded } internal class Scanner : IScanner { private const int MaxVersionNumberLength = 9; private static readonly SortedDictionary SimpleEscapeCodes = new SortedDictionary { { '0', '\0' }, { 'a', '\a' }, { 'b', '\b' }, { 't', '\t' }, { '\t', '\t' }, { 'n', '\n' }, { 'v', '\v' }, { 'f', '\f' }, { 'r', '\r' }, { 'e', '\u001b' }, { ' ', ' ' }, { '"', '"' }, { '\\', '\\' }, { '/', '/' }, { 'N', '\u0085' }, { '_', '\u00a0' }, { 'L', '\u2028' }, { 'P', '\u2029' } }; private readonly Stack indents = new Stack(); private readonly InsertionQueue tokens = new InsertionQueue(); private readonly Stack simpleKeys = new Stack(); private readonly CharacterAnalyzer analyzer; private readonly Cursor cursor; private bool streamStartProduced; private bool streamEndProduced; private bool plainScalarFollowedByComment; private int flowSequenceStartLine; private bool flowCollectionFetched; private bool startFlowCollectionFetched; private int indent = -1; private bool flowScalarFetched; private bool simpleKeyAllowed; private int flowLevel; private int tokensParsed; private bool tokenAvailable; private Token? previous; private Anchor? previousAnchor; private YamlDotNet.Core.Tokens.Scalar? lastScalar; private static readonly byte[] EmptyBytes = new byte[0]; public bool SkipComments { get; private set; } public Token? Current { get; private set; } public Mark CurrentPosition => cursor.Mark(); private bool IsDocumentStart() { if (!analyzer.EndOfInput && cursor.LineOffset == 0 && analyzer.Check('-') && analyzer.Check('-', 1) && analyzer.Check('-', 2)) { return analyzer.IsWhiteBreakOrZero(3); } return false; } private bool IsDocumentEnd() { if (!analyzer.EndOfInput && cursor.LineOffset == 0 && analyzer.Check('.') && analyzer.Check('.', 1) && analyzer.Check('.', 2)) { return analyzer.IsWhiteBreakOrZero(3); } return false; } private bool IsDocumentIndicator() { if (!IsDocumentStart()) { return IsDocumentEnd(); } return true; } public Scanner(TextReader input, bool skipComments = true) { analyzer = new CharacterAnalyzer(new LookAheadBuffer(input, 1024)); cursor = new Cursor(); SkipComments = skipComments; } public bool MoveNext() { if (Current != null) { ConsumeCurrent(); } return MoveNextWithoutConsuming(); } public bool MoveNextWithoutConsuming() { if (!tokenAvailable && !streamEndProduced) { FetchMoreTokens(); } if (tokens.Count > 0) { Current = tokens.Dequeue(); tokenAvailable = false; return true; } Current = null; return false; } public void ConsumeCurrent() { tokensParsed++; tokenAvailable = false; previous = Current; Current = null; } private char ReadCurrentCharacter() { char result = analyzer.Peek(0); Skip(); return result; } private char ReadLine() { if (analyzer.Check("\r\n\u0085")) { SkipLine(); return '\n'; } char result = analyzer.Peek(0); SkipLine(); return result; } private void FetchMoreTokens() { while (true) { bool flag = false; if (tokens.Count == 0) { flag = true; } else { foreach (SimpleKey simpleKey in simpleKeys) { if (simpleKey.IsPossible && simpleKey.TokenNumber == tokensParsed) { flag = true; break; } } } if (!flag) { break; } FetchNextToken(); } tokenAvailable = true; } private static bool StartsWith(StringBuilder what, char start) { if (what.Length > 0) { return what[0] == start; } return false; } private void StaleSimpleKeys() { foreach (SimpleKey simpleKey in simpleKeys) { if (simpleKey.IsPossible && (simpleKey.Line < cursor.Line || simpleKey.Index + 1024 < cursor.Index)) { if (simpleKey.IsRequired) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning a simple key, could not find expected ':'.", mark, mark)); } simpleKey.MarkAsImpossible(); } } } private void FetchNextToken() { if (!streamStartProduced) { FetchStreamStart(); return; } ScanToNextToken(); StaleSimpleKeys(); UnrollIndent(cursor.LineOffset); analyzer.Buffer.Cache(4); if (analyzer.Buffer.EndOfInput) { lastScalar = null; FetchStreamEnd(); } if (cursor.LineOffset == 0 && analyzer.Check('%')) { lastScalar = null; FetchDirective(); return; } if (IsDocumentStart()) { lastScalar = null; FetchDocumentIndicator(isStartToken: true); return; } if (IsDocumentEnd()) { lastScalar = null; FetchDocumentIndicator(isStartToken: false); return; } if (analyzer.Check('[')) { lastScalar = null; FetchFlowCollectionStart(isSequenceToken: true); return; } if (analyzer.Check('{')) { lastScalar = null; FetchFlowCollectionStart(isSequenceToken: false); return; } if (analyzer.Check(']')) { lastScalar = null; FetchFlowCollectionEnd(isSequenceToken: true); return; } if (analyzer.Check('}')) { lastScalar = null; FetchFlowCollectionEnd(isSequenceToken: false); return; } if (analyzer.Check(',')) { lastScalar = null; FetchFlowEntry(); return; } if (analyzer.Check('-')) { if (analyzer.IsWhiteBreakOrZero(1)) { FetchBlockEntry(); return; } if (flowLevel > 0 && analyzer.Check(",[]{}", 1)) { tokens.Enqueue(new Error("Invalid key indicator format.", cursor.Mark(), cursor.Mark())); } } if (analyzer.Check('?') && (flowLevel > 0 || analyzer.IsWhiteBreakOrZero(1)) && analyzer.IsWhiteBreakOrZero(1)) { FetchKey(); } else if (analyzer.Check(':') && (flowLevel > 0 || analyzer.IsWhiteBreakOrZero(1)) && (!simpleKeyAllowed || flowLevel <= 0) && (!flowScalarFetched || !analyzer.Check(':', 1)) && (analyzer.IsWhiteBreakOrZero(1) || analyzer.Check(',', 1) || flowScalarFetched || flowCollectionFetched || startFlowCollectionFetched)) { if (lastScalar != null) { lastScalar.IsKey = true; lastScalar = null; } FetchValue(); } else if (analyzer.Check('*')) { FetchAnchor(isAlias: true); } else if (analyzer.Check('&')) { FetchAnchor(isAlias: false); } else if (analyzer.Check('!')) { FetchTag(); } else if (analyzer.Check('|') && flowLevel == 0) { FetchBlockScalar(isLiteral: true); } else if (analyzer.Check('>') && flowLevel == 0) { FetchBlockScalar(isLiteral: false); } else if (analyzer.Check('\'')) { FetchFlowScalar(isSingleQuoted: true); } else if (analyzer.Check('"')) { FetchFlowScalar(isSingleQuoted: false); } else if ((!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("-?:,[]{}#&*!|>'\"%@`")) || (analyzer.Check('-') && !analyzer.IsWhite(1)) || (analyzer.Check("?:") && !analyzer.IsWhiteBreakOrZero(1)) || (simpleKeyAllowed && flowLevel > 0)) { if (plainScalarFollowedByComment) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning plain scalar, found a comment between adjacent scalars.", mark, mark)); } if ((flowScalarFetched || (flowCollectionFetched && !startFlowCollectionFetched)) && analyzer.Check(':')) { Skip(); } flowScalarFetched = false; flowCollectionFetched = false; startFlowCollectionFetched = false; plainScalarFollowedByComment = false; FetchPlainScalar(); } else { if (simpleKeyAllowed && indent >= cursor.LineOffset && analyzer.IsTab()) { throw new SyntaxErrorException("While scanning a mapping, found invalid tab as indentation."); } if (!analyzer.IsWhiteBreakOrZero()) { Mark start = cursor.Mark(); Skip(); Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning for the next token, found character that cannot start any token."); } Skip(); } } private bool CheckWhiteSpace() { if (!analyzer.Check(' ')) { if (flowLevel > 0 || !simpleKeyAllowed) { return analyzer.Check('\t'); } return false; } return true; } private void Skip() { cursor.Skip(); analyzer.Buffer.Skip(1); } private void SkipLine() { if (analyzer.IsCrLf()) { cursor.SkipLineByOffset(2); analyzer.Buffer.Skip(2); } else if (analyzer.IsBreak()) { cursor.SkipLineByOffset(1); analyzer.Buffer.Skip(1); } else if (!analyzer.IsZero()) { throw new InvalidOperationException("Not at a break."); } } private void ScanToNextToken() { while (true) { if (CheckWhiteSpace()) { Skip(); continue; } ProcessComment(); if (analyzer.IsBreak()) { SkipLine(); if (flowLevel == 0) { simpleKeyAllowed = true; } continue; } break; } } private void ProcessComment() { if (!analyzer.Check('#')) { return; } Mark start = cursor.Mark(); Skip(); while (analyzer.IsSpace()) { Skip(); } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; while (!analyzer.IsBreakOrZero()) { builder.Append(ReadCurrentCharacter()); } if (!SkipComments) { bool isInline = previous != null && previous.End.Line == start.Line && previous.End.Column != 1 && !(previous is YamlDotNet.Core.Tokens.StreamStart); tokens.Enqueue(new YamlDotNet.Core.Tokens.Comment(builder.ToString(), isInline, start, cursor.Mark())); } } finally { ((IDisposable)builderWrapper).Dispose(); } } private void FetchStreamStart() { simpleKeys.Push(new SimpleKey()); simpleKeyAllowed = true; streamStartProduced = true; Mark start = cursor.Mark(); tokens.Enqueue(new YamlDotNet.Core.Tokens.StreamStart(in start, in start)); } private void UnrollIndent(int column) { if (flowLevel == 0) { while (indent > column) { Mark start = cursor.Mark(); tokens.Enqueue(new BlockEnd(in start, in start)); indent = indents.Pop(); } } } private void FetchStreamEnd() { cursor.ForceSkipLineAfterNonBreak(); UnrollIndent(-1); RemoveSimpleKey(); simpleKeyAllowed = false; streamEndProduced = true; Mark start = cursor.Mark(); tokens.Enqueue(new YamlDotNet.Core.Tokens.StreamEnd(in start, in start)); } private void FetchDirective() { UnrollIndent(-1); RemoveSimpleKey(); simpleKeyAllowed = false; Token token = ScanDirective(); if (token != null) { tokens.Enqueue(token); } } private Token? ScanDirective() { Mark start = cursor.Mark(); Skip(); string text = ScanDirectiveName(in start); Token result; if (!(text == "YAML")) { if (!(text == "TAG")) { while (!analyzer.EndOfInput && !analyzer.Check('#') && !analyzer.IsBreak()) { Skip(); } return null; } result = ScanTagDirectiveValue(in start); } else { if (!(previous is YamlDotNet.Core.Tokens.DocumentStart) && !(previous is YamlDotNet.Core.Tokens.StreamStart) && !(previous is YamlDotNet.Core.Tokens.DocumentEnd)) { Mark end = cursor.Mark(); throw new SemanticErrorException(in start, in end, "While scanning a version directive, did not find preceding ."); } result = ScanVersionDirectiveValue(in start); } while (analyzer.IsWhite()) { Skip(); } ProcessComment(); if (!analyzer.IsBreakOrZero()) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a directive, did not find expected comment or line break."); } if (analyzer.IsBreak()) { SkipLine(); } return result; } private void FetchDocumentIndicator(bool isStartToken) { UnrollIndent(-1); RemoveSimpleKey(); simpleKeyAllowed = false; Mark end = cursor.Mark(); Skip(); Skip(); Skip(); if (isStartToken) { InsertionQueue insertionQueue = tokens; Mark end2 = cursor.Mark(); insertionQueue.Enqueue(new YamlDotNet.Core.Tokens.DocumentStart(in end, in end2)); return; } Token token = null; while (!analyzer.EndOfInput && !analyzer.IsBreak() && !analyzer.Check('#')) { if (!analyzer.IsWhite()) { token = new Error("While scanning a document end, found invalid content after '...' marker.", end, cursor.Mark()); break; } Skip(); } tokens.Enqueue(new YamlDotNet.Core.Tokens.DocumentEnd(in end, in end)); if (token != null) { tokens.Enqueue(token); } } private void FetchFlowCollectionStart(bool isSequenceToken) { SaveSimpleKey(); IncreaseFlowLevel(); simpleKeyAllowed = true; Mark start = cursor.Mark(); Skip(); Token token; if (isSequenceToken) { token = new FlowSequenceStart(in start, in start); flowSequenceStartLine = token.Start.Line; } else { token = new FlowMappingStart(in start, in start); } tokens.Enqueue(token); startFlowCollectionFetched = true; } private void IncreaseFlowLevel() { simpleKeys.Push(new SimpleKey()); flowLevel++; } private void FetchFlowCollectionEnd(bool isSequenceToken) { RemoveSimpleKey(); DecreaseFlowLevel(); simpleKeyAllowed = false; Mark start = cursor.Mark(); Skip(); Token token = null; Token item; if (isSequenceToken) { if (analyzer.Check('#')) { token = new Error("While scanning a flow sequence end, found invalid comment after ']'.", start, start); } item = new FlowSequenceEnd(in start, in start); } else { item = new FlowMappingEnd(in start, in start); } tokens.Enqueue(item); if (token != null) { tokens.Enqueue(token); } flowCollectionFetched = true; } private void DecreaseFlowLevel() { if (flowLevel > 0) { flowLevel--; simpleKeys.Pop(); } } private void FetchFlowEntry() { RemoveSimpleKey(); simpleKeyAllowed = true; Mark start = cursor.Mark(); Skip(); Mark end = cursor.Mark(); if (analyzer.Check('#')) { tokens.Enqueue(new Error("While scanning a flow entry, found invalid comment after comma.", start, end)); } else { tokens.Enqueue(new FlowEntry(in start, in end)); } } private void FetchBlockEntry() { Mark start; if (flowLevel == 0) { if (!simpleKeyAllowed) { if (previousAnchor != null && previousAnchor.End.Line == cursor.Line) { start = previousAnchor.Start; Mark end = previousAnchor.End; throw new SemanticErrorException(in start, in end, "Anchor before sequence entry on same line is not allowed."); } Mark mark = cursor.Mark(); tokens.Enqueue(new Error("Block sequence entries are not allowed in this context.", mark, mark)); } RollIndent(cursor.LineOffset, -1, isSequence: true, cursor.Mark()); } RemoveSimpleKey(); simpleKeyAllowed = true; Mark start2 = cursor.Mark(); Skip(); InsertionQueue insertionQueue = tokens; start = cursor.Mark(); insertionQueue.Enqueue(new BlockEntry(in start2, in start)); } private void FetchKey() { if (flowLevel == 0) { if (!simpleKeyAllowed) { Mark start = cursor.Mark(); throw new SyntaxErrorException(in start, in start, "Mapping keys are not allowed in this context."); } RollIndent(cursor.LineOffset, -1, isSequence: false, cursor.Mark()); } RemoveSimpleKey(); simpleKeyAllowed = flowLevel == 0; Mark start2 = cursor.Mark(); Skip(); InsertionQueue insertionQueue = tokens; Mark end = cursor.Mark(); insertionQueue.Enqueue(new Key(in start2, in end)); } private void FetchValue() { SimpleKey simpleKey = simpleKeys.Peek(); Mark start; if (simpleKey.IsPossible) { InsertionQueue insertionQueue = tokens; int index = simpleKey.TokenNumber - tokensParsed; start = simpleKey.Mark; Mark end = simpleKey.Mark; insertionQueue.Insert(index, new Key(in start, in end)); RollIndent(simpleKey.LineOffset, simpleKey.TokenNumber, isSequence: false, simpleKey.Mark); simpleKey.MarkAsImpossible(); simpleKeyAllowed = false; } else { bool flag = flowLevel == 0; if (flag) { if (!simpleKeyAllowed) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("Mapping values are not allowed in this context.", mark, mark)); return; } RollIndent(cursor.LineOffset, -1, isSequence: false, cursor.Mark()); if (cursor.LineOffset == 0 && simpleKey.LineOffset == 0) { InsertionQueue insertionQueue2 = tokens; int count = tokens.Count; start = simpleKey.Mark; Mark end = simpleKey.Mark; insertionQueue2.Insert(count, new Key(in start, in end)); flag = false; } } simpleKeyAllowed = flag; } Mark start2 = cursor.Mark(); Skip(); InsertionQueue insertionQueue3 = tokens; start = cursor.Mark(); insertionQueue3.Enqueue(new Value(in start2, in start)); } private void RollIndent(int column, int number, bool isSequence, Mark position) { if (flowLevel <= 0 && indent < column) { indents.Push(indent); indent = column; Token item = ((!isSequence) ? ((Token)new BlockMappingStart(in position, in position)) : ((Token)new BlockSequenceStart(in position, in position))); if (number == -1) { tokens.Enqueue(item); } else { tokens.Insert(number - tokensParsed, item); } } } private void FetchAnchor(bool isAlias) { SaveSimpleKey(); simpleKeyAllowed = false; tokens.Enqueue(ScanAnchor(isAlias)); } private Token ScanAnchor(bool isAlias) { Mark start = cursor.Mark(); Skip(); bool flag = false; if (isAlias) { SimpleKey simpleKey = simpleKeys.Peek(); flag = simpleKey.IsRequired && simpleKey.IsPossible; } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; while (!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("[]{},") && (!flag || !analyzer.Check(':') || !analyzer.IsWhiteBreakOrZero(1))) { builder.Append(ReadCurrentCharacter()); } if (builder.Length == 0 || (!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("?:,]}%@`"))) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning an anchor or alias, found value containing disallowed: []{},"); } AnchorName value = new AnchorName(builder.ToString()); if (isAlias) { return new YamlDotNet.Core.Tokens.AnchorAlias(value, start, cursor.Mark()); } return previousAnchor = new Anchor(value, start, cursor.Mark()); } finally { ((IDisposable)builderWrapper).Dispose(); } } private void FetchTag() { SaveSimpleKey(); simpleKeyAllowed = false; tokens.Enqueue(ScanTag()); } private Token ScanTag() { Mark start = cursor.Mark(); string text; string text2; if (analyzer.Check('<', 1)) { text = string.Empty; Skip(); Skip(); text2 = ScanTagUri(null, start); if (!analyzer.Check('>')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag, did not find the expected '>'."); } Skip(); } else { string text3 = ScanTagHandle(isDirective: false, start); if (text3.Length > 1 && text3[0] == '!' && text3[text3.Length - 1] == '!') { text = text3; text2 = ScanTagUri(null, start); } else { text2 = ScanTagUri(text3, start); text = "!"; if (text2.Length == 0) { text2 = text; text = string.Empty; } } } if (!analyzer.IsWhiteBreakOrZero() && !analyzer.Check(',')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag, did not find expected whitespace, comma or line break."); } return new Tag(text, text2, start, cursor.Mark()); } private void FetchBlockScalar(bool isLiteral) { SaveSimpleKey(); simpleKeyAllowed = true; tokens.Enqueue(ScanBlockScalar(isLiteral)); } private Token ScanBlockScalar(bool isLiteral) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; StringBuilderPool.BuilderWrapper builderWrapper2 = StringBuilderPool.Rent(); try { StringBuilder builder2 = builderWrapper2.Builder; StringBuilderPool.BuilderWrapper builderWrapper3 = StringBuilderPool.Rent(); try { StringBuilder builder3 = builderWrapper3.Builder; int num = 0; int num2 = 0; int currentIndent = 0; bool flag = false; bool? isFirstLine = null; Mark start = cursor.Mark(); Skip(); if (analyzer.Check("+-")) { num = (analyzer.Check('+') ? 1 : (-1)); Skip(); if (analyzer.IsDigit()) { if (analyzer.Check('0')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a block scalar, found an indentation indicator equal to 0."); } num2 = analyzer.AsDigit(); Skip(); } } else if (analyzer.IsDigit()) { if (analyzer.Check('0')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a block scalar, found an indentation indicator equal to 0."); } num2 = analyzer.AsDigit(); Skip(); if (analyzer.Check("+-")) { num = (analyzer.Check('+') ? 1 : (-1)); Skip(); } } if (analyzer.Check('#')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a block scalar, found a comment without whtespace after '>' indicator."); } while (analyzer.IsWhite()) { Skip(); } ProcessComment(); if (!analyzer.IsBreakOrZero()) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a block scalar, did not find expected comment or line break."); } if (analyzer.IsBreak()) { SkipLine(); if (!isFirstLine.HasValue) { isFirstLine = true; } else if (isFirstLine == true) { isFirstLine = false; } } Mark end2 = cursor.Mark(); if (num2 != 0) { currentIndent = ((indent >= 0) ? (indent + num2) : num2); } currentIndent = ScanBlockScalarBreaks(currentIndent, builder3, isLiteral, ref end2, ref isFirstLine); isFirstLine = false; while (cursor.LineOffset == currentIndent && !analyzer.IsZero() && !IsDocumentEnd()) { bool flag2 = analyzer.IsWhite(); if (!isLiteral && StartsWith(builder2, '\n') && !flag && !flag2) { if (builder3.Length == 0) { builder.Append(' '); } builder2.Length = 0; } else { builder.Append(builder2.ToString()); builder2.Length = 0; } builder.Append(builder3.ToString()); builder3.Length = 0; flag = analyzer.IsWhite(); while (!analyzer.IsBreakOrZero()) { builder.Append(ReadCurrentCharacter()); } char c = ReadLine(); if (c != 0) { builder2.Append(c); } currentIndent = ScanBlockScalarBreaks(currentIndent, builder3, isLiteral, ref end2, ref isFirstLine); } if (num != -1) { builder.Append((object?)builder2); } if (num == 1) { builder.Append((object?)builder3); } ScalarStyle style = (isLiteral ? ScalarStyle.Literal : ScalarStyle.Folded); return new YamlDotNet.Core.Tokens.Scalar(builder.ToString(), style, start, end2); } finally { ((IDisposable)builderWrapper3).Dispose(); } } finally { ((IDisposable)builderWrapper2).Dispose(); } } finally { ((IDisposable)builderWrapper).Dispose(); } } private int ScanBlockScalarBreaks(int currentIndent, StringBuilder breaks, bool isLiteral, ref Mark end, ref bool? isFirstLine) { int num = 0; int num2 = -1; end = cursor.Mark(); while (true) { if ((currentIndent == 0 || cursor.LineOffset < currentIndent) && analyzer.IsSpace()) { Skip(); continue; } if (cursor.LineOffset > num) { num = cursor.LineOffset; } if (!analyzer.IsBreak()) { break; } if (isFirstLine == true) { isFirstLine = false; num2 = cursor.LineOffset; } breaks.Append(ReadLine()); end = cursor.Mark(); } if (isLiteral && isFirstLine == true) { int num3 = cursor.LineOffset; int num4 = 0; while (!analyzer.IsBreak(num4) && analyzer.IsSpace(num4)) { num4++; num3++; } if (analyzer.IsBreak(num4) && num3 > cursor.LineOffset) { isFirstLine = false; num2 = num3; } } if (isLiteral && num2 > 1 && currentIndent < num2 - 1) { Mark end2 = cursor.Mark(); throw new SemanticErrorException(in end, in end2, "While scanning a literal block scalar, found extra spaces in first line."); } if (!isLiteral && num > cursor.LineOffset && num2 > -1) { Mark end2 = cursor.Mark(); throw new SemanticErrorException(in end, in end2, "While scanning a literal block scalar, found more spaces in lines above first content line."); } if (currentIndent == 0 && (cursor.LineOffset > 0 || indent > -1)) { currentIndent = Math.Max(num, Math.Max(indent + 1, 1)); } return currentIndent; } private void FetchFlowScalar(bool isSingleQuoted) { SaveSimpleKey(); simpleKeyAllowed = false; flowScalarFetched = true; tokens.Enqueue(ScanFlowScalar(isSingleQuoted)); if (!isSingleQuoted && analyzer.Check('#')) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning a flow sequence end, found invalid comment after double-quoted scalar.", mark, mark)); } } private Token ScanFlowScalar(bool isSingleQuoted) { Mark start = cursor.Mark(); Skip(); StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; StringBuilderPool.BuilderWrapper builderWrapper2 = StringBuilderPool.Rent(); try { StringBuilder builder2 = builderWrapper2.Builder; StringBuilderPool.BuilderWrapper builderWrapper3 = StringBuilderPool.Rent(); try { StringBuilder builder3 = builderWrapper3.Builder; StringBuilderPool.BuilderWrapper builderWrapper4 = StringBuilderPool.Rent(); try { StringBuilder builder4 = builderWrapper4.Builder; bool flag = false; while (true) { if (IsDocumentIndicator()) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a quoted scalar, found unexpected document indicator."); } if (analyzer.IsZero()) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a quoted scalar, found unexpected end of stream."); } if (flag && !isSingleQuoted && indent >= cursor.LineOffset) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a multi-line double-quoted scalar, found wrong indentation."); } flag = false; while (!analyzer.IsWhiteBreakOrZero()) { if (isSingleQuoted && analyzer.Check('\'') && analyzer.Check('\'', 1)) { builder.Append('\''); Skip(); Skip(); continue; } if (analyzer.Check(isSingleQuoted ? '\'' : '"')) { break; } if (!isSingleQuoted && analyzer.Check('\\') && analyzer.IsBreak(1)) { Skip(); SkipLine(); flag = true; break; } if (!isSingleQuoted && analyzer.Check('\\')) { int num = 0; char c = analyzer.Peek(1); switch (c) { case 'x': num = 2; break; case 'u': num = 4; break; case 'U': num = 8; break; default: { if (SimpleEscapeCodes.TryGetValue(c, out var value)) { builder.Append(value); break; } Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a quoted scalar, found unknown escape character."); } } Skip(); Skip(); if (num <= 0) { continue; } int num2 = 0; for (int i = 0; i < num; i++) { if (!analyzer.IsHex(i)) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a quoted scalar, did not find expected hexadecimal number."); } num2 = (num2 << 4) + analyzer.AsHex(i); } if ((num2 >= 55296 && num2 <= 57343) || num2 > 1114111) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a quoted scalar, found invalid Unicode character escape code."); } builder.Append(char.ConvertFromUtf32(num2)); for (int j = 0; j < num; j++) { Skip(); } } else { builder.Append(ReadCurrentCharacter()); } } if (analyzer.Check(isSingleQuoted ? '\'' : '"')) { break; } while (analyzer.IsWhite() || analyzer.IsBreak()) { if (analyzer.IsWhite()) { if (!flag) { builder2.Append(ReadCurrentCharacter()); } else { Skip(); } } else if (!flag) { builder2.Length = 0; builder3.Append(ReadLine()); flag = true; } else { builder4.Append(ReadLine()); } } if (flag) { if (StartsWith(builder3, '\n')) { if (builder4.Length == 0) { builder.Append(' '); } else { builder.Append(builder4.ToString()); } } else { builder.Append(builder3.ToString()); builder.Append(builder4.ToString()); } builder3.Length = 0; builder4.Length = 0; } else { builder.Append(builder2.ToString()); builder2.Length = 0; } } Skip(); return new YamlDotNet.Core.Tokens.Scalar(builder.ToString(), isSingleQuoted ? ScalarStyle.SingleQuoted : ScalarStyle.DoubleQuoted, start, cursor.Mark()); } finally { ((IDisposable)builderWrapper4).Dispose(); } } finally { ((IDisposable)builderWrapper3).Dispose(); } } finally { ((IDisposable)builderWrapper2).Dispose(); } } finally { ((IDisposable)builderWrapper).Dispose(); } } private void FetchPlainScalar() { SaveSimpleKey(); simpleKeyAllowed = false; bool isMultiline = false; YamlDotNet.Core.Tokens.Scalar item = (lastScalar = ScanPlainScalar(ref isMultiline)); if (isMultiline && analyzer.Check(':') && flowLevel == 0 && indent < cursor.LineOffset) { tokens.Enqueue(new Error("While scanning a multiline plain scalar, found invalid mapping.", cursor.Mark(), cursor.Mark())); } tokens.Enqueue(item); } private YamlDotNet.Core.Tokens.Scalar ScanPlainScalar(ref bool isMultiline) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; StringBuilderPool.BuilderWrapper builderWrapper2 = StringBuilderPool.Rent(); try { StringBuilder builder2 = builderWrapper2.Builder; StringBuilderPool.BuilderWrapper builderWrapper3 = StringBuilderPool.Rent(); try { StringBuilder builder3 = builderWrapper3.Builder; StringBuilderPool.BuilderWrapper builderWrapper4 = StringBuilderPool.Rent(); try { StringBuilder builder4 = builderWrapper4.Builder; bool flag = false; int num = indent + 1; Mark start = cursor.Mark(); Mark end = start; SimpleKey simpleKey = simpleKeys.Peek(); while (!IsDocumentIndicator()) { if (analyzer.Check('#')) { if (indent < 0 && flowLevel == 0) { plainScalarFollowedByComment = true; } break; } bool flag2 = analyzer.Check('*') && (!simpleKey.IsPossible || !simpleKey.IsRequired); while (!analyzer.IsWhiteBreakOrZero()) { if ((analyzer.Check(':') && !flag2 && (analyzer.IsWhiteBreakOrZero(1) || (flowLevel > 0 && analyzer.Check(',', 1)))) || (flowLevel > 0 && analyzer.Check(",[]{}"))) { if (flowLevel == 0 && !simpleKey.IsPossible) { tokens.Enqueue(new Error("While scanning a plain scalar value, found invalid mapping.", cursor.Mark(), cursor.Mark())); } break; } if (flag || builder2.Length > 0) { if (flag) { if (StartsWith(builder3, '\n')) { if (builder4.Length == 0) { builder.Append(' '); } else { builder.Append((object?)builder4); } } else { builder.Append((object?)builder3); builder.Append((object?)builder4); } builder3.Length = 0; builder4.Length = 0; flag = false; } else { builder.Append((object?)builder2); builder2.Length = 0; } } if (flowLevel > 0 && cursor.LineOffset < num) { throw new Exception(); } builder.Append(ReadCurrentCharacter()); end = cursor.Mark(); } if (!analyzer.IsWhite() && !analyzer.IsBreak()) { break; } while (analyzer.IsWhite() || analyzer.IsBreak()) { if (analyzer.IsWhite()) { if (flag && cursor.LineOffset < num && analyzer.IsTab()) { Mark end2 = cursor.Mark(); throw new SyntaxErrorException(in start, in end2, "While scanning a plain scalar, found a tab character that violate indentation."); } if (!flag) { builder2.Append(ReadCurrentCharacter()); } else { Skip(); } } else { isMultiline = true; if (!flag) { builder2.Length = 0; builder3.Append(ReadLine()); flag = true; } else { builder4.Append(ReadLine()); } } } if (flowLevel == 0 && cursor.LineOffset < num) { break; } } if (flag) { simpleKeyAllowed = true; } return new YamlDotNet.Core.Tokens.Scalar(builder.ToString(), ScalarStyle.Plain, start, end); } finally { ((IDisposable)builderWrapper4).Dispose(); } } finally { ((IDisposable)builderWrapper3).Dispose(); } } finally { ((IDisposable)builderWrapper2).Dispose(); } } finally { ((IDisposable)builderWrapper).Dispose(); } } private void RemoveSimpleKey() { SimpleKey simpleKey = simpleKeys.Peek(); if (simpleKey.IsPossible && simpleKey.IsRequired) { Mark start = simpleKey.Mark; Mark end = simpleKey.Mark; throw new SyntaxErrorException(in start, in end, "While scanning a simple key, could not find expected ':'."); } simpleKey.MarkAsImpossible(); } private string ScanDirectiveName(in Mark start) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; while (analyzer.IsAlphaNumericDashOrUnderscore()) { builder.Append(ReadCurrentCharacter()); } if (builder.Length == 0) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a directive, could not find expected directive name."); } if (analyzer.EndOfInput) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a directive, found unexpected end of stream."); } if (!analyzer.IsWhiteBreakOrZero()) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a directive, found unexpected non-alphabetical character."); } return builder.ToString(); } finally { ((IDisposable)builderWrapper).Dispose(); } } private void SkipWhitespaces() { while (analyzer.IsWhite()) { Skip(); } } private Token ScanVersionDirectiveValue(in Mark start) { SkipWhitespaces(); int major = ScanVersionDirectiveNumber(in start); if (!analyzer.Check('.')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a %YAML directive, did not find expected digit or '.' character."); } Skip(); int minor = ScanVersionDirectiveNumber(in start); return new VersionDirective(new Version(major, minor), start, start); } private Token ScanTagDirectiveValue(in Mark start) { SkipWhitespaces(); string handle = ScanTagHandle(isDirective: true, start); if (!analyzer.IsWhite()) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a %TAG directive, did not find expected whitespace."); } SkipWhitespaces(); string prefix = ScanTagUri(null, start); if (!analyzer.IsWhiteBreakOrZero()) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a %TAG directive, did not find expected whitespace or line break."); } return new TagDirective(handle, prefix, start, start); } private string ScanTagUri(string? head, Mark start) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; if (head != null && head.Length > 1) { builder.Append(head.Substring(1)); } while (analyzer.IsAlphaNumericDashOrUnderscore() || analyzer.Check(";/?:@&=+$.!~*'()[]%") || (analyzer.Check(',') && !analyzer.IsBreak(1))) { if (analyzer.Check('%')) { builder.Append(ScanUriEscapes(in start)); } else if (analyzer.Check('+')) { builder.Append(' '); Skip(); } else { builder.Append(ReadCurrentCharacter()); } } if (builder.Length == 0) { return string.Empty; } string text = builder.ToString(); if (text.EndsWith(",")) { Mark start2 = cursor.Mark(); Mark end = cursor.Mark(); throw new SyntaxErrorException(in start2, in end, "Unexpected comma at end of tag"); } return text; } finally { ((IDisposable)builderWrapper).Dispose(); } } private string ScanUriEscapes(in Mark start) { byte[] array = EmptyBytes; int count = 0; int num = 0; do { if (!analyzer.Check('%') || !analyzer.IsHex(1) || !analyzer.IsHex(2)) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag, did not find URI escaped octet."); } int num2 = (analyzer.AsHex(1) << 4) + analyzer.AsHex(2); if (num == 0) { num = (((num2 & 0x80) == 0) ? 1 : (((num2 & 0xE0) == 192) ? 2 : (((num2 & 0xF0) == 224) ? 3 : (((num2 & 0xF8) == 240) ? 4 : 0)))); if (num == 0) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag, found an incorrect leading UTF-8 octet."); } array = new byte[num]; } else if ((num2 & 0xC0) != 128) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag, found an incorrect trailing UTF-8 octet."); } array[count++] = (byte)num2; Skip(); Skip(); Skip(); } while (--num > 0); string @string = Encoding.UTF8.GetString(array, 0, count); if (@string.Length == 0 || @string.Length > 2) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag, found an incorrect UTF-8 sequence."); } return @string; } private string ScanTagHandle(bool isDirective, Mark start) { if (!analyzer.Check('!')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag, did not find expected '!'."); } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; builder.Append(ReadCurrentCharacter()); while (analyzer.IsAlphaNumericDashOrUnderscore()) { builder.Append(ReadCurrentCharacter()); } if (analyzer.Check('!')) { builder.Append(ReadCurrentCharacter()); } else if (isDirective && (builder.Length != 1 || builder[0] != '!')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag directive, did not find expected '!'."); } return builder.ToString(); } finally { ((IDisposable)builderWrapper).Dispose(); } } private int ScanVersionDirectiveNumber(in Mark start) { int num = 0; int num2 = 0; while (analyzer.IsDigit()) { if (++num2 > 9) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a %YAML directive, found extremely long version number."); } num = num * 10 + analyzer.AsDigit(); Skip(); } if (num2 == 0) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a %YAML directive, did not find expected version number."); } return num; } private void SaveSimpleKey() { bool isRequired = flowLevel == 0 && indent == cursor.LineOffset; if (simpleKeyAllowed) { SimpleKey item = new SimpleKey(isRequired, tokensParsed + tokens.Count, cursor); RemoveSimpleKey(); simpleKeys.Pop(); simpleKeys.Push(item); } } } internal class SemanticErrorException : YamlException { public SemanticErrorException(string message) : base(message) { } public SemanticErrorException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public SemanticErrorException(string message, Exception inner) : base(message, inner) { } } internal sealed class SimpleKey { private readonly Cursor cursor; public bool IsPossible { get; private set; } public bool IsRequired { get; } public int TokenNumber { get; } public int Index => cursor.Index; public int Line => cursor.Line; public int LineOffset => cursor.LineOffset; public Mark Mark => cursor.Mark(); public void MarkAsImpossible() { IsPossible = false; } public SimpleKey() { cursor = new Cursor(); } public SimpleKey(bool isRequired, int tokenNumber, Cursor cursor) { IsPossible = true; IsRequired = isRequired; TokenNumber = tokenNumber; this.cursor = new Cursor(cursor); } } internal sealed class StringLookAheadBuffer : ILookAheadBuffer { private readonly string value; public int Position { get; private set; } public int Length => value.Length; public bool EndOfInput => IsOutside(Position); public StringLookAheadBuffer(string value) { this.value = value; } public char Peek(int offset) { int index = Position + offset; if (!IsOutside(index)) { return value[index]; } return '\0'; } private bool IsOutside(int index) { return index >= value.Length; } public void Skip(int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length", "The length must be positive."); } Position += length; } } internal sealed class SyntaxErrorException : YamlException { public SyntaxErrorException(string message) : base(message) { } public SyntaxErrorException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public SyntaxErrorException(string message, Exception inner) : base(message, inner) { } } internal sealed class TagDirectiveCollection : KeyedCollection { public TagDirectiveCollection() { } public TagDirectiveCollection(IEnumerable tagDirectives) { foreach (TagDirective tagDirective in tagDirectives) { Add(tagDirective); } } protected override string GetKeyForItem(TagDirective item) { return item.Handle; } public new bool Contains(TagDirective directive) { return Contains(GetKeyForItem(directive)); } } internal readonly struct TagName : IEquatable { public static readonly TagName Empty; private readonly string? value; public string Value => value ?? throw new InvalidOperationException("Cannot read the Value of a non-specific tag"); public bool IsEmpty => value == null; public bool IsNonSpecific { get { if (!IsEmpty) { if (!(value == "!")) { return value == "?"; } return true; } return false; } } public bool IsLocal { get { if (!IsEmpty) { return Value[0] == '!'; } return false; } } public bool IsGlobal { get { if (!IsEmpty) { return !IsLocal; } return false; } } public TagName(string value) { this.value = value ?? throw new ArgumentNullException("value"); if (value.Length == 0) { throw new ArgumentException("Tag value must not be empty.", "value"); } if (IsGlobal && !Uri.IsWellFormedUriString(value, UriKind.RelativeOrAbsolute)) { throw new ArgumentException("Global tags must be valid URIs.", "value"); } } public override string ToString() { return value ?? "?"; } public bool Equals(TagName other) { return object.Equals(value, other.value); } public override bool Equals(object? obj) { if (obj is TagName other) { return Equals(other); } return false; } public override int GetHashCode() { return value?.GetHashCode() ?? 0; } public static bool operator ==(TagName left, TagName right) { return left.Equals(right); } public static bool operator !=(TagName left, TagName right) { return !(left == right); } public static bool operator ==(TagName left, string right) { return object.Equals(left.value, right); } public static bool operator !=(TagName left, string right) { return !(left == right); } public static implicit operator TagName(string? value) { if (value != null) { return new TagName(value); } return Empty; } } internal sealed class Version { public int Major { get; } public int Minor { get; } public Version(int major, int minor) { if (major < 0) { throw new ArgumentOutOfRangeException("major", $"{major} should be >= 0"); } Major = major; if (minor < 0) { throw new ArgumentOutOfRangeException("minor", $"{minor} should be >= 0"); } Minor = minor; } public override bool Equals(object? obj) { if (obj is Version version && Major == version.Major) { return Minor == version.Minor; } return false; } public override int GetHashCode() { return HashCode.CombineHashCodes(Major.GetHashCode(), Minor.GetHashCode()); } } internal class YamlException : Exception { public Mark Start { get; } public Mark End { get; } public YamlException(string message) : this(in Mark.Empty, in Mark.Empty, message) { } public YamlException(in Mark start, in Mark end, string message) : this(in start, in end, message, null) { } public YamlException(in Mark start, in Mark end, string message, Exception? innerException) : base(message, innerException) { Start = start; End = end; } public YamlException(string message, Exception inner) : this(in Mark.Empty, in Mark.Empty, message, inner) { } public override string ToString() { return $"({Start}) - ({End}): {Message}"; } } } namespace YamlDotNet.Core.Tokens { internal class Anchor : Token { public AnchorName Value { get; } public Anchor(AnchorName value) : this(value, Mark.Empty, Mark.Empty) { } public Anchor(AnchorName value, Mark start, Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new ArgumentNullException("value"); } Value = value; } } internal sealed class AnchorAlias : Token { public AnchorName Value { get; } public AnchorAlias(AnchorName value) : this(value, Mark.Empty, Mark.Empty) { } public AnchorAlias(AnchorName value, Mark start, Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new ArgumentNullException("value"); } Value = value; } } internal sealed class BlockEnd : Token { public BlockEnd() : this(in Mark.Empty, in Mark.Empty) { } public BlockEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class BlockEntry : Token { public BlockEntry() : this(in Mark.Empty, in Mark.Empty) { } public BlockEntry(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class BlockMappingStart : Token { public BlockMappingStart() : this(in Mark.Empty, in Mark.Empty) { } public BlockMappingStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class BlockSequenceStart : Token { public BlockSequenceStart() : this(in Mark.Empty, in Mark.Empty) { } public BlockSequenceStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class Comment : Token { public string Value { get; } public bool IsInline { get; } public Comment(string value, bool isInline) : this(value, isInline, Mark.Empty, Mark.Empty) { } public Comment(string value, bool isInline, Mark start, Mark end) : base(in start, in end) { Value = value ?? throw new ArgumentNullException("value"); IsInline = isInline; } } internal sealed class DocumentEnd : Token { public DocumentEnd() : this(in Mark.Empty, in Mark.Empty) { } public DocumentEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class DocumentStart : Token { public DocumentStart() : this(in Mark.Empty, in Mark.Empty) { } public DocumentStart(in Mark start, in Mark end) : base(in start, in end) { } } internal class Error : Token { public string Value { get; } public Error(string value, Mark start, Mark end) : base(in start, in end) { Value = value; } } internal sealed class FlowEntry : Token { public FlowEntry() : this(in Mark.Empty, in Mark.Empty) { } public FlowEntry(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowMappingEnd : Token { public FlowMappingEnd() : this(in Mark.Empty, in Mark.Empty) { } public FlowMappingEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowMappingStart : Token { public FlowMappingStart() : this(in Mark.Empty, in Mark.Empty) { } public FlowMappingStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowSequenceEnd : Token { public FlowSequenceEnd() : this(in Mark.Empty, in Mark.Empty) { } public FlowSequenceEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowSequenceStart : Token { public FlowSequenceStart() : this(in Mark.Empty, in Mark.Empty) { } public FlowSequenceStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class Key : Token { public Key() : this(in Mark.Empty, in Mark.Empty) { } public Key(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class Scalar : Token { public bool IsKey { get; set; } public string Value { get; } public ScalarStyle Style { get; } public Scalar(string value) : this(value, ScalarStyle.Any) { } public Scalar(string value, ScalarStyle style) : this(value, style, Mark.Empty, Mark.Empty) { } public Scalar(string value, ScalarStyle style, Mark start, Mark end) : base(in start, in end) { Value = value ?? throw new ArgumentNullException("value"); Style = style; } } internal sealed class StreamEnd : Token { public StreamEnd() : this(in Mark.Empty, in Mark.Empty) { } public StreamEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class StreamStart : Token { public StreamStart() : this(in Mark.Empty, in Mark.Empty) { } public StreamStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class Tag : Token { public string Handle { get; } public string Suffix { get; } public Tag(string handle, string suffix) : this(handle, suffix, Mark.Empty, Mark.Empty) { } public Tag(string handle, string suffix, Mark start, Mark end) : base(in start, in end) { Handle = handle ?? throw new ArgumentNullException("handle"); Suffix = suffix ?? throw new ArgumentNullException("suffix"); } } internal class TagDirective : Token { private static readonly Regex TagHandlePattern = new Regex("^!([0-9A-Za-z_\\-]*!)?$", RegexOptions.Compiled); public string Handle { get; } public string Prefix { get; } public TagDirective(string handle, string prefix) : this(handle, prefix, Mark.Empty, Mark.Empty) { } public TagDirective(string handle, string prefix, Mark start, Mark end) : base(in start, in end) { if (string.IsNullOrEmpty(handle)) { throw new ArgumentNullException("handle", "Tag handle must not be empty."); } if (!TagHandlePattern.IsMatch(handle)) { throw new ArgumentException("Tag handle must start and end with '!' and contain alphanumerical characters only.", "handle"); } Handle = handle; if (string.IsNullOrEmpty(prefix)) { throw new ArgumentNullException("prefix", "Tag prefix must not be empty."); } Prefix = prefix; } public override bool Equals(object? obj) { if (obj is TagDirective tagDirective && Handle.Equals(tagDirective.Handle)) { return Prefix.Equals(tagDirective.Prefix); } return false; } public override int GetHashCode() { return Handle.GetHashCode() ^ Prefix.GetHashCode(); } public override string ToString() { return Handle + " => " + Prefix; } } internal abstract class Token { public Mark Start { get; } public Mark End { get; } protected Token(in Mark start, in Mark end) { Start = start; End = end; } } internal sealed class Value : Token { public Value() : this(in Mark.Empty, in Mark.Empty) { } public Value(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class VersionDirective : Token { public Version Version { get; } public VersionDirective(Version version) : this(version, Mark.Empty, Mark.Empty) { } public VersionDirective(Version version, Mark start, Mark end) : base(in start, in end) { Version = version; } public override bool Equals(object? obj) { if (obj is VersionDirective versionDirective) { return Version.Equals(versionDirective.Version); } return false; } public override int GetHashCode() { return Version.GetHashCode(); } } } namespace YamlDotNet.Core.Events { internal sealed class AnchorAlias : ParsingEvent { internal override EventType Type => EventType.Alias; public AnchorName Value { get; } public AnchorAlias(AnchorName value, Mark start, Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new YamlException(in start, in end, "Anchor value must not be empty."); } Value = value; } public AnchorAlias(AnchorName value) : this(value, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Alias [value = {Value}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class Comment : ParsingEvent { public string Value { get; } public bool IsInline { get; } internal override EventType Type => EventType.Comment; public Comment(string value, bool isInline) : this(value, isInline, Mark.Empty, Mark.Empty) { } public Comment(string value, bool isInline, Mark start, Mark end) : base(in start, in end) { Value = value; IsInline = isInline; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } public override string ToString() { return (IsInline ? "Inline" : "Block") + " Comment [" + Value + "]"; } } internal sealed class DocumentEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.DocumentEnd; public bool IsImplicit { get; } public DocumentEnd(bool isImplicit, Mark start, Mark end) : base(in start, in end) { IsImplicit = isImplicit; } public DocumentEnd(bool isImplicit) : this(isImplicit, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Document end [isImplicit = {IsImplicit}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class DocumentStart : ParsingEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.DocumentStart; public TagDirectiveCollection? Tags { get; } public VersionDirective? Version { get; } public bool IsImplicit { get; } public DocumentStart(VersionDirective? version, TagDirectiveCollection? tags, bool isImplicit, Mark start, Mark end) : base(in start, in end) { Version = version; Tags = tags; IsImplicit = isImplicit; } public DocumentStart(VersionDirective? version, TagDirectiveCollection? tags, bool isImplicit) : this(version, tags, isImplicit, Mark.Empty, Mark.Empty) { } public DocumentStart(in Mark start, in Mark end) : this(null, null, isImplicit: true, start, end) { } public DocumentStart() : this(null, null, isImplicit: true, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Document start [isImplicit = {IsImplicit}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum EventType { None, StreamStart, StreamEnd, DocumentStart, DocumentEnd, Alias, Scalar, SequenceStart, SequenceEnd, MappingStart, MappingEnd, Comment } internal interface IParsingEventVisitor { void Visit(AnchorAlias e); void Visit(StreamStart e); void Visit(StreamEnd e); void Visit(DocumentStart e); void Visit(DocumentEnd e); void Visit(Scalar e); void Visit(SequenceStart e); void Visit(SequenceEnd e); void Visit(MappingStart e); void Visit(MappingEnd e); void Visit(Comment e); } internal class MappingEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.MappingEnd; public MappingEnd(in Mark start, in Mark end) : base(in start, in end) { } public MappingEnd() : this(in Mark.Empty, in Mark.Empty) { } public override string ToString() { return "Mapping end"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class MappingStart : NodeEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.MappingStart; public bool IsImplicit { get; } public override bool IsCanonical => !IsImplicit; public MappingStyle Style { get; } public MappingStart(AnchorName anchor, TagName tag, bool isImplicit, MappingStyle style, Mark start, Mark end) : base(anchor, tag, start, end) { IsImplicit = isImplicit; Style = style; } public MappingStart(AnchorName anchor, TagName tag, bool isImplicit, MappingStyle style) : this(anchor, tag, isImplicit, style, Mark.Empty, Mark.Empty) { } public MappingStart() : this(AnchorName.Empty, TagName.Empty, isImplicit: true, MappingStyle.Any, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Mapping start [anchor = {base.Anchor}, tag = {base.Tag}, isImplicit = {IsImplicit}, style = {Style}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum MappingStyle { Any, Block, Flow } internal abstract class NodeEvent : ParsingEvent { public AnchorName Anchor { get; } public TagName Tag { get; } public abstract bool IsCanonical { get; } protected NodeEvent(AnchorName anchor, TagName tag, Mark start, Mark end) : base(in start, in end) { Anchor = anchor; Tag = tag; } protected NodeEvent(AnchorName anchor, TagName tag) : this(anchor, tag, Mark.Empty, Mark.Empty) { } } internal abstract class ParsingEvent { public virtual int NestingIncrease => 0; internal abstract EventType Type { get; } public Mark Start { get; } public Mark End { get; } public abstract void Accept(IParsingEventVisitor visitor); internal ParsingEvent(in Mark start, in Mark end) { Start = start; End = end; } } internal sealed class Scalar : NodeEvent { internal override EventType Type => EventType.Scalar; public string Value { get; } public ScalarStyle Style { get; } public bool IsPlainImplicit { get; } public bool IsQuotedImplicit { get; } public override bool IsCanonical { get { if (!IsPlainImplicit) { return !IsQuotedImplicit; } return false; } } public bool IsKey { get; } public Scalar(AnchorName anchor, TagName tag, string value, ScalarStyle style, bool isPlainImplicit, bool isQuotedImplicit, Mark start, Mark end, bool isKey = false) : base(anchor, tag, start, end) { Value = value; Style = style; IsPlainImplicit = isPlainImplicit; IsQuotedImplicit = isQuotedImplicit; IsKey = isKey; } public Scalar(AnchorName anchor, TagName tag, string value, ScalarStyle style, bool isPlainImplicit, bool isQuotedImplicit) : this(anchor, tag, value, style, isPlainImplicit, isQuotedImplicit, Mark.Empty, Mark.Empty) { } public Scalar(string value) : this(AnchorName.Empty, TagName.Empty, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, Mark.Empty, Mark.Empty) { } public Scalar(TagName tag, string value) : this(AnchorName.Empty, tag, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, Mark.Empty, Mark.Empty) { } public Scalar(AnchorName anchor, TagName tag, string value) : this(anchor, tag, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Scalar [anchor = {base.Anchor}, tag = {base.Tag}, value = {Value}, style = {Style}, isPlainImplicit = {IsPlainImplicit}, isQuotedImplicit = {IsQuotedImplicit}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class SequenceEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.SequenceEnd; public SequenceEnd(in Mark start, in Mark end) : base(in start, in end) { } public SequenceEnd() : this(in Mark.Empty, in Mark.Empty) { } public override string ToString() { return "Sequence end"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class SequenceStart : NodeEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.SequenceStart; public bool IsImplicit { get; } public override bool IsCanonical => !IsImplicit; public SequenceStyle Style { get; } public SequenceStart(AnchorName anchor, TagName tag, bool isImplicit, SequenceStyle style, Mark start, Mark end) : base(anchor, tag, start, end) { IsImplicit = isImplicit; Style = style; } public SequenceStart(AnchorName anchor, TagName tag, bool isImplicit, SequenceStyle style) : this(anchor, tag, isImplicit, style, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Sequence start [anchor = {base.Anchor}, tag = {base.Tag}, isImplicit = {IsImplicit}, style = {Style}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum SequenceStyle { Any, Block, Flow } internal sealed class StreamEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.StreamEnd; public StreamEnd(in Mark start, in Mark end) : base(in start, in end) { } public StreamEnd() : this(in Mark.Empty, in Mark.Empty) { } public override string ToString() { return "Stream end"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class StreamStart : ParsingEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.StreamStart; public StreamStart() : this(in Mark.Empty, in Mark.Empty) { } public StreamStart(in Mark start, in Mark end) : base(in start, in end) { } public override string ToString() { return "Stream start"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } } namespace System.Collections.Generic { internal static class DeconstructionExtensions { public static void Deconstruct(this KeyValuePair pair, out TKey key, out TValue value) { key = pair.Key; value = pair.Value; } } } namespace System.Diagnostics.CodeAnalysis { [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [DebuggerNonUserCode] [ExcludeFromCodeCoverage] internal sealed class DoesNotReturnAttribute : Attribute { } [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class MaybeNullAttribute : Attribute { } [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } }