using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using B83.Image.BMP; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Dummiesman; using Dummiesman.Extensions; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using PieceManager; using RainbowTrollArmor; using ServerSync; using TMPro; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using UnityEngine.UI; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; using wackydatabase; using wackydatabase.Armor; using wackydatabase.Datas; using wackydatabase.GetData; using wackydatabase.OBJimporter; using wackydatabase.OtherApi; using wackydatabase.Read; using wackydatabase.SetData; using wackydatabase.Startup; using wackydatabase.Util; [assembly: AssemblyFileVersion("2.4.79")] [assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")] [assembly: ComVisible(false)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyProduct("WackysDatabase")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyDescription("")] [assembly: AssemblyTitle("WackysDatabase")] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(8)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("WackyMole")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.4.79.0")] [module: <44f7d4ac-c15e-4b5f-8f50-432d8b8cb69c>RefSafetyRules(11)] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<0b1b7107-d58b-42b4-9c58-6af06143ec15>Embedded] internal sealed class <0b1b7107-d58b-42b4-9c58-6af06143ec15>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [<0b1b7107-d58b-42b4-9c58-6af06143ec15>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)] [CompilerGenerated] [<0b1b7107-d58b-42b4-9c58-6af06143ec15>Embedded] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [<0b1b7107-d58b-42b4-9c58-6af06143ec15>Embedded] [CompilerGenerated] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class <44f7d4ac-c15e-4b5f-8f50-432d8b8cb69c>RefSafetyRulesAttribute : Attribute { public readonly int Version; public <44f7d4ac-c15e-4b5f-8f50-432d8b8cb69c>RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } [NullableContext(1)] [Nullable(0)] public class MTLLoader { public List SearchPaths = new List { "%FileName%_Textures", string.Empty }; private FileInfo _objFileInfo; public virtual Texture2D TextureLoadFunction(string path, bool isNormalMap) { foreach (string searchPath in SearchPaths) { string text = Path.Combine((_objFileInfo != null) ? searchPath.Replace("%FileName%", Path.GetFileNameWithoutExtension(_objFileInfo.Name)) : searchPath, path); if (File.Exists(text)) { Texture2D val = ImageLoader.LoadTexture(text); if (isNormalMap) { val = ImageUtils.ConvertToNormalMap(val); } return val; } } return null; } private Texture2D TryLoadTexture(string texturePath, bool normalMap = false) { texturePath = texturePath.Replace('\\', Path.DirectorySeparatorChar); texturePath = texturePath.Replace('/', Path.DirectorySeparatorChar); return TextureLoadFunction(texturePath, normalMap); } private int GetArgValueCount(string arg) { switch (arg) { case "-bm": case "-blendu": case "-blendv": case "-texres": case "-clamp": case "-imfchan": return 1; case "-mm": return 2; case "-o": case "-s": case "-t": return 3; default: return -1; } } private int GetTexNameIndex(string[] components) { int num; for (num = 1; num < components.Length; num++) { int argValueCount = GetArgValueCount(components[num]); if (argValueCount < 0) { return num; } num += argValueCount; } return -1; } private float GetArgValue(string[] components, string arg, float fallback = 1f) { string text = arg.ToLower(); for (int i = 1; i < components.Length - 1; i++) { string text2 = components[i].ToLower(); if (text == text2) { return OBJLoaderHelper.FastFloatParse(components[i + 1]); } } return fallback; } private string GetTexPathFromMapStatement(string processedLine, string[] splitLine) { int texNameIndex = GetTexNameIndex(splitLine); if (texNameIndex < 0) { Debug.LogError((object)("texNameCmpIdx < 0 on line " + processedLine + ". Texture not loaded.")); return null; } int startIndex = processedLine.IndexOf(splitLine[texNameIndex]); return processedLine.Substring(startIndex); } public Dictionary Load(Stream input) { //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: 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_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Invalid comparison between Unknown and I4 //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Invalid comparison between Unknown and I4 //IL_0280: Unknown result type (might be due to invalid IL or missing references) //IL_02bc: Unknown result type (might be due to invalid IL or missing references) //IL_037c: Unknown result type (might be due to invalid IL or missing references) //IL_0381: Unknown result type (might be due to invalid IL or missing references) //IL_0392: Unknown result type (might be due to invalid IL or missing references) StringReader stringReader = new StringReader(new StreamReader(input).ReadToEnd()); Dictionary dictionary = new Dictionary(); Material val = null; for (string text = stringReader.ReadLine(); text != null; text = stringReader.ReadLine()) { if (!string.IsNullOrWhiteSpace(text)) { string text2 = text.Clean(); string[] array = text2.Split(new char[1] { ' ' }); if (array.Length >= 2 && text2[0] != '#') { if (array[0] == "newmtl") { string text3 = text2.Substring(7); Material val3 = (dictionary[text3] = new Material(Shader.Find("Standard (Specular setup)")) { name = text3 }); val = val3; } else if (!((Object)(object)val == (Object)null)) { if (array[0] == "Kd" || array[0] == "kd") { Color color = val.GetColor("_Color"); Color val4 = OBJLoaderHelper.ColorFromStrArray(array); val.SetColor("_Color", new Color(val4.r, val4.g, val4.b, color.a)); } else if (array[0] == "map_Kd" || array[0] == "map_kd") { string texPathFromMapStatement = GetTexPathFromMapStatement(text2, array); if (texPathFromMapStatement != null) { Texture2D val5 = TryLoadTexture(texPathFromMapStatement); val.SetTexture("_MainTex", (Texture)(object)val5); if ((Object)(object)val5 != (Object)null && ((int)val5.format == 12 || (int)val5.format == 5)) { OBJLoaderHelper.EnableMaterialTransparency(val); } if (Path.GetExtension(texPathFromMapStatement).ToLower() == ".dds") { val.mainTextureScale = new Vector2(1f, -1f); } } } else if (array[0] == "map_Bump" || array[0] == "map_bump") { string texPathFromMapStatement2 = GetTexPathFromMapStatement(text2, array); if (texPathFromMapStatement2 != null) { Texture2D val6 = TryLoadTexture(texPathFromMapStatement2, normalMap: true); float argValue = GetArgValue(array, "-bm"); if ((Object)(object)val6 != (Object)null) { val.SetTexture("_BumpMap", (Texture)(object)val6); val.SetFloat("_BumpScale", argValue); val.EnableKeyword("_NORMALMAP"); } } } else if (array[0] == "Ks" || array[0] == "ks") { val.SetColor("_SpecColor", OBJLoaderHelper.ColorFromStrArray(array)); } else if (array[0] == "Ka" || array[0] == "ka") { val.SetColor("_EmissionColor", OBJLoaderHelper.ColorFromStrArray(array, 0.05f)); val.EnableKeyword("_EMISSION"); } else if (array[0] == "map_Ka" || array[0] == "map_ka") { string texPathFromMapStatement3 = GetTexPathFromMapStatement(text2, array); if (texPathFromMapStatement3 != null) { val.SetTexture("_EmissionMap", (Texture)(object)TryLoadTexture(texPathFromMapStatement3)); } } else if (array[0] == "d" || array[0] == "Tr") { float num = OBJLoaderHelper.FastFloatParse(array[1]); if (array[0] == "Tr") { num = 1f - num; } if (num < 1f - Mathf.Epsilon) { Color color2 = val.GetColor("_Color"); color2.a = num; val.SetColor("_Color", color2); OBJLoaderHelper.EnableMaterialTransparency(val); } } else if (array[0] == "Ns" || array[0] == "ns") { float num2 = OBJLoaderHelper.FastFloatParse(array[1]); num2 /= 1000f; val.SetFloat("_Glossiness", num2); } } } } } return dictionary; } public Dictionary Load(string path) { _objFileInfo = new FileInfo(path); SearchPaths.Add(_objFileInfo.Directory.FullName); using FileStream input = new FileStream(path, FileMode.Open); return Load(input); } } public class RequirementQuality { public int quality; } [Nullable(0)] [NullableContext(1)] public class ColorUtil { public static Color GetColorFromHex(string hex) { //IL_00a3: Unknown result type (might be due to invalid IL or missing references) hex = hex.TrimStart(new char[1] { '#' }); Color result = default(Color); ((Color)(ref result))..ctor(255f, 0f, 0f); if (hex.Length >= 6) { result.r = int.Parse(hex.Substring(0, 2), NumberStyles.HexNumber); result.g = int.Parse(hex.Substring(2, 2), NumberStyles.HexNumber); result.b = int.Parse(hex.Substring(4, 2), NumberStyles.HexNumber); if (hex.Length == 8) { result.a = int.Parse(hex.Substring(6, 2), NumberStyles.HexNumber); } } return result; } public static string GetHexFromColor(Color color) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) return $"#{(int)(color.r * 255f):X2}" + $"{(int)(color.g * 255f):X2}" + $"{(int)(color.b * 255f):X2}" + $"{(int)(color.a * 255f):X2}"; } } [NullableContext(1)] [Nullable(0)] internal sealed class ConfigurationManagerAttributes { public bool? ShowRangeAsPercent; public Action CustomDrawer; public bool? Browsable; public string Category; public object DefaultValue; public bool? HideDefaultButton; public bool? HideSettingName; public string Description; public string DispName; public int? Order; public bool? ReadOnly; public bool? IsAdvanced; public Func ObjToStr; public Func StrToObj; } [NullableContext(1)] [Nullable(0)] public class TextureEventArgs : EventArgs { public Texture2D Texture { get; private set; } public TextureEventArgs(Texture2D t) { Texture = t; } } namespace RainbowTrollArmor { [NullableContext(1)] [Nullable(0)] public class SpriteTools { private Sprite outcome; private Texture2D texture; private Texture2D rawTexture; private Texture2D secondaryLayer; private Sprite source; private Color tint; public float ratio = 0.5f; public void setTint(Color tint) { //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) this.tint = tint; } public void setSecondaryLayer(Texture2D secondaryLayer) { this.secondaryLayer = secondaryLayer; } public void setRatio(int ratio) { this.ratio = (float)ratio / 100f; } public void setRatio(float ratio) { this.ratio = ratio; } public Texture2D CreateTexture2D(Texture2D rawTexture, bool useTint) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) this.rawTexture = rawTexture; makeTexture(((Texture)rawTexture).width, ((Texture)rawTexture).height); getTexturePixels(); if (useTint) { _ = tint; BlendTexture(); } return texture; } public Texture2D CreateTexture2D(Sprite source, bool useTint) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_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_0035: Unknown result type (might be due to invalid IL or missing references) this.source = source; Rect rect = source.rect; int width = (int)((Rect)(ref rect)).width; rect = source.rect; makeTexture(width, (int)((Rect)(ref rect)).height); getSpritePixels(); if (useTint) { _ = tint; BlendTexture(); } return texture; } private void MakeGrayscale() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0030: 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) Color val = default(Color); for (int i = 0; i < ((Texture)texture).width; i++) { for (int j = 0; j < ((Texture)texture).height; j++) { Color pixel = texture.GetPixel(i, j); if (pixel.a > 0f) { float grayscale = ((Color)(ref pixel)).grayscale; ((Color)(ref val))..ctor(grayscale, grayscale, grayscale, pixel.a); texture.SetPixel(i, j, val); } } } texture.Apply(); } public Sprite CreateSprite(Sprite source, bool useTint, bool grayscale = false) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_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_003e: Unknown result type (might be due to invalid IL or missing references) this.source = source; Rect rect = source.rect; int width = (int)((Rect)(ref rect)).width; rect = source.rect; makeTexture(width, (int)((Rect)(ref rect)).height); getSpritePixels(); if (grayscale) { MakeGrayscale(); } if (useTint) { _ = tint; BlendTexture(); } MakeSprite(); return outcome; } public Sprite CreateSprite(Texture2D rawTexture, bool useTint, bool grayscale = false) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) this.rawTexture = rawTexture; makeTexture(((Texture)rawTexture).width, ((Texture)rawTexture).height); getTexturePixels(); if (grayscale) { MakeGrayscale(); } if (useTint) { _ = tint; BlendTexture(); } MakeSprite(); return outcome; } public void makeTexture(int width, int height) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown texture = new Texture2D(width, height); } private void getTexturePixels() { Color[] pixels = rawTexture.GetPixels(); texture.SetPixels(pixels); texture.Apply(); } private void getSpritePixels() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) Texture2D obj = source.texture; Rect textureRect = source.textureRect; int num = (int)((Rect)(ref textureRect)).x; textureRect = source.textureRect; int num2 = (int)((Rect)(ref textureRect)).y; textureRect = source.textureRect; int num3 = (int)((Rect)(ref textureRect)).width; textureRect = source.textureRect; Color[] pixels = obj.GetPixels(num, num2, num3, (int)((Rect)(ref textureRect)).height); texture.SetPixels(pixels); texture.Apply(); } private void BlendTexture() { //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_0019: 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_0030: 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_005b: 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_0061: 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) for (int i = 0; i < ((Texture)texture).width; i++) { for (int j = 0; j < ((Texture)texture).height; j++) { Color pixel = texture.GetPixel(i, j); if (!(pixel.a > 0f)) { continue; } texture.SetPixel(i, j, Color.Lerp(pixel, tint, ratio)); if ((Object)(object)secondaryLayer != (Object)null) { Color pixel2 = secondaryLayer.GetPixel(i, j); if (pixel2.a > 0f) { texture.SetPixel(i, j, pixel2); } } } } texture.Apply(); } public Sprite convertTextureToSprite(Texture2D tex) { //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) return Sprite.Create(tex, new Rect(0f, 0f, (float)((Texture)tex).width, (float)((Texture)tex).height), Vector2.zero); } private void MakeSprite() { //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) outcome = Sprite.Create(texture, new Rect(0f, 0f, (float)((Texture)texture).width, (float)((Texture)texture).height), Vector2.zero); } public Texture2D GetTexture2D() { return texture; } public Sprite getSprite() { return outcome; } public static Sprite LoadNewSprite(string FilePath, float PixelsPerUnit = 100f, SpriteMeshType spriteType = 1) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) Texture2D val = LoadTexture(FilePath); return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0f, 0f), PixelsPerUnit, 0u, spriteType); } public static Sprite ConvertTextureToSprite(Texture2D texture, float PixelsPerUnit = 100f, SpriteMeshType spriteType = 1) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) return Sprite.Create(texture, new Rect(0f, 0f, (float)((Texture)texture).width, (float)((Texture)texture).height), new Vector2(0f, 0f), PixelsPerUnit, 0u, spriteType); } public static Texture2D LoadTexture(string FilePath) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown if (File.Exists(FilePath)) { byte[] array = File.ReadAllBytes(FilePath); Texture2D val = new Texture2D(2, 2); if (ImageConversion.LoadImage(val, array)) { return val; } } return null; } public static string Base64Encode(string plainText) { return Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText)); } public static string Base64Decode(string base64EncodedData) { byte[] bytes = Convert.FromBase64String(base64EncodedData); return Encoding.UTF8.GetString(bytes); } } } namespace B83.Image.BMP { public enum BMPComressionMode { BI_RGB = 0, BI_RLE8 = 1, BI_RLE4 = 2, BI_BITFIELDS = 3, BI_JPEG = 4, BI_PNG = 5, BI_ALPHABITFIELDS = 6, BI_CMYK = 11, BI_CMYKRLE8 = 12, BI_CMYKRLE4 = 13 } public struct BMPFileHeader { public ushort magic; public uint filesize; public uint reserved; public uint offset; } public struct BitmapInfoHeader { public uint size; public int width; public int height; public ushort nColorPlanes; public ushort nBitsPerPixel; public BMPComressionMode compressionMethod; public uint rawImageSize; public int xPPM; public int yPPM; public uint nPaletteColors; public uint nImportantColors; public int absWidth => Mathf.Abs(width); public int absHeight => Mathf.Abs(height); } [Nullable(0)] [NullableContext(1)] public class BMPImage { public BMPFileHeader header; public BitmapInfoHeader info; public uint rMask = 16711680u; public uint gMask = 65280u; public uint bMask = 255u; public uint aMask; public List palette; public Color32[] imageData; public Texture2D ToTexture2D() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown Texture2D val = new Texture2D(info.absWidth, info.absHeight); val.SetPixels32(imageData); val.Apply(); return val; } } [Nullable(0)] [NullableContext(1)] public class BMPLoader { private const ushort MAGIC = 19778; public bool ReadPaletteAlpha; public bool ForceAlphaReadWhenPossible; public BMPImage LoadBMP(string aFileName) { using FileStream aData = File.OpenRead(aFileName); return LoadBMP(aData); } public BMPImage LoadBMP(byte[] aData) { using MemoryStream aData2 = new MemoryStream(aData); return LoadBMP(aData2); } public BMPImage LoadBMP(Stream aData) { using BinaryReader aReader = new BinaryReader(aData); return LoadBMP(aReader); } public BMPImage LoadBMP(BinaryReader aReader) { BMPImage bMPImage = new BMPImage(); if (!ReadFileHeader(aReader, ref bMPImage.header)) { Debug.LogError((object)"Not a BMP file"); return null; } if (!ReadInfoHeader(aReader, ref bMPImage.info)) { Debug.LogError((object)"Unsupported header format"); return null; } if (bMPImage.info.compressionMethod != 0 && bMPImage.info.compressionMethod != BMPComressionMode.BI_BITFIELDS && bMPImage.info.compressionMethod != BMPComressionMode.BI_ALPHABITFIELDS && bMPImage.info.compressionMethod != BMPComressionMode.BI_RLE4 && bMPImage.info.compressionMethod != BMPComressionMode.BI_RLE8) { Debug.LogError((object)("Unsupported image format: " + bMPImage.info.compressionMethod)); return null; } long offset = 14 + bMPImage.info.size; aReader.BaseStream.Seek(offset, SeekOrigin.Begin); if (bMPImage.info.nBitsPerPixel < 24) { bMPImage.rMask = 31744u; bMPImage.gMask = 992u; bMPImage.bMask = 31u; } if (bMPImage.info.compressionMethod == BMPComressionMode.BI_BITFIELDS || bMPImage.info.compressionMethod == BMPComressionMode.BI_ALPHABITFIELDS) { bMPImage.rMask = aReader.ReadUInt32(); bMPImage.gMask = aReader.ReadUInt32(); bMPImage.bMask = aReader.ReadUInt32(); } if (ForceAlphaReadWhenPossible) { bMPImage.aMask = GetMask(bMPImage.info.nBitsPerPixel) ^ (bMPImage.rMask | bMPImage.gMask | bMPImage.bMask); } if (bMPImage.info.compressionMethod == BMPComressionMode.BI_ALPHABITFIELDS) { bMPImage.aMask = aReader.ReadUInt32(); } if (bMPImage.info.nPaletteColors != 0 || bMPImage.info.nBitsPerPixel <= 8) { bMPImage.palette = ReadPalette(aReader, bMPImage, ReadPaletteAlpha || ForceAlphaReadWhenPossible); } aReader.BaseStream.Seek(bMPImage.header.offset, SeekOrigin.Begin); bool flag = bMPImage.info.compressionMethod == BMPComressionMode.BI_RGB || bMPImage.info.compressionMethod == BMPComressionMode.BI_BITFIELDS || bMPImage.info.compressionMethod == BMPComressionMode.BI_ALPHABITFIELDS; if (bMPImage.info.nBitsPerPixel == 32 && flag) { Read32BitImage(aReader, bMPImage); } else if (bMPImage.info.nBitsPerPixel == 24 && flag) { Read24BitImage(aReader, bMPImage); } else if (bMPImage.info.nBitsPerPixel == 16 && flag) { Read16BitImage(aReader, bMPImage); } else if (bMPImage.info.compressionMethod == BMPComressionMode.BI_RLE4 && bMPImage.info.nBitsPerPixel == 4 && bMPImage.palette != null) { ReadIndexedImageRLE4(aReader, bMPImage); } else if (bMPImage.info.compressionMethod == BMPComressionMode.BI_RLE8 && bMPImage.info.nBitsPerPixel == 8 && bMPImage.palette != null) { ReadIndexedImageRLE8(aReader, bMPImage); } else { if (!flag || bMPImage.info.nBitsPerPixel > 8 || bMPImage.palette == null) { Debug.LogError((object)("Unsupported file format: " + bMPImage.info.compressionMethod.ToString() + " BPP: " + bMPImage.info.nBitsPerPixel)); return null; } ReadIndexedImage(aReader, bMPImage); } return bMPImage; } private static void Read32BitImage(BinaryReader aReader, BMPImage bmp) { //IL_0101: 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) int num = Mathf.Abs(bmp.info.width); int num2 = Mathf.Abs(bmp.info.height); Color32[] array = (bmp.imageData = (Color32[])(object)new Color32[num * num2]); if (aReader.BaseStream.Position + num * num2 * 4 > aReader.BaseStream.Length) { Debug.LogError((object)"Unexpected end of file."); return; } int shiftCount = GetShiftCount(bmp.rMask); int shiftCount2 = GetShiftCount(bmp.gMask); int shiftCount3 = GetShiftCount(bmp.bMask); int shiftCount4 = GetShiftCount(bmp.aMask); byte b = byte.MaxValue; for (int i = 0; i < array.Length; i++) { uint num3 = aReader.ReadUInt32(); byte b2 = (byte)((num3 & bmp.rMask) >> shiftCount); byte b3 = (byte)((num3 & bmp.gMask) >> shiftCount2); byte b4 = (byte)((num3 & bmp.bMask) >> shiftCount3); if (bmp.bMask != 0) { b = (byte)((num3 & bmp.aMask) >> shiftCount4); } array[i] = new Color32(b2, b3, b4, b); } } private static void Read24BitImage(BinaryReader aReader, BMPImage bmp) { //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) int num = Mathf.Abs(bmp.info.width); int num2 = Mathf.Abs(bmp.info.height); int num3 = (24 * num + 31) / 32 * 4; int num4 = num3 * num2; int num5 = num3 - num * 3; Color32[] array = (bmp.imageData = (Color32[])(object)new Color32[num * num2]); if (aReader.BaseStream.Position + num4 > aReader.BaseStream.Length) { Debug.LogError((object)("Unexpected end of file. (Have " + (aReader.BaseStream.Position + num4) + " bytes, expected " + aReader.BaseStream.Length + " bytes)")); return; } int shiftCount = GetShiftCount(bmp.rMask); int shiftCount2 = GetShiftCount(bmp.gMask); int shiftCount3 = GetShiftCount(bmp.bMask); for (int i = 0; i < num2; i++) { for (int j = 0; j < num; j++) { int num6 = aReader.ReadByte() | (aReader.ReadByte() << 8) | (aReader.ReadByte() << 16); byte b = (byte)(((uint)num6 & bmp.rMask) >> shiftCount); byte b2 = (byte)(((uint)num6 & bmp.gMask) >> shiftCount2); byte b3 = (byte)(((uint)num6 & bmp.bMask) >> shiftCount3); array[j + i * num] = new Color32(b, b2, b3, byte.MaxValue); } for (int k = 0; k < num5; k++) { aReader.ReadByte(); } } } private static void Read16BitImage(BinaryReader aReader, BMPImage bmp) { //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) int num = Mathf.Abs(bmp.info.width); int num2 = Mathf.Abs(bmp.info.height); int num3 = (16 * num + 31) / 32 * 4; int num4 = num3 * num2; int num5 = num3 - num * 2; Color32[] array = (bmp.imageData = (Color32[])(object)new Color32[num * num2]); if (aReader.BaseStream.Position + num4 > aReader.BaseStream.Length) { Debug.LogError((object)("Unexpected end of file. (Have " + (aReader.BaseStream.Position + num4) + " bytes, expected " + aReader.BaseStream.Length + " bytes)")); return; } int shiftCount = GetShiftCount(bmp.rMask); int shiftCount2 = GetShiftCount(bmp.gMask); int shiftCount3 = GetShiftCount(bmp.bMask); int shiftCount4 = GetShiftCount(bmp.aMask); byte b = byte.MaxValue; for (int i = 0; i < num2; i++) { for (int j = 0; j < num; j++) { uint num6 = (uint)(aReader.ReadByte() | (aReader.ReadByte() << 8)); byte b2 = (byte)((num6 & bmp.rMask) >> shiftCount); byte b3 = (byte)((num6 & bmp.gMask) >> shiftCount2); byte b4 = (byte)((num6 & bmp.bMask) >> shiftCount3); if (bmp.aMask != 0) { b = (byte)((num6 & bmp.aMask) >> shiftCount4); } array[j + i * num] = new Color32(b2, b3, b4, b); } for (int k = 0; k < num5; k++) { aReader.ReadByte(); } } } private static void ReadIndexedImage(BinaryReader aReader, BMPImage bmp) { //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) int num = Mathf.Abs(bmp.info.width); int num2 = Mathf.Abs(bmp.info.height); int nBitsPerPixel = bmp.info.nBitsPerPixel; int num3 = (nBitsPerPixel * num + 31) / 32 * 4; int num4 = num3 * num2; int num5 = num3 - (num * nBitsPerPixel + 7) / 8; Color32[] array = (bmp.imageData = (Color32[])(object)new Color32[num * num2]); if (aReader.BaseStream.Position + num4 > aReader.BaseStream.Length) { Debug.LogError((object)("Unexpected end of file. (Have " + (aReader.BaseStream.Position + num4) + " bytes, expected " + aReader.BaseStream.Length + " bytes)")); return; } BitStreamReader bitStreamReader = new BitStreamReader(aReader); for (int i = 0; i < num2; i++) { for (int j = 0; j < num; j++) { int num6 = (int)bitStreamReader.ReadBits(nBitsPerPixel); if (num6 >= bmp.palette.Count) { Debug.LogError((object)"Indexed bitmap has indices greater than it's color palette"); return; } array[j + i * num] = bmp.palette[num6]; } bitStreamReader.Flush(); for (int k = 0; k < num5; k++) { aReader.ReadByte(); } } } private static void ReadIndexedImageRLE4(BinaryReader aReader, BMPImage bmp) { //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_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) int num = Mathf.Abs(bmp.info.width); int num2 = Mathf.Abs(bmp.info.height); Color32[] array = (bmp.imageData = (Color32[])(object)new Color32[num * num2]); int num3 = 0; int num4 = 0; int num5 = 0; while (aReader.BaseStream.Position < aReader.BaseStream.Length - 1) { int num6 = aReader.ReadByte(); byte b = aReader.ReadByte(); if (num6 > 0) { for (int num7 = num6 / 2; num7 > 0; num7--) { array[num3++ + num5] = bmp.palette[(b >> 4) & 0xF]; array[num3++ + num5] = bmp.palette[b & 0xF]; } if ((num6 & 1) > 0) { array[num3++ + num5] = bmp.palette[(b >> 4) & 0xF]; } continue; } switch (b) { case 0: num3 = 0; num4++; num5 = num4 * num; continue; case 2: num3 += aReader.ReadByte(); num4 += aReader.ReadByte(); num5 = num4 * num; continue; case 1: return; } for (int num8 = b / 2; num8 > 0; num8--) { byte b2 = aReader.ReadByte(); array[num3++ + num5] = bmp.palette[(b2 >> 4) & 0xF]; array[num3++ + num5] = bmp.palette[b2 & 0xF]; } if ((b & 1) > 0) { array[num3++ + num5] = bmp.palette[(aReader.ReadByte() >> 4) & 0xF]; } if ((((b - 1) / 2) & 1) == 0) { aReader.ReadByte(); } } } private static void ReadIndexedImageRLE8(BinaryReader aReader, BMPImage bmp) { //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) int num = Mathf.Abs(bmp.info.width); int num2 = Mathf.Abs(bmp.info.height); Color32[] array = (bmp.imageData = (Color32[])(object)new Color32[num * num2]); int num3 = 0; int num4 = 0; int num5 = 0; while (aReader.BaseStream.Position < aReader.BaseStream.Length - 1) { int num6 = aReader.ReadByte(); byte b = aReader.ReadByte(); if (num6 > 0) { for (int num7 = num6; num7 > 0; num7--) { array[num3++ + num5] = bmp.palette[b]; } continue; } switch (b) { case 0: num3 = 0; num4++; num5 = num4 * num; continue; case 2: num3 += aReader.ReadByte(); num4 += aReader.ReadByte(); num5 = num4 * num; continue; case 1: return; } for (int num8 = b; num8 > 0; num8--) { array[num3++ + num5] = bmp.palette[aReader.ReadByte()]; } if ((b & 1) > 0) { aReader.ReadByte(); } } } private static int GetShiftCount(uint mask) { for (int i = 0; i < 32; i++) { if ((mask & (true ? 1u : 0u)) != 0) { return i; } mask >>= 1; } return -1; } private static uint GetMask(int bitCount) { uint num = 0u; for (int i = 0; i < bitCount; i++) { num <<= 1; num |= 1u; } return num; } private static bool ReadFileHeader(BinaryReader aReader, ref BMPFileHeader aFileHeader) { aFileHeader.magic = aReader.ReadUInt16(); if (aFileHeader.magic != 19778) { return false; } aFileHeader.filesize = aReader.ReadUInt32(); aFileHeader.reserved = aReader.ReadUInt32(); aFileHeader.offset = aReader.ReadUInt32(); return true; } private static bool ReadInfoHeader(BinaryReader aReader, ref BitmapInfoHeader aHeader) { aHeader.size = aReader.ReadUInt32(); if (aHeader.size < 40) { return false; } aHeader.width = aReader.ReadInt32(); aHeader.height = aReader.ReadInt32(); aHeader.nColorPlanes = aReader.ReadUInt16(); aHeader.nBitsPerPixel = aReader.ReadUInt16(); aHeader.compressionMethod = (BMPComressionMode)aReader.ReadInt32(); aHeader.rawImageSize = aReader.ReadUInt32(); aHeader.xPPM = aReader.ReadInt32(); aHeader.yPPM = aReader.ReadInt32(); aHeader.nPaletteColors = aReader.ReadUInt32(); aHeader.nImportantColors = aReader.ReadUInt32(); int num = (int)(aHeader.size - 40); if (num > 0) { aReader.ReadBytes(num); } return true; } public static List ReadPalette(BinaryReader aReader, BMPImage aBmp, bool aReadAlpha) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) uint num = aBmp.info.nPaletteColors; if (num == 0) { num = (uint)(1 << (int)aBmp.info.nBitsPerPixel); } List list = new List((int)num); for (int i = 0; i < num; i++) { byte b = aReader.ReadByte(); byte b2 = aReader.ReadByte(); byte b3 = aReader.ReadByte(); byte b4 = aReader.ReadByte(); if (!aReadAlpha) { b4 = byte.MaxValue; } list.Add(new Color32(b3, b2, b, b4)); } return list; } } [Nullable(0)] [NullableContext(1)] public class BitStreamReader { private BinaryReader m_Reader; private byte m_Data; private int m_Bits; public BitStreamReader(BinaryReader aReader) { m_Reader = aReader; } public BitStreamReader(Stream aStream) : this(new BinaryReader(aStream)) { } public byte ReadBit() { if (m_Bits <= 0) { m_Data = m_Reader.ReadByte(); m_Bits = 8; } return (byte)((uint)(m_Data >> --m_Bits) & 1u); } public ulong ReadBits(int aCount) { ulong num = 0uL; if (aCount <= 0 || aCount > 32) { throw new ArgumentOutOfRangeException("aCount", "aCount must be between 1 and 32 inclusive"); } for (int num2 = aCount - 1; num2 >= 0; num2--) { num |= (ulong)ReadBit() << num2; } return num; } public void Flush() { m_Data = 0; m_Bits = 0; } } } namespace Dummiesman { [Nullable(0)] [NullableContext(1)] public static class BinaryExtensions { public static Color32 ReadColor32RGBR(this BinaryReader r) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) byte[] array = r.ReadBytes(4); return new Color32(array[0], array[1], array[2], byte.MaxValue); } public static Color32 ReadColor32RGBA(this BinaryReader r) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) byte[] array = r.ReadBytes(4); return new Color32(array[0], array[1], array[2], array[3]); } public static Color32 ReadColor32RGB(this BinaryReader r) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) byte[] array = r.ReadBytes(3); return new Color32(array[0], array[1], array[2], byte.MaxValue); } public static Color32 ReadColor32BGR(this BinaryReader r) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) byte[] array = r.ReadBytes(3); return new Color32(array[2], array[1], array[0], byte.MaxValue); } } [Nullable(0)] [NullableContext(1)] public class CharWordReader { public char[] word; public int wordSize; public bool endReached; private StreamReader reader; private int bufferSize; private char[] buffer; public char currentChar; private int currentPosition; private int maxPosition; public CharWordReader(StreamReader reader, int bufferSize) { this.reader = reader; this.bufferSize = bufferSize; buffer = new char[this.bufferSize]; word = new char[this.bufferSize]; MoveNext(); } public void SkipWhitespaces() { while (char.IsWhiteSpace(currentChar)) { MoveNext(); } } public void SkipWhitespaces(out bool newLinePassed) { newLinePassed = false; while (char.IsWhiteSpace(currentChar)) { if (currentChar == '\r' || currentChar == '\n') { newLinePassed = true; } MoveNext(); } } public void SkipUntilNewLine() { while (currentChar != 0 && currentChar != '\n' && currentChar != '\r') { MoveNext(); } SkipNewLineSymbols(); } public void ReadUntilWhiteSpace() { wordSize = 0; while (currentChar != 0 && !char.IsWhiteSpace(currentChar)) { word[wordSize] = currentChar; wordSize++; MoveNext(); } } public void ReadUntilNewLine() { wordSize = 0; while (currentChar != 0 && currentChar != '\n' && currentChar != '\r') { word[wordSize] = currentChar; wordSize++; MoveNext(); } SkipNewLineSymbols(); } public bool Is(string other) { if (other.Length != wordSize) { return false; } for (int i = 0; i < wordSize; i++) { if (word[i] != other[i]) { return false; } } return true; } public string GetString(int startIndex = 0) { if (startIndex >= wordSize - 1) { return string.Empty; } return new string(word, startIndex, wordSize - startIndex); } public Vector3 ReadVector() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) SkipWhitespaces(); float num = ReadFloat(); SkipWhitespaces(); float num2 = ReadFloat(); SkipWhitespaces(out var newLinePassed); float num3 = 0f; if (!newLinePassed) { num3 = ReadFloat(); } return new Vector3(num, num2, num3); } public int ReadInt() { int num = 0; bool flag = currentChar == '-'; if (flag) { MoveNext(); } while (currentChar >= '0' && currentChar <= '9') { int num2 = currentChar - 48; num = num * 10 + num2; MoveNext(); } if (!flag) { return num; } return -num; } public float ReadFloat() { bool num = currentChar == '-'; if (num) { MoveNext(); } float num2 = ReadInt(); if (currentChar == '.' || currentChar == ',') { MoveNext(); num2 += ReadFloatEnd(); if (currentChar == 'e' || currentChar == 'E') { MoveNext(); int num3 = ReadInt(); num2 *= Mathf.Pow(10f, (float)num3); } } if (num) { num2 = 0f - num2; } return num2; } private float ReadFloatEnd() { float num = 0f; float num2 = 0.1f; while (currentChar >= '0' && currentChar <= '9') { int num3 = currentChar - 48; num += (float)num3 * num2; num2 *= 0.1f; MoveNext(); } return num; } private void SkipNewLineSymbols() { while (currentChar == '\n' || currentChar == '\r') { MoveNext(); } } public void MoveNext() { currentPosition++; if (currentPosition >= maxPosition) { if (reader.EndOfStream) { currentChar = '\0'; endReached = true; return; } currentPosition = 0; maxPosition = reader.Read(buffer, 0, bufferSize); } currentChar = buffer[currentPosition]; } } [NullableContext(1)] [Nullable(0)] public static class DDSLoader { public static Texture2D Load(Stream ddsStream) { byte[] array = new byte[ddsStream.Length]; ddsStream.Read(array, 0, (int)ddsStream.Length); return Load(array); } public static Texture2D Load(string ddsPath) { return Load(File.ReadAllBytes(ddsPath)); } public static Texture2D Load(byte[] ddsBytes) { //IL_005e: 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_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_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Expected O, but got Unknown try { if (ddsBytes[4] != 124) { throw new Exception("Invalid DDS header. Structure length is incrrrect."); } byte b = ddsBytes[87]; if (b != 49 && b != 53) { throw new Exception("Cannot load DDS due to an unsupported pixel format. Needs to be DXT1 or DXT5."); } int num = ddsBytes[13] * 256 + ddsBytes[12]; int num2 = ddsBytes[17] * 256 + ddsBytes[16]; bool flag = ddsBytes[28] > 0; TextureFormat val = (TextureFormat)((b == 49) ? 10 : 12); int num3 = 128; byte[] array = new byte[ddsBytes.Length - num3]; Buffer.BlockCopy(ddsBytes, num3, array, 0, ddsBytes.Length - num3); Texture2D val2 = new Texture2D(num2, num, val, flag); val2.LoadRawTextureData(array); val2.Apply(); return val2; } catch (Exception ex) { throw new Exception("An error occured while loading DirectDraw Surface: " + ex.Message); } } } [Nullable(0)] [NullableContext(1)] public class ImageLoader { [NullableContext(0)] public enum TextureFormat { DDS, TGA, BMP, PNG, JPG, CRN } public static void SetNormalMap(ref Texture2D tex) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) Color[] pixels = tex.GetPixels(); for (int i = 0; i < pixels.Length; i++) { Color val = pixels[i]; val.r = pixels[i].g; val.a = pixels[i].r; pixels[i] = val; } tex.SetPixels(pixels); tex.Apply(true); } public static Texture2D LoadTexture(Stream stream, TextureFormat format) { //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_0052: Expected O, but got Unknown //IL_0054: Expected O, but got Unknown switch (format) { case TextureFormat.BMP: return new BMPLoader().LoadBMP(stream).ToTexture2D(); case TextureFormat.DDS: return DDSLoader.Load(stream); case TextureFormat.PNG: case TextureFormat.JPG: { byte[] array = new byte[stream.Length]; stream.Read(array, 0, (int)stream.Length); Texture2D val = new Texture2D(1, 1); ImageConversion.LoadImage(val, array); return val; } case TextureFormat.TGA: return TGALoader.Load(stream); default: return null; } } public static Texture2D LoadTexture(string fn) { //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Expected O, but got Unknown //IL_018d: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Expected O, but got Unknown //IL_01ac: Unknown result type (might be due to invalid IL or missing references) if (!File.Exists(fn)) { return null; } byte[] array = File.ReadAllBytes(fn); string text = Path.GetExtension(fn).ToLower(); string fileName = Path.GetFileName(fn); Texture2D val = null; if (text != null) { int length = text.Length; if (length != 4) { if (length == 5 && text == ".jpeg") { goto IL_0103; } } else { switch (text[1]) { case 'p': break; case 'j': goto IL_0099; case 'd': goto IL_00ab; case 't': goto IL_00bd; case 'b': goto IL_00cf; case 'c': goto IL_00e1; default: goto IL_020a; } if (text == ".png") { goto IL_0103; } } } goto IL_020a; IL_0220: if ((Object)(object)val != (Object)null) { val = ImageLoaderHelper.VerifyFormat(val); ((Object)val).name = Path.GetFileNameWithoutExtension(fn); } return val; IL_00e1: if (!(text == ".crn")) { goto IL_020a; } byte[] array2 = array; ushort num = BitConverter.ToUInt16(new byte[2] { array2[13], array2[12] }, 0); ushort num2 = BitConverter.ToUInt16(new byte[2] { array2[15], array2[14] }, 0); byte b = array2[18]; TextureFormat val2 = (TextureFormat)3; if (b == 0) { val2 = (TextureFormat)28; } else if (b == 2) { val2 = (TextureFormat)29; } else { if (b != 12) { Debug.LogError((object)("Could not load crunched texture " + fileName + " because its format is not supported (" + b + "): " + fn)); goto IL_0220; } val2 = (TextureFormat)65; } val = new Texture2D((int)num, (int)num2, val2, true); val.LoadRawTextureData(array2); val.Apply(true); goto IL_0220; IL_020a: Debug.LogError((object)("Could not load texture " + fileName + " because its format is not supported : " + fn)); goto IL_0220; IL_00bd: if (!(text == ".tga")) { goto IL_020a; } val = TGALoader.Load(array); goto IL_0220; IL_0103: val = new Texture2D(1, 1); ImageConversion.LoadImage(val, array); goto IL_0220; IL_00cf: if (!(text == ".bmp")) { goto IL_020a; } val = new BMPLoader().LoadBMP(array).ToTexture2D(); goto IL_0220; IL_0099: if (text == ".jpg") { goto IL_0103; } goto IL_020a; IL_00ab: if (!(text == ".dds")) { goto IL_020a; } val = DDSLoader.Load(array); goto IL_0220; } } [Nullable(0)] [NullableContext(1)] public class ImageLoaderHelper { public static Texture2D VerifyFormat(Texture2D tex) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Invalid comparison between Unknown and I4 //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Invalid comparison between Unknown and I4 //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: 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_007b: Expected O, but got Unknown if ((int)tex.format != 5 && (int)tex.format != 4 && (int)tex.format != 12) { return tex; } Color32[] pixels = tex.GetPixels32(); bool flag = false; Color32[] array = pixels; for (int i = 0; i < array.Length; i++) { if (array[i].a < byte.MaxValue) { flag = true; break; } } if (!flag) { Texture2D val = new Texture2D(((Texture)tex).width, ((Texture)tex).height, (TextureFormat)3, ((Texture)tex).mipmapCount > 0); val.SetPixels32(pixels); val.Apply(true); return val; } return tex; } public static void FillPixelArray(Color32[] fillArray, byte[] pixelData, int bytesPerPixel, bool bgra = false) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) if (bgra) { if (bytesPerPixel == 4) { for (int i = 0; i < fillArray.Length; i++) { int num = i * bytesPerPixel; fillArray[i] = new Color32(pixelData[num + 2], pixelData[num + 1], pixelData[num], pixelData[num + 3]); } return; } for (int j = 0; j < fillArray.Length; j++) { fillArray[j].r = pixelData[j * 3 + 2]; fillArray[j].g = pixelData[j * 3 + 1]; fillArray[j].b = pixelData[j * 3]; } } else if (bytesPerPixel == 4) { for (int k = 0; k < fillArray.Length; k++) { fillArray[k].r = pixelData[k * 4]; fillArray[k].g = pixelData[k * 4 + 1]; fillArray[k].b = pixelData[k * 4 + 2]; fillArray[k].a = pixelData[k * 4 + 3]; } } else { int num2 = 0; for (int l = 0; l < fillArray.Length; l++) { fillArray[l].r = pixelData[num2++]; fillArray[l].g = pixelData[num2++]; fillArray[l].b = pixelData[num2++]; fillArray[l].a = byte.MaxValue; } } } } public static class ImageUtils { [NullableContext(1)] public static Texture2D ConvertToNormalMap(Texture2D tex) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Invalid comparison between Unknown and I4 //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Invalid comparison between Unknown and I4 //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) Texture2D val = tex; if ((int)tex.format != 4 && (int)tex.format != 5) { val = new Texture2D(((Texture)tex).width, ((Texture)tex).height, (TextureFormat)4, true); } Color[] pixels = tex.GetPixels(); for (int i = 0; i < pixels.Length; i++) { Color val2 = pixels[i]; val2.a = pixels[i].r; val2.r = 0f; val2.g = pixels[i].g; val2.b = 0f; pixels[i] = val2; } val.SetPixels(pixels); val.Apply(true); return val; } } public enum SplitMode { None, Object, Material } [Nullable(0)] [NullableContext(1)] public class OBJLoader { public SplitMode SplitMode = SplitMode.Object; internal List Vertices = new List(); internal List Normals = new List(); internal List UVs = new List(); internal Dictionary Materials; private FileInfo _objInfo; private void LoadMaterialLibrary(string mtlLibPath) { if (_objInfo != null && File.Exists(Path.Combine(_objInfo.Directory.FullName, mtlLibPath))) { Materials = new MTLLoader().Load(Path.Combine(_objInfo.Directory.FullName, mtlLibPath)); } else if (File.Exists(mtlLibPath)) { Materials = new MTLLoader().Load(mtlLibPath); } } public GameObject Load(Stream input) { //IL_032b: Unknown result type (might be due to invalid IL or missing references) //IL_0332: Expected O, but got Unknown //IL_0348: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) StreamReader reader = new StreamReader(input); Dictionary builderDict = new Dictionary(); OBJObjectBuilder currentBuilder = null; string material = "default"; List list = new List(); List list2 = new List(); List list3 = new List(); Action action = delegate(string objectName) { if (!builderDict.TryGetValue(objectName, out currentBuilder)) { currentBuilder = new OBJObjectBuilder(objectName, this); builderDict[objectName] = currentBuilder; } }; action("default"); CharWordReader charWordReader = new CharWordReader(reader, 4096); while (true) { charWordReader.SkipWhitespaces(); if (charWordReader.endReached) { break; } charWordReader.ReadUntilWhiteSpace(); if (charWordReader.Is("#")) { charWordReader.SkipUntilNewLine(); } else if (Materials == null && charWordReader.Is("mtllib")) { charWordReader.SkipWhitespaces(); charWordReader.ReadUntilNewLine(); string @string = charWordReader.GetString(); LoadMaterialLibrary(@string); } else if (charWordReader.Is("v")) { Vertices.Add(charWordReader.ReadVector()); } else if (charWordReader.Is("vn")) { Normals.Add(charWordReader.ReadVector()); } else if (charWordReader.Is("vt")) { UVs.Add(Vector2.op_Implicit(charWordReader.ReadVector())); } else if (charWordReader.Is("usemtl")) { charWordReader.SkipWhitespaces(); charWordReader.ReadUntilNewLine(); string string2 = charWordReader.GetString(); material = string2; if (SplitMode == SplitMode.Material) { action(string2); } } else if ((charWordReader.Is("o") || charWordReader.Is("g")) && SplitMode == SplitMode.Object) { charWordReader.ReadUntilNewLine(); string string3 = charWordReader.GetString(1); action(string3); } else if (charWordReader.Is("f")) { while (true) { charWordReader.SkipWhitespaces(out var newLinePassed); if (newLinePassed) { break; } int num = int.MinValue; int num2 = int.MinValue; int num3 = int.MinValue; num = charWordReader.ReadInt(); if (charWordReader.currentChar == '/') { charWordReader.MoveNext(); if (charWordReader.currentChar != '/') { num3 = charWordReader.ReadInt(); } if (charWordReader.currentChar == '/') { charWordReader.MoveNext(); num2 = charWordReader.ReadInt(); } } if (num > int.MinValue) { if (num < 0) { num = Vertices.Count - num; } num--; } if (num2 > int.MinValue) { if (num2 < 0) { num2 = Normals.Count - num2; } num2--; } if (num3 > int.MinValue) { if (num3 < 0) { num3 = UVs.Count - num3; } num3--; } list.Add(num); list2.Add(num2); list3.Add(num3); } currentBuilder.PushFace(material, list, list2, list3); list.Clear(); list2.Clear(); list3.Clear(); } else { charWordReader.SkipUntilNewLine(); } } GameObject val = new GameObject((_objInfo != null) ? Path.GetFileNameWithoutExtension(_objInfo.Name) : "WavefrontObject"); val.transform.localScale = new Vector3(1f, 1f, 1f); foreach (KeyValuePair item in builderDict) { if (item.Value.PushedFaceCount != 0) { item.Value.Build().transform.SetParent(val.transform, false); } } return val; } public GameObject Load(Stream input, Stream mtlInput) { MTLLoader mTLLoader = new MTLLoader(); Materials = mTLLoader.Load(mtlInput); return Load(input); } public GameObject Load(string path, string mtlPath) { _objInfo = new FileInfo(path); if (!string.IsNullOrEmpty(mtlPath) && File.Exists(mtlPath)) { MTLLoader mTLLoader = new MTLLoader(); Materials = mTLLoader.Load(mtlPath); using FileStream input = new FileStream(path, FileMode.Open); return Load(input); } using FileStream input2 = new FileStream(path, FileMode.Open); return Load(input2); } public GameObject Load(string path) { return Load(path, null); } } [Nullable(0)] [NullableContext(1)] public static class OBJLoaderHelper { public static void EnableMaterialTransparency(Material mtl) { mtl.SetFloat("_Mode", 3f); mtl.SetInt("_SrcBlend", 5); mtl.SetInt("_DstBlend", 10); mtl.SetInt("_ZWrite", 0); mtl.DisableKeyword("_ALPHATEST_ON"); mtl.EnableKeyword("_ALPHABLEND_ON"); mtl.DisableKeyword("_ALPHAPREMULTIPLY_ON"); mtl.renderQueue = 3000; } public static float FastFloatParse(string input) { if (input.Contains("e") || input.Contains("E")) { return float.Parse(input, CultureInfo.InvariantCulture); } float num = 0f; int num2 = 0; int length = input.Length; if (length == 0) { return float.NaN; } char c = input[0]; float num3 = 1f; if (c == '-') { num3 = -1f; num2++; if (num2 >= length) { return float.NaN; } } while (true) { if (num2 >= length) { return num3 * num; } c = input[num2++]; if (c < '0' || c > '9') { break; } num = num * 10f + (float)(c - 48); } if (c != '.' && c != ',') { return float.NaN; } float num4 = 0.1f; while (num2 < length) { c = input[num2++]; if (c < '0' || c > '9') { return float.NaN; } num += (float)(c - 48) * num4; num4 *= 0.1f; } return num3 * num; } public static int FastIntParse(string input) { int num = 0; bool flag = input[0] == '-'; for (int i = (flag ? 1 : 0); i < input.Length; i++) { num = num * 10 + (input[i] - 48); } if (!flag) { return num; } return -num; } public static Material CreateNullMaterial() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown return new Material(Shader.Find("Standard (Specular setup)")); } public static Vector3 VectorFromStrArray(string[] cmps) { //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_0024: Unknown result type (might be due to invalid IL or missing references) float num = FastFloatParse(cmps[1]); float num2 = FastFloatParse(cmps[2]); if (cmps.Length == 4) { float num3 = FastFloatParse(cmps[3]); return new Vector3(num, num2, num3); } return Vector2.op_Implicit(new Vector2(num, num2)); } public static Color ColorFromStrArray(string[] cmps, float scalar = 1f) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) float num = FastFloatParse(cmps[1]) * scalar; float num2 = FastFloatParse(cmps[2]) * scalar; float num3 = FastFloatParse(cmps[3]) * scalar; return new Color(num, num2, num3); } } [Nullable(0)] [NullableContext(1)] public class OBJObjectBuilder { [NullableContext(0)] private class ObjLoopHash { public int vertexIndex; public int normalIndex; public int uvIndex; [NullableContext(1)] public override bool Equals(object obj) { if (!(obj is ObjLoopHash)) { return false; } ObjLoopHash objLoopHash = obj as ObjLoopHash; if (objLoopHash.vertexIndex == vertexIndex && objLoopHash.uvIndex == uvIndex) { return objLoopHash.normalIndex == normalIndex; } return false; } public override int GetHashCode() { return ((3 * 314159 + vertexIndex) * 314159 + normalIndex) * 314159 + uvIndex; } } private OBJLoader _loader; private string _name; private Dictionary _globalIndexRemap = new Dictionary(); private Dictionary> _materialIndices = new Dictionary>(); private List _currentIndexList; private string _lastMaterial; private List _vertices = new List(); private List _normals = new List(); private List _uvs = new List(); private bool recalculateNormals; public int PushedFaceCount { get; private set; } public GameObject Build() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_007d: 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_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown GameObject val = new GameObject(_name); MeshRenderer val2 = val.AddComponent(); int num = 0; Material[] array = (Material[])(object)new Material[_materialIndices.Count]; foreach (KeyValuePair> materialIndex in _materialIndices) { _ = materialIndex; array[num] = WMRecipeCust.originalMaterials["wood"]; num++; } ((Renderer)val2).sharedMaterials = array; MeshFilter val3 = val.AddComponent(); num = 0; Mesh val4 = new Mesh { name = _name, indexFormat = (IndexFormat)(_vertices.Count > 65535), subMeshCount = _materialIndices.Count }; val4.SetVertices(_vertices); val4.SetNormals(_normals); val4.SetUVs(0, _uvs); foreach (KeyValuePair> materialIndex2 in _materialIndices) { val4.SetTriangles(materialIndex2.Value, num); num++; } if (recalculateNormals) { val4.RecalculateNormals(); } val4.RecalculateTangents(); val4.RecalculateBounds(); val3.sharedMesh = val4; return val; } public void SetMaterial(string name) { if (!_materialIndices.TryGetValue(name, out _currentIndexList)) { _currentIndexList = new List(); _materialIndices[name] = _currentIndexList; } } public void PushFace(string material, List vertexIndices, List normalIndices, List uvIndices) { //IL_00c9: 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_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_013f: 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) if (vertexIndices.Count < 3) { return; } if (material != _lastMaterial) { SetMaterial(material); _lastMaterial = material; } int[] array = new int[vertexIndices.Count]; for (int i = 0; i < vertexIndices.Count; i++) { int num = vertexIndices[i]; int num2 = normalIndices[i]; int num3 = uvIndices[i]; ObjLoopHash key = new ObjLoopHash { vertexIndex = num, normalIndex = num2, uvIndex = num3 }; int value = -1; if (!_globalIndexRemap.TryGetValue(key, out value)) { _globalIndexRemap.Add(key, _vertices.Count); value = _vertices.Count; _vertices.Add((num >= 0 && num < _loader.Vertices.Count) ? _loader.Vertices[num] : Vector3.zero); _normals.Add((num2 >= 0 && num2 < _loader.Normals.Count) ? _loader.Normals[num2] : Vector3.zero); _uvs.Add((num3 >= 0 && num3 < _loader.UVs.Count) ? _loader.UVs[num3] : Vector2.zero); if (num2 < 0) { recalculateNormals = true; } } array[i] = value; } if (array.Length == 3) { _currentIndexList.AddRange(new int[3] { array[0], array[1], array[2] }); } else if (array.Length == 4) { _currentIndexList.AddRange(new int[3] { array[0], array[1], array[2] }); _currentIndexList.AddRange(new int[3] { array[2], array[3], array[0] }); } else if (array.Length > 4) { for (int num4 = array.Length - 1; num4 >= 2; num4--) { _currentIndexList.AddRange(new int[3] { array[0], array[num4 - 1], array[num4] }); } } PushedFaceCount++; } public OBJObjectBuilder(string name, OBJLoader loader) { _name = name; _loader = loader; } } public static class StringExtensions { [NullableContext(1)] public static string Clean(this string str) { string text = str.Replace('\t', ' '); while (text.Contains(" ")) { text = text.Replace(" ", " "); } return text.Trim(); } } [NullableContext(1)] [Nullable(0)] public class TGALoader { private static int GetBits(byte b, int offset, int count) { return (b >> offset) & ((1 << count) - 1); } private static Color32[] LoadRawTGAData(BinaryReader r, int bitDepth, int width, int height) { Color32[] array = new Color32[width * height]; byte[] pixelData = r.ReadBytes(width * height * (bitDepth / 8)); ImageLoaderHelper.FillPixelArray((Color32[])(object)array, pixelData, bitDepth / 8, bgra: true); return (Color32[])(object)array; } private static Color32[] LoadRLETGAData(BinaryReader r, int bitDepth, int width, int height) { //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_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_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) Color32[] array = (Color32[])(object)new Color32[width * height]; int num; for (int i = 0; i < array.Length; i += num) { byte b = r.ReadByte(); int bits = GetBits(b, 7, 1); num = GetBits(b, 0, 7) + 1; if (bits == 0) { for (int j = 0; j < num; j++) { Color32 val = ((bitDepth == 32) ? r.ReadColor32RGBA().FlipRB() : r.ReadColor32RGB().FlipRB()); array[j + i] = val; } } else { Color32 val2 = ((bitDepth == 32) ? r.ReadColor32RGBA().FlipRB() : r.ReadColor32RGB().FlipRB()); for (int k = 0; k < num; k++) { array[k + i] = val2; } } } return array; } public static Texture2D Load(string fileName) { using FileStream tGAStream = File.OpenRead(fileName); return Load(tGAStream); } public static Texture2D Load(byte[] bytes) { using MemoryStream tGAStream = new MemoryStream(bytes); return Load(tGAStream); } public static Texture2D Load(Stream TGAStream) { //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Expected O, but got Unknown using BinaryReader binaryReader = new BinaryReader(TGAStream); binaryReader.BaseStream.Seek(2L, SeekOrigin.Begin); byte b = binaryReader.ReadByte(); if (b != 10 && b != 2) { Debug.LogError((object)$"Unsupported targa image type. ({b})"); return null; } binaryReader.BaseStream.Seek(12L, SeekOrigin.Begin); short num = binaryReader.ReadInt16(); short num2 = binaryReader.ReadInt16(); int num3 = binaryReader.ReadByte(); if (num3 < 24) { throw new Exception("Tried to load TGA with unsupported bit depth"); } binaryReader.BaseStream.Seek(1L, SeekOrigin.Current); Texture2D val = new Texture2D((int)num, (int)num2, (TextureFormat)((num3 == 24) ? 3 : 5), true); if (b == 2) { val.SetPixels32(LoadRawTGAData(binaryReader, num3, num, num2)); } else { val.SetPixels32(LoadRLETGAData(binaryReader, num3, num, num2)); } val.Apply(); return val; } } } namespace Dummiesman.Extensions { public static class ColorExtensions { public static Color FlipRB(this Color color) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: 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_0018: Unknown result type (might be due to invalid IL or missing references) return new Color(color.b, color.g, color.r, color.a); } public static Color32 FlipRB(this Color32 color) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: 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_0018: Unknown result type (might be due to invalid IL or missing references) return new Color32(color.b, color.g, color.r, color.a); } } } namespace ServerSync { [NullableContext(1)] [Nullable(0)] [PublicAPI] public abstract class OwnConfigEntryBase { [Nullable(2)] public object LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [Nullable(0)] [NullableContext(1)] [PublicAPI] public 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)] public 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; }; } } [Nullable(0)] [PublicAPI] [NullableContext(1)] public 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)] public class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] [NullableContext(0)] private static class SnatchCurrentlyHandlingRPC { [Nullable(2)] public static ZRpc currentRpc; [NullableContext(1)] [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] [NullableContext(0)] internal static class RegisterRPCPatch { [CompilerGenerated] private sealed class <g__WatchAdminListChanges|0_0>d : IEnumerator, IDisposable, IEnumerator { private int <>1__state; private object <>2__current; private <>c__DisplayClass0_0 <>8__1; [Nullable(new byte[] { 0, 1 })] private List 5__2; object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <g__WatchAdminListChanges|0_0>d(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>8__1 = null; 5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Expected O, but got Unknown //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -1; if (!<>8__1.adminList.GetList().SequenceEqual(5__2)) { 5__2 = new List(<>8__1.adminList.GetList()); List list = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)<>8__1.listContainsId != null) ? ((bool)<>8__1.listContainsId.Invoke(ZNet.instance, new object[2] { <>8__1.adminList, hostName })) : <>8__1.adminList.Contains(hostName); }).ToList(); g__SendAdmin|0_1(ZNet.instance.GetPeers().Except(list).ToList(), isAdmin: false); g__SendAdmin|0_1(list, isAdmin: true); } } else { <>1__state = -1; <>8__1 = new <>c__DisplayClass0_0(); <>8__1.listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); <>8__1.adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); 5__2 = new List(<>8__1.adminList.GetList()); } <>2__current = (object)new WaitForSeconds(30f); <>1__state = 1; return true; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class <>c__DisplayClass0_0 { public MethodInfo listContainsId; public SyncedList adminList; public Func <>9__2; internal bool b__2(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); if ((object)listContainsId != null) { return (bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName }); } return adminList.Contains(hostName); } } [NullableContext(1)] [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync in configSyncs) { ZRoutedRpc.instance.Register(configSync.Name + " ConfigSync", (Action)configSync.RPC_FromOtherClientConfigSync); if (isServer) { configSync.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } [IteratorStateMachine(typeof(<g__WatchAdminListChanges|0_0>d))] [NullableContext(1)] static IEnumerator WatchAdminListChanges() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <g__WatchAdminListChanges|0_0>d(0); } } [NullableContext(1)] [CompilerGenerated] internal static void g__SendAdmin|0_1(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)); } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [NullableContext(0)] private static class RegisterClientRPCPatch { [NullableContext(1)] [HarmonyPostfix] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register(configSync.Name + " ConfigSync", (Action)configSync.RPC_FromServerConfigSync); } } } [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; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [Nullable(0)] private class SendConfigsAfterLogin { [Nullable(0)] private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished; public volatile int versionMatchQueued = -1; public readonly List Package = new List(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFabSocket)this)..ctor(); } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [CompilerGenerated] private sealed class <>c__DisplayClass2_0 { [Nullable(0)] public ZRpc rpc; [Nullable(0)] public ZNet __instance; [Nullable(new byte[] { 0, 1, 1 })] public Dictionary __state; [Nullable(0)] public ZNetPeer peer; } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix([Nullable(new byte[] { 2, 1, 1 })] ref Dictionary __state, ZNet __instance, ZRpc rpc) { //IL_0073: Unknown result type (might be due to invalid IL or missing references) if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend != 0) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); object? value = fieldInfo.GetValue(val); ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null); if (val2 != null) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId); } fieldInfo.SetValue(val, bufferingSocket); } if (__state == null) { __state = new Dictionary(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary __state, ZNet __instance, ZRpc rpc) { <>c__DisplayClass2_0 CS$<>8__locals0 = new <>c__DisplayClass2_0(); CS$<>8__locals0.rpc = rpc; CS$<>8__locals0.__instance = __instance; CS$<>8__locals0.__state = __state; if (CS$<>8__locals0.__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(CS$<>8__locals0.__instance, new object[1] { CS$<>8__locals0.rpc }); CS$<>8__locals0.peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (CS$<>8__locals0.peer == null) { SendBufferedData(); } else { ((MonoBehaviour)CS$<>8__locals0.__instance).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (CS$<>8__locals0.rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(CS$<>8__locals0.rpc, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(CS$<>8__locals0.__instance, new object[1] { CS$<>8__locals0.rpc }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = CS$<>8__locals0.__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(); } } [IteratorStateMachine(typeof(<>c__DisplayClass2_0.<g__sendAsync|1>d))] IEnumerator sendAsync() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <>c__DisplayClass2_0.<g__sendAsync|1>d(0) { <>4__this = CS$<>8__locals0 }; } } } [Nullable(0)] private class PackageEntry { public string section; public string key; public Type type; [Nullable(2)] public object value; } [NullableContext(0)] [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [NullableContext(1)] [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [NullableContext(0)] [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [NullableContext(1)] [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } [Nullable(0)] private class InvalidDeserializationTypeException : Exception { public string expected; public string received; public string field = ""; } [CompilerGenerated] private sealed class <>c__DisplayClass55_0 { [Nullable(0)] public ZNetPeer peer; [Nullable(0)] public ConfigSync <>4__this; [Nullable(0)] public ZRoutedRpc rpc; } [CompilerGenerated] private sealed class <>c__DisplayClass57_0 { [Nullable(0)] public ConfigSync <>4__this; [Nullable(0)] public ZPackage package; [NullableContext(0)] internal IEnumerator b__1(ZNetPeer p) { return <>4__this.distributeConfigToPeers(p, package); } } [CompilerGenerated] private sealed class d__55 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; private bool <>2__current; [Nullable(0)] public ZNetPeer peer; [Nullable(0)] public ConfigSync <>4__this; [Nullable(0)] public ZPackage package; [Nullable(0)] private <>c__DisplayClass55_0 <>8__1; [Nullable(0)] private byte[] 5__2; private int 5__3; private long 5__4; private int 5__5; [Nullable(0)] private IEnumerator <>7__wrap5; bool IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__55(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { switch (<>1__state) { case -3: case 1: try { } finally { <>m__Finally1(); } break; case -4: case 3: try { } finally { <>m__Finally2(); } break; } <>8__1 = null; 5__2 = null; <>7__wrap5 = null; <>1__state = -2; } private bool MoveNext() { //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Expected O, but got Unknown try { ZPackage val; int num; switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>8__1 = new <>c__DisplayClass55_0(); <>8__1.peer = peer; <>8__1.<>4__this = <>4__this; <>8__1.rpc = ZRoutedRpc.instance; if (<>8__1.rpc == null) { return false; } 5__2 = package.GetArray(); if (5__2 != null && 5__2.LongLength > 250000) { 5__3 = (int)(1 + (5__2.LongLength - 1) / 250000); 5__4 = ++packageCounter; 5__5 = 0; goto IL_020f; } <>7__wrap5 = waitForQueue().GetEnumerator(); <>1__state = -4; goto IL_026a; case 1: <>1__state = -3; goto IL_0130; case 2: <>1__state = -1; goto IL_01fd; case 3: { <>1__state = -4; goto IL_026a; } IL_0130: if (<>7__wrap5.MoveNext()) { bool current = <>7__wrap5.Current; <>2__current = current; <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap5 = null; if (!<>8__1.peer.m_socket.IsConnected()) { return false; } val = new ZPackage(); val.Write((byte)2); val.Write(5__4); val.Write(5__5); val.Write(5__3); val.Write(5__2.Skip(250000 * 5__5).Take(250000).ToArray()); SendPackage(val); if (5__5 != 5__3 - 1) { <>2__current = true; <>1__state = 2; return true; } goto IL_01fd; IL_01fd: num = 5__5 + 1; 5__5 = num; goto IL_020f; IL_026a: if (<>7__wrap5.MoveNext()) { bool current2 = <>7__wrap5.Current; <>2__current = current2; <>1__state = 3; return true; } <>m__Finally2(); <>7__wrap5 = null; SendPackage(package); break; IL_020f: if (5__5 < 5__3) { <>7__wrap5 = waitForQueue().GetEnumerator(); <>1__state = -3; goto IL_0130; } break; } return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } void SendPackage(ZPackage pkg) { string text = ((<>c__DisplayClass55_0)this).<>4__this.Name + " ConfigSync"; if (isServer) { ((<>c__DisplayClass55_0)this).peer.m_rpc.Invoke(text, new object[1] { pkg }); } else { ((<>c__DisplayClass55_0)this).rpc.InvokeRoutedRPC(((<>c__DisplayClass55_0)this).peer.m_server ? 0 : ((<>c__DisplayClass55_0)this).peer.m_uid, text, new object[1] { pkg }); } } [IteratorStateMachine(typeof(<>c__DisplayClass55_0.<g__waitForQueue|0>d))] IEnumerable waitForQueue() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <>c__DisplayClass55_0.<g__waitForQueue|0>d(-2) { <>4__this = this }; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap5 != null) { <>7__wrap5.Dispose(); } } private void <>m__Finally2() { <>1__state = -1; if (<>7__wrap5 != null) { <>7__wrap5.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class d__57 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; [Nullable(0)] public ConfigSync <>4__this; [Nullable(0)] public ZPackage package; [Nullable(new byte[] { 0, 1 })] public List peers; [Nullable(new byte[] { 0, 1 })] private List> 5__2; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__57(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown switch (<>1__state) { default: return false; case 0: { <>1__state = -1; <>c__DisplayClass57_0 CS$<>8__locals0 = new <>c__DisplayClass57_0 { <>4__this = <>4__this, package = package }; if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return false; } byte[] array = CS$<>8__locals0.package.GetArray(); if (array != null && array.LongLength > 10000) { ZPackage val = new ZPackage(); val.Write((byte)4); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal)) { deflateStream.Write(array, 0, array.Length); } val.Write(memoryStream.ToArray()); CS$<>8__locals0.package = val; } 5__2 = (from peer in peers where peer.IsReady() select peer into p select CS$<>8__locals0.<>4__this.distributeConfigToPeers(p, CS$<>8__locals0.package)).ToList(); 5__2.RemoveAll((IEnumerator writer) => !writer.MoveNext()); break; } case 1: <>1__state = -1; 5__2.RemoveAll((IEnumerator writer) => !writer.MoveNext()); break; } if (5__2.Count > 0) { <>2__current = null; <>1__state = 1; return true; } 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 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; 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; 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_0051; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag.GetValueOrDefault(); } if (num) { return !lockExempt; } goto IL_0051; IL_0051: return false; } set { forceConfigLocking = value; } } public bool IsAdmin { get { if (!lockExempt) { return isSourceOfTruth; } return true; } } public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } [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_0209: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Expected O, but got Unknown //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Expected O, but got Unknown //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(([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) { MemoryStream stream = new MemoryStream(package.ReadByteArray()); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; val2.Save(); } foreach (KeyValuePair customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary dictionary = allConfigs.Where([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; } if (!configSync.IsSourceOfTruth && config.SynchronizedConfig && config.LocalBaseValue != null) { if (!configSync.IsLocked) { if (config == configSync.lockedConfig) { return lockExempt; } return true; } return false; } return true; } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where([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(); } [IteratorStateMachine(typeof(d__55))] private IEnumerator distributeConfigToPeers(ZNetPeer peer, ZPackage package) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__55(0) { <>4__this = this, peer = peer, package = package }; } 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); } [IteratorStateMachine(typeof(d__57))] private IEnumerator sendZPackage(List peers, ZPackage package) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__57(0) { <>4__this = this, peers = peers, package = package }; } 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) { if (!type.IsEnum) { return type; } return Enum.GetUnderlyingType(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_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: 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(partial ? ((byte)1) : ((byte)0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty()) { AddEntryToPackage(val, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(val, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(val, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return val; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, [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)] [HarmonyPatch] [PublicAPI] [Nullable(0)] public 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 { string text = minimumRequiredVersion; if (text == null) { if (!ModRequired) { return "0.0.0"; } text = CurrentVersion; } return text; } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null)); if (patchInfo != null && patchInfo.Postfixes.Count([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 num = new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion); bool flag = new System.Version(ReceivedCurrentVersion) >= new System.Version(MinimumRequiredVersion); return num && flag; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } bool flag = new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion); if (CurrentVersion == "0.0.1") { WMRecipeCust.ConnectionError = "WackysDatabase You started a Local Game before Multiplayer. That is Not allowed. -Restart Game"; return "WackysDatabase You started a Local Game before Multiplayer. That is Not allowed. -Restart Game"; } if (!flag) { return DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + "."; } return DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + "."; } private string ErrorServer(ZRpc rpc) { return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion; } private string Error([Nullable(2)] ZRpc rpc = null) { if (rpc != null) { return ErrorServer(rpc); } return ErrorClient(); } 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(); } public 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); } } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; for (int i = 0; i < array2.Length; i++) { Debug.LogWarning((object)array2[i].Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPrefix] [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Expected O, but got Unknown notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck"))) { object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")]; Action action = (Action)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register("ServerSync VersionCheck", (Action)([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); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] [HarmonyPostfix] private static void ShowConnectionError(FejdStartup __instance) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 //IL_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_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: 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_0216: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_0226: 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 (WMRecipeCust.ConnectionError != "") { TMP_Text connectionFailedError3 = __instance.m_connectionFailedError; connectionFailedError3.text = connectionFailedError3.text + "\n " + WMRecipeCust.ConnectionError + " 0.0.1"; 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 PieceManager { [PublicAPI] public enum CraftingTable { None, [InternalName("piece_workbench")] Workbench, [InternalName("piece_cauldron")] Cauldron, [InternalName("forge")] Forge, [InternalName("piece_artisanstation")] ArtisanTable, [InternalName("piece_stonecutter")] StoneCutter, [InternalName("piece_magetable")] MageTable, [InternalName("blackforge")] BlackForge, [InternalName("piece_preptable")] FoodPreparationTable, [InternalName("piece_MeadCauldron")] MeadKetill, Custom } [NullableContext(1)] [Nullable(0)] public class InternalName : Attribute { public readonly string internalName; public InternalName(string internalName) { this.internalName = internalName; } } [NullableContext(1)] [Nullable(0)] [PublicAPI] public class ExtensionList { public readonly List ExtensionStations = new List(); public void Set(CraftingTable table, int maxStationDistance = 5) { ExtensionStations.Add(new ExtensionConfig { Table = table, maxStationDistance = maxStationDistance }); } public void Set(string customTable, int maxStationDistance = 5) { ExtensionStations.Add(new ExtensionConfig { Table = CraftingTable.Custom, custom = customTable, maxStationDistance = maxStationDistance }); } } public struct ExtensionConfig { public CraftingTable Table; public float maxStationDistance; [Nullable(2)] public string custom; } [Nullable(0)] [NullableContext(1)] [PublicAPI] public class CraftingStationList { public readonly List Stations = new List(); public void Set(CraftingTable table) { Stations.Add(new CraftingStationConfig { Table = table }); } public void Set(string customTable) { Stations.Add(new CraftingStationConfig { Table = CraftingTable.Custom, custom = customTable }); } } public struct CraftingStationConfig { public CraftingTable Table; public int level; [Nullable(2)] public string custom; } [PublicAPI] public enum BuildPieceCategory { Misc = 0, Crafting = 1, BuildingWorkbench = 2, BuildingStonecutter = 3, Furniture = 4, All = 100, Custom = 99 } [NullableContext(1)] [Nullable(0)] [PublicAPI] public class RequiredResourcesList { public readonly List Requirements = new List(); public void Add(string item, int amount, bool recover) { Requirements.Add(new Requirement { itemName = item, amount = amount, recover = recover }); } } public struct Requirement { [Nullable(1)] public string itemName; public int amount; public bool recover; } public struct SpecialProperties { [Description("Admins should be the only ones that can build this piece.")] public bool AdminOnly; [Description("Turns off generating a config for this build piece.")] public bool NoConfig; } [PublicAPI] [Nullable(0)] [NullableContext(1)] public class BuildingPieceCategory { public BuildPieceCategory Category; public string custom = ""; public void Set(BuildPieceCategory category) { Category = category; } public void Set(string customCategory) { Category = BuildPieceCategory.Custom; custom = customCategory; } } [PublicAPI] [NullableContext(1)] [Nullable(0)] public class PieceTool { public readonly HashSet Tools = new HashSet(); public void Add(string tool) { Tools.Add(tool); } } [Nullable(0)] [PublicAPI] [NullableContext(1)] public class BuildPiece { [Nullable(0)] internal class PieceConfig { public ConfigEntry craft; public ConfigEntry category; public ConfigEntry customCategory; public ConfigEntry tools; public ConfigEntry extensionTable; public ConfigEntry customExtentionTable; public ConfigEntry maxStationDistance; public ConfigEntry table; public ConfigEntry customTable; } [NullableContext(0)] private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [UsedImplicitly] [Nullable(2)] public string Category; [Nullable(new byte[] { 2, 1 })] [UsedImplicitly] public Action CustomDrawer; } [Nullable(0)] private class SerializedRequirements { public readonly List Reqs; public SerializedRequirements(List reqs) { Reqs = reqs; } public SerializedRequirements(string reqs) { Reqs = reqs.Split(new char[1] { ',' }).Select([NullableContext(0)] (string r) => { string[] array = r.Split(new char[1] { ':' }); Requirement result = default(Requirement); result.itemName = array[0]; result.amount = ((array.Length <= 1 || !int.TryParse(array[1], out var result2)) ? 1 : result2); bool result3 = default(bool); result.recover = array.Length <= 2 || !bool.TryParse(array[2], out result3) || result3; return result; }).ToList(); } public override string ToString() { return string.Join(",", Reqs.Select([NullableContext(0)] (Requirement r) => $"{r.itemName}:{r.amount}:{r.recover}")); } [return: Nullable(2)] public static ItemDrop fetchByName(ObjectDB objectDB, string name) { GameObject itemPrefab = objectDB.GetItemPrefab(name); ItemDrop obj = ((itemPrefab != null) ? itemPrefab.GetComponent() : null); if ((Object)(object)obj == (Object)null) { Debug.LogWarning((object)(((!string.IsNullOrWhiteSpace(((Object)plugin).name)) ? ("[" + ((Object)plugin).name + "]") : "") + " The required item '" + name + "' does not exist.")); } return obj; } public static Requirement[] toPieceReqs(SerializedRequirements craft) { return craft.Reqs.Where((Requirement r) => r.itemName != "").ToDictionary((Func)([NullableContext(0)] (Requirement r) => r.itemName), (Func)([NullableContext(0)] (Requirement r) => { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown ItemDrop val = ResItem(r); return (val != null) ? new Requirement { m_amount = r.amount, m_resItem = val, m_recover = r.recover } : ((Requirement)null); })).Values.Where([NullableContext(0)] (Requirement v) => v != null).ToArray(); [NullableContext(2)] static ItemDrop ResItem(Requirement r) { return fetchByName(ObjectDB.instance, r.itemName); } } } internal static readonly List registeredPieces = new List(); private static readonly Dictionary pieceMap = new Dictionary(); internal static Dictionary pieceConfigs = new Dictionary(); internal List Conversions = new List(); internal List conversions = new List(); [Description("Disables generation of the configs for your pieces. This is global, this turns it off for all pieces in your mod.")] public static bool ConfigurationEnabled = true; public readonly GameObject Prefab; [Description("Specifies the resources needed to craft the piece.\nUse .Add to add resources with their internal ID and an amount.\nUse one .Add for each resource type the building piece should need.")] public readonly RequiredResourcesList RequiredItems = new RequiredResourcesList(); [Description("Sets the category for the building piece.")] public readonly BuildingPieceCategory Category = new BuildingPieceCategory(); [Description("Specifies the tool needed to build your piece.\nUse .Add to add a tool.")] public readonly PieceTool Tool = new PieceTool(); [Description("Specifies the crafting station needed to build your piece.\nUse .Add to add a crafting station, using the CraftingTable enum and a minimum level for the crafting station.")] public CraftingStationList Crafting = new CraftingStationList(); [Description("Makes this piece a station extension")] public ExtensionList Extension = new ExtensionList(); [Description("Change the extended/special properties of your build piece.")] public SpecialProperties SpecialProperties; [Nullable(2)] [Description("Specifies a config entry which toggles whether a recipe is active.")] public ConfigEntryBase RecipeIsActive; [Nullable(2)] private LocalizeKey _name; [Nullable(2)] private LocalizeKey _description; internal string[] activeTools; [Nullable(2)] private static object configManager; [Nullable(2)] private static Localization _english; [Nullable(2)] internal static BaseUnityPlugin _plugin = null; private static bool hasConfigSync = true; [Nullable(2)] private static object _configSync; public LocalizeKey Name { get { LocalizeKey name = _name; if (name != null) { return name; } Piece component = Prefab.GetComponent(); if (component.m_name.StartsWith("$")) { _name = new LocalizeKey(component.m_name); } else { string text = "$piece_" + ((Object)Prefab).name.Replace(" ", "_"); _name = new LocalizeKey(text).English(component.m_name); component.m_name = text; } return _name; } } public LocalizeKey Description { get { LocalizeKey description = _description; if (description != null) { return description; } Piece component = Prefab.GetComponent(); if (component.m_description.StartsWith("$")) { _description = new LocalizeKey(component.m_description); } else { string text = "$piece_" + ((Object)Prefab).name.Replace(" ", "_") + "_description"; _description = new LocalizeKey(text).English(component.m_description); component.m_description = text; } return _description; } } private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English")); internal static BaseUnityPlugin plugin { get { //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Expected O, but got Unknown if (_plugin != null) { return _plugin; } IEnumerable source; try { source = Assembly.GetExecutingAssembly().DefinedTypes.ToList(); } catch (ReflectionTypeLoadException ex) { source = from t in ex.Types where t != null select t.GetTypeInfo(); } _plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); return _plugin; } } [Nullable(2)] private static object configSync { [NullableContext(2)] get { if (_configSync != null || !hasConfigSync) { return _configSync; } Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync"); if ((object)type != null) { _configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " PieceManager"); type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString()); type.GetProperty("IsLocked").SetValue(_configSync, true); } else { hasConfigSync = false; } return _configSync; } } public BuildPiece(string assetBundleFileName, string prefabName, string folderName = "assets") : this(PiecePrefabManager.RegisterAssetBundle(assetBundleFileName, folderName), prefabName) { } public BuildPiece(AssetBundle bundle, string prefabName) { Prefab = PiecePrefabManager.RegisterPrefab(bundle, prefabName); registeredPieces.Add(this); } public static void BuildTableConfigChangedWacky(Piece piecePrefab, string wantedcategory) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_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) if (Enum.TryParse(wantedcategory, ignoreCase: true, out PieceCategory _)) { piecePrefab.m_category = PiecePrefabManager.GetCategory(wantedcategory); } else { piecePrefab.m_category = PiecePrefabManager.GetCategory(wantedcategory); } if (Object.op_Implicit((Object)(object)Hud.instance)) { PiecePrefabManager.CreateCategoryTabs(); } } internal static void Patch_FejdStartup(FejdStartup __instance) { //IL_00e9: 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_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_029e: Expected O, but got Unknown //IL_0337: Unknown result type (might be due to invalid IL or missing references) //IL_0341: Expected O, but got Unknown //IL_03d3: Unknown result type (might be due to invalid IL or missing references) //IL_03af: Unknown result type (might be due to invalid IL or missing references) //IL_03b4: Unknown result type (might be due to invalid IL or missing references) //IL_0428: Unknown result type (might be due to invalid IL or missing references) //IL_0432: Expected O, but got Unknown //IL_0586: Unknown result type (might be due to invalid IL or missing references) //IL_0590: Expected O, but got Unknown //IL_0849: Unknown result type (might be due to invalid IL or missing references) //IL_0853: Expected O, but got Unknown //IL_05f6: Unknown result type (might be due to invalid IL or missing references) //IL_0600: Expected O, but got Unknown //IL_0697: Unknown result type (might be due to invalid IL or missing references) //IL_06a1: Expected O, but got Unknown //IL_08b9: Unknown result type (might be due to invalid IL or missing references) //IL_08c3: Expected O, but got Unknown //IL_0ac1: Unknown result type (might be due to invalid IL or missing references) //IL_0acb: Expected O, but got Unknown //IL_0b5a: Unknown result type (might be due to invalid IL or missing references) //IL_0b64: Expected O, but got Unknown Type configManagerType = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault([NullableContext(0)] (Assembly a) => a.GetName().Name == "ConfigurationManager")?.GetType("ConfigurationManager.ConfigurationManager"); configManager = ((configManagerType == null) ? null : Chainloader.ManagerObject.GetComponent(configManagerType)); foreach (BuildPiece registeredPiece in registeredPieces) { registeredPiece.activeTools = registeredPiece.Tool.Tools.DefaultIfEmpty("Hammer").ToArray(); if (registeredPiece.Category.Category != BuildPieceCategory.Custom) { registeredPiece.Prefab.GetComponent().m_category = (PieceCategory)registeredPiece.Category.Category; } else { registeredPiece.Prefab.GetComponent().m_category = PiecePrefabManager.GetCategory(registeredPiece.Category.custom); } } if (!ConfigurationEnabled) { return; } bool saveOnConfigSet = plugin.Config.SaveOnConfigSet; plugin.Config.SaveOnConfigSet = false; foreach (BuildPiece registeredPiece2 in registeredPieces) { BuildPiece piece = registeredPiece2; if (piece.SpecialProperties.NoConfig) { continue; } PieceConfig pieceConfig2 = (pieceConfigs[piece] = new PieceConfig()); PieceConfig cfg = pieceConfig2; Piece piecePrefab2 = piece.Prefab.GetComponent(); string pieceName = piecePrefab2.m_name; string englishName = new Regex("[=\\n\\t\\\\\"\\'\\[\\]]*").Replace(english.Localize(pieceName), "").Trim(); string localizedName = Localization.instance.Localize(pieceName).Trim(); int order = 0; cfg.category = config(englishName, "Build Table Category", piece.Category.Category, new ConfigDescription("Build Category where " + localizedName + " is available.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = (order -= 1), Category = localizedName } })); ConfigurationManagerAttributes customTableAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), Browsable = (cfg.category.Value == BuildPieceCategory.Custom), Category = localizedName }; cfg.customCategory = config(englishName, "Custom Build Category", piece.Category.custom, new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes })); cfg.category.SettingChanged += BuildTableConfigChanged; cfg.customCategory.SettingChanged += BuildTableConfigChanged; if (cfg.category.Value == BuildPieceCategory.Custom) { piecePrefab2.m_category = PiecePrefabManager.GetCategory(cfg.customCategory.Value); } else { piecePrefab2.m_category = (PieceCategory)cfg.category.Value; } cfg.tools = config(englishName, "Tools", string.Join(", ", piece.activeTools), new ConfigDescription("Comma separated list of tools where " + localizedName + " is available.", (AcceptableValueBase)null, new object[1] { customTableAttributes })); piece.activeTools = (from s in cfg.tools.Value.Split(new char[1] { ',' }) select s.Trim()).ToArray(); cfg.tools.SettingChanged += [NullableContext(0)] (object _, EventArgs _) => { Inventory[] source = (from c in Player.s_players.Select([NullableContext(0)] (Player p) => ((Humanoid)p).GetInventory()).Concat(from c in Object.FindObjectsByType((FindObjectsSortMode)0) select c.GetInventory()) where c != null select c).ToArray(); Dictionary> dictionary = (from kv in (from i in (from p in ObjectDB.instance.m_items select p.GetComponent() into c where Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((Component)c).GetComponent()) select c).Concat(ItemDrop.s_instances) select new KeyValuePair(Utils.GetPrefabName(((Component)i).gameObject), i.m_itemData)).Concat(from i in source.SelectMany([NullableContext(0)] (Inventory i) => i.GetAllItems()) select new KeyValuePair(((Object)i.m_dropPrefab).name, i)) where Object.op_Implicit((Object)(object)kv.Value.m_shared.m_buildPieces) group kv by kv.Key).ToDictionary([NullableContext(0)] (IGrouping> g) => g.Key, [NullableContext(0)] (IGrouping> g) => g.Select([NullableContext(0)] (KeyValuePair kv) => kv.Value.m_shared.m_buildPieces).Distinct().ToList()); string[] array5 = piece.activeTools; foreach (string key in array5) { if (dictionary.TryGetValue(key, out var value2)) { foreach (PieceTable item3 in value2) { item3.m_pieces.Remove(piece.Prefab); } } } piece.activeTools = (from s in cfg.tools.Value.Split(new char[1] { ',' }) select s.Trim()).ToArray(); if (Object.op_Implicit((Object)(object)ObjectDB.instance)) { array5 = piece.activeTools; foreach (string key2 in array5) { if (dictionary.TryGetValue(key2, out var value3)) { foreach (PieceTable item4 in value3) { if (!item4.m_pieces.Contains(piece.Prefab)) { item4.m_pieces.Add(piece.Prefab); } } } } if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)Player.m_localPlayer.m_buildPieces)) { PiecePrefabManager.CategoryRefreshNeeded = true; ((Humanoid)Player.m_localPlayer).SetPlaceMode(Player.m_localPlayer.m_buildPieces); } } }; StationExtension pieceExtensionComp; List hideWhenNoneAttributes2; if (piece.Extension.ExtensionStations.Count > 0) { pieceExtensionComp = piece.Prefab.GetOrAddComponent(); PieceConfig pieceConfig3 = cfg; string group = englishName; CraftingTable table = piece.Extension.ExtensionStations.First().Table; string text = "Crafting station that " + localizedName + " extends."; object[] array = new object[1]; ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes(); int num = order - 1; order = num; configurationManagerAttributes.Order = num; array[0] = configurationManagerAttributes; pieceConfig3.extensionTable = config(group, "Extends Station", table, new ConfigDescription(text, (AcceptableValueBase)null, array)); cfg.customExtentionTable = config(englishName, "Custom Extend Station", piece.Extension.ExtensionStations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes })); PieceConfig pieceConfig4 = cfg; string group2 = englishName; float maxStationDistance = piece.Extension.ExtensionStations.First().maxStationDistance; string text2 = "Distance from the station that " + localizedName + " can be placed."; object[] array2 = new object[1]; ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes(); num = order - 1; order = num; configurationManagerAttributes2.Order = num; array2[0] = configurationManagerAttributes2; pieceConfig4.maxStationDistance = config(group2, "Max Station Distance", maxStationDistance, new ConfigDescription(text2, (AcceptableValueBase)null, array2)); hideWhenNoneAttributes2 = new List(); cfg.extensionTable.SettingChanged += ExtensionTableConfigChanged; cfg.customExtentionTable.SettingChanged += ExtensionTableConfigChanged; cfg.maxStationDistance.SettingChanged += ExtensionTableConfigChanged; ConfigurationManagerAttributes configurationManagerAttributes3 = new ConfigurationManagerAttributes(); num = order - 1; order = num; configurationManagerAttributes3.Order = num; configurationManagerAttributes3.Browsable = cfg.extensionTable.Value != CraftingTable.None; ConfigurationManagerAttributes item = configurationManagerAttributes3; hideWhenNoneAttributes2.Add(item); } List hideWhenNoneAttributes; if (piece.Crafting.Stations.Count > 0) { hideWhenNoneAttributes = new List(); PieceConfig pieceConfig5 = cfg; string group3 = englishName; CraftingTable table2 = piece.Crafting.Stations.First().Table; string text3 = "Crafting station where " + localizedName + " is available."; object[] array3 = new object[1]; ConfigurationManagerAttributes configurationManagerAttributes4 = new ConfigurationManagerAttributes(); int num = order - 1; order = num; configurationManagerAttributes4.Order = num; array3[0] = configurationManagerAttributes4; pieceConfig5.table = config(group3, "Crafting Station", table2, new ConfigDescription(text3, (AcceptableValueBase)null, array3)); cfg.customTable = config(englishName, "Custom Crafting Station", piece.Crafting.Stations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes })); cfg.table.SettingChanged += TableConfigChanged; cfg.customTable.SettingChanged += TableConfigChanged; ConfigurationManagerAttributes configurationManagerAttributes5 = new ConfigurationManagerAttributes(); num = order - 1; order = num; configurationManagerAttributes5.Order = num; configurationManagerAttributes5.Browsable = cfg.table.Value != CraftingTable.None; ConfigurationManagerAttributes item2 = configurationManagerAttributes5; hideWhenNoneAttributes.Add(item2); } cfg.craft = itemConfig("Crafting Costs", new SerializedRequirements(piece.RequiredItems.Requirements).ToString(), "Item costs to craft " + localizedName); cfg.craft.SettingChanged += [NullableContext(0)] (object _, EventArgs _) => { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && (Object)(object)ObjectDB.instance.GetItemPrefab("YmirRemains") != (Object)null) { Requirement[] resources = SerializedRequirements.toPieceReqs(new SerializedRequirements(cfg.craft.Value)); piecePrefab2.m_resources = resources; Piece[] array4 = Object.FindObjectsByType((FindObjectsSortMode)0); foreach (Piece val in array4) { if (val.m_name == pieceName) { val.m_resources = resources; } } } }; for (int j = 0; j < piece.Conversions.Count; j++) { string text4 = ((piece.Conversions.Count > 1) ? $"{j + 1}. " : ""); Conversion conversion = piece.Conversions[j]; conversion.config = new Conversion.ConversionConfig(); int index = j; conversion.config.input = config(englishName, text4 + "Conversion Input Item", conversion.Input, new ConfigDescription("Conversion input item within " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName } })); conversion.config.input.SettingChanged += [NullableContext(0)] (object _, EventArgs _) => { if (index < piece.conversions.Count) { ObjectDB instance2 = ObjectDB.instance; if (instance2 != null) { ItemDrop from = SerializedRequirements.fetchByName(instance2, conversion.config.input.Value); piece.conversions[index].m_from = from; } } }; conversion.config.output = config(englishName, text4 + "Conversion Output Item", conversion.Output, new ConfigDescription("Conversion output item within " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName } })); conversion.config.output.SettingChanged += [NullableContext(0)] (object _, EventArgs _) => { if (index < piece.conversions.Count) { ObjectDB instance = ObjectDB.instance; if (instance != null) { ItemDrop to = SerializedRequirements.fetchByName(instance, conversion.config.output.Value); piece.conversions[index].m_to = to; } } }; } void BuildTableConfigChanged(object o, EventArgs e) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) if (registeredPieces.Count > 0) { if (cfg.category.Value == BuildPieceCategory.Custom) { piecePrefab2.m_category = PiecePrefabManager.GetCategory(cfg.customCategory.Value); } else { piecePrefab2.m_category = (PieceCategory)cfg.category.Value; } if (Object.op_Implicit((Object)(object)Hud.instance)) { PiecePrefabManager.CategoryRefreshNeeded = true; PiecePrefabManager.CreateCategoryTabs(); } } customTableAttributes.Browsable = cfg.category.Value == BuildPieceCategory.Custom; ReloadConfigDisplay(); } void ExtensionTableConfigChanged(object o, EventArgs e) { if (piece.RequiredItems.Requirements.Count > 0) { if (cfg.extensionTable.Value == CraftingTable.Custom) { StationExtension obj2 = pieceExtensionComp; GameObject prefab2 = ZNetScene.instance.GetPrefab(cfg.customExtentionTable.Value); obj2.m_craftingStation = ((prefab2 != null) ? prefab2.GetComponent() : null); } else { pieceExtensionComp.m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(cfg.extensionTable.Value.ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent(); } pieceExtensionComp.m_maxStationDistance = cfg.maxStationDistance.Value; } customTableAttributes.Browsable = cfg.extensionTable.Value == CraftingTable.Custom; foreach (ConfigurationManagerAttributes item5 in hideWhenNoneAttributes2) { item5.Browsable = cfg.extensionTable.Value != CraftingTable.None; } ReloadConfigDisplay(); plugin.Config.Save(); } void TableConfigChanged(object o, EventArgs e) { if (piece.RequiredItems.Requirements.Count > 0) { switch (cfg.table.Value) { case CraftingTable.None: piecePrefab2.m_craftingStation = null; break; case CraftingTable.Custom: { Piece obj = piecePrefab2; GameObject prefab = ZNetScene.instance.GetPrefab(cfg.customTable.Value); obj.m_craftingStation = ((prefab != null) ? prefab.GetComponent() : null); break; } default: piecePrefab2.m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(cfg.table.Value.ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent(); break; } } customTableAttributes.Browsable = cfg.table.Value == CraftingTable.Custom; foreach (ConfigurationManagerAttributes item6 in hideWhenNoneAttributes) { item6.Browsable = cfg.table.Value != CraftingTable.None; } ReloadConfigDisplay(); plugin.Config.Save(); } ConfigEntry itemConfig(string name, string value, string desc) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown ConfigurationManagerAttributes configurationManagerAttributes6 = new ConfigurationManagerAttributes { CustomDrawer = DrawConfigTable, Order = (order -= 1), Category = localizedName }; return config(englishName, name, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes6 })); } } foreach (BuildPiece registeredPiece3 in registeredPieces) { ConfigEntryBase enabledCfg = registeredPiece3.RecipeIsActive; Piece piecePrefab; if (enabledCfg != null) { piecePrefab = registeredPiece3.Prefab.GetComponent(); ConfigChanged(null, null); ((object)enabledCfg).GetType().GetEvent("SettingChanged").AddEventHandler(enabledCfg, new EventHandler(ConfigChanged)); } registeredPiece3.InitializeNewRegisteredPiece(registeredPiece3); [NullableContext(2)] void ConfigChanged(object o, EventArgs e) { piecePrefab.m_enabled = (int)enabledCfg.BoxedValue != 0; } } if (saveOnConfigSet) { plugin.Config.SaveOnConfigSet = true; plugin.Config.Save(); } void ReloadConfigDisplay() { object obj3 = configManagerType?.GetProperty("DisplayingWindow").GetValue(configManager); if (obj3 is bool && (bool)obj3) { configManagerType.GetMethod("BuildSettingList").Invoke(configManager, Array.Empty()); } } } private void InitializeNewRegisteredPiece(BuildPiece piece) { ConfigEntryBase recipeIsActive = piece.RecipeIsActive; PieceConfig cfg; Piece piecePrefab; string pieceName; if (recipeIsActive != null) { pieceConfigs.TryGetValue(piece, out cfg); piecePrefab = piece.Prefab.GetComponent(); pieceName = piecePrefab.m_name; ((object)recipeIsActive).GetType().GetEvent("SettingChanged").AddEventHandler(recipeIsActive, new EventHandler(ConfigChanged)); } void ConfigChanged(object o, EventArgs e) { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && (Object)(object)ObjectDB.instance.GetItemPrefab("YmirRemains") != (Object)null && cfg != null) { Requirement[] resources = SerializedRequirements.toPieceReqs(new SerializedRequirements(cfg.craft.Value)); piecePrefab.m_resources = resources; Piece[] array = Object.FindObjectsByType((FindObjectsSortMode)0); foreach (Piece val in array) { if (val.m_name == pieceName) { val.m_resources = resources; } } } } } [HarmonyPriority(700)] internal static void Patch_ObjectDBInit(ObjectDB __instance) { //IL_0441: Unknown result type (might be due to invalid IL or missing references) //IL_0446: Unknown result type (might be due to invalid IL or missing references) //IL_0479: Unknown result type (might be due to invalid IL or missing references) //IL_04b1: Expected O, but got Unknown if ((Object)(object)__instance.GetItemPrefab("YmirRemains") == (Object)null) { return; } foreach (BuildPiece registeredPiece in registeredPieces) { pieceConfigs.TryGetValue(registeredPiece, out var value); registeredPiece.Prefab.GetComponent().m_resources = SerializedRequirements.toPieceReqs((value == null) ? new SerializedRequirements(registeredPiece.RequiredItems.Requirements) : new SerializedRequirements(value.craft.Value)); foreach (ExtensionConfig extensionStation in registeredPiece.Extension.ExtensionStations) { switch ((value == null || registeredPiece.Extension.ExtensionStations.Count > 1) ? extensionStation.Table : value.extensionTable.Value) { case CraftingTable.None: registeredPiece.Prefab.GetComponent().m_craftingStation = null; break; case CraftingTable.Custom: { GameObject prefab = ZNetScene.instance.GetPrefab((value == null || registeredPiece.Extension.ExtensionStations.Count > 0) ? extensionStation.custom : value.customExtentionTable.Value); if (prefab != null) { registeredPiece.Prefab.GetComponent().m_craftingStation = prefab.GetComponent(); } else { Debug.LogWarning((object)("Custom crafting station '" + ((value == null || registeredPiece.Extension.ExtensionStations.Count > 0) ? extensionStation.custom : value.customExtentionTable.Value) + "' does not exist")); } break; } default: if (value != null && value.table.Value == CraftingTable.None) { registeredPiece.Prefab.GetComponent().m_craftingStation = null; } else { registeredPiece.Prefab.GetComponent().m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(((value == null || registeredPiece.Extension.ExtensionStations.Count > 1) ? extensionStation.Table : value.extensionTable.Value).ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent(); } break; } } foreach (CraftingStationConfig station in registeredPiece.Crafting.Stations) { switch ((value == null || registeredPiece.Crafting.Stations.Count > 0) ? station.Table : value.table.Value) { case CraftingTable.None: registeredPiece.Prefab.GetComponent().m_craftingStation = null; break; case CraftingTable.Custom: { GameObject prefab2 = ZNetScene.instance.GetPrefab((value == null || registeredPiece.Crafting.Stations.Count > 1) ? station.custom : value.customTable.Value); if (prefab2 != null) { registeredPiece.Prefab.GetComponent().m_craftingStation = prefab2.GetComponent(); } else { Debug.LogWarning((object)("Custom crafting station '" + ((value == null || registeredPiece.Crafting.Stations.Count > 0) ? station.custom : value.customTable.Value) + "' does not exist")); } break; } default: if (value != null && value.table.Value == CraftingTable.None) { registeredPiece.Prefab.GetComponent().m_craftingStation = null; } else { registeredPiece.Prefab.GetComponent().m_craftingStation = ZNetScene.instance.GetPrefab(((InternalName)typeof(CraftingTable).GetMember(((value == null || registeredPiece.Crafting.Stations.Count > 1) ? station.Table : value.table.Value).ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName).GetComponent(); } break; } } registeredPiece.conversions = new List(); for (int i = 0; i < registeredPiece.Conversions.Count; i++) { Conversion conversion = registeredPiece.Conversions[i]; registeredPiece.conversions.Add(new ItemConversion { m_from = SerializedRequirements.fetchByName(ObjectDB.instance, conversion.config?.input.Value ?? conversion.Input), m_to = SerializedRequirements.fetchByName(ObjectDB.instance, conversion.config?.output.Value ?? conversion.Output) }); if (registeredPiece.conversions[i].m_from != null && registeredPiece.conversions[i].m_to != null) { registeredPiece.Prefab.GetComponent().m_conversion.Add(registeredPiece.conversions[i]); } } } } public void Snapshot(float lightIntensity = 1.3f, Quaternion? cameraRotation = null) { SnapshotPiece(Prefab, lightIntensity, cameraRotation); } internal void SnapshotPiece(GameObject prefab, float lightIntensity = 1.3f, Quaternion? cameraRotation = null) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_006f: 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_009a: 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_0102: 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_0178: 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_01b4: 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_01de: Unknown result type (might be due to invalid IL or missing references) //IL_0202: Unknown result type (might be due to invalid IL or missing references) //IL_0207: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02e2: Unknown result type (might be due to invalid IL or missing references) //IL_02f3: Unknown result type (might be due to invalid IL or missing references) //IL_02f8: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Unknown result type (might be due to invalid IL or missing references) //IL_0331: Expected O, but got Unknown //IL_034f: Unknown result type (might be due to invalid IL or missing references) //IL_038b: 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_039a: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)prefab == (Object)null) && (prefab.GetComponentsInChildren().Any() || prefab.GetComponentsInChildren().Any())) { 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); Transform[] componentsInChildren = val.GetComponentsInChildren(); for (int i = 0; i < componentsInChildren.Length; i++) { ((Component)componentsInChildren[i]).gameObject.layer = 3; } val.transform.position = Vector3.zero; val.transform.rotation = Quaternion.Euler(23f, 51f, 25.8f); ((Object)val).name = ((Object)prefab).name; MeshRenderer[] componentsInChildren2 = val.GetComponentsInChildren(); Vector3 val2 = componentsInChildren2.Aggregate(Vector3.positiveInfinity, [NullableContext(0)] (Vector3 cur, MeshRenderer 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)renderer).bounds; return Vector3.Min(cur, ((Bounds)(ref bounds2)).min); }); Vector3 val3 = componentsInChildren2.Aggregate(Vector3.negativeInfinity, [NullableContext(0)] (Vector3 cur, MeshRenderer 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)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; val.AddComponent().Trigger(1f); Rect val5 = default(Rect); ((Rect)(ref val5))..ctor(0f, 0f, 128f, 128f); component.targetTexture = RenderTexture.GetTemporary((int)((Rect)(ref val5)).width, (int)((Rect)(ref val5)).height); component.fieldOfView = 20f; float num = (Mathf.Max(val4.x, val4.y) + 0.1f) / Mathf.Tan(component.fieldOfView * ((float)Math.PI / 180f)) * 1.1f; ((Component)component).transform.position = new Vector3(10000f, 10000f, 10000f) + new Vector3(0f, 0f, num); component.Render(); RenderTexture active = RenderTexture.active; RenderTexture.active = component.targetTexture; Texture2D val6 = new Texture2D((int)((Rect)(ref val5)).width, (int)((Rect)(ref val5)).height, (TextureFormat)4, false); val6.ReadPixels(new Rect(0f, 0f, (float)(int)((Rect)(ref val5)).width, (float)(int)((Rect)(ref val5)).height), 0, 0); val6.Apply(); RenderTexture.active = active; prefab.GetComponent().m_icon = Sprite.Create(val6, new Rect(0f, 0f, (float)(int)((Rect)(ref val5)).width, (float)(int)((Rect)(ref val5)).height), Vector2.one / 2f); ((Component)component2).gameObject.SetActive(false); component.targetTexture.Release(); ((Component)component).gameObject.SetActive(false); val.SetActive(false); 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); } } private static void DrawConfigTable(ConfigEntryBase cfg) { //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Expected O, but got Unknown //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Expected O, but got Unknown //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Expected O, but got Unknown //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_0207: Expected O, but got Unknown //IL_024a: Unknown result type (might be due to invalid IL or missing references) //IL_024f: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Expected O, but got Unknown bool valueOrDefault = cfg.Description.Tags.Select([NullableContext(0)] (object a) => (!(a.GetType().Name == "ConfigurationManagerAttributes")) ? null : ((bool?)a.GetType().GetField("ReadOnly")?.GetValue(a))).FirstOrDefault((bool? v) => v.HasValue).GetValueOrDefault(); List list = new List(); bool flag = false; int num = (int)(configManager?.GetType().GetProperty("RightColumnWidth", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(nonPublic: true) .Invoke(configManager, Array.Empty()) ?? ((object)130)); GUILayout.BeginVertical(Array.Empty()); foreach (Requirement req in new SerializedRequirements((string)cfg.BoxedValue).Reqs) { GUILayout.BeginHorizontal(Array.Empty()); int num2 = req.amount; if (int.TryParse(GUILayout.TextField(num2.ToString(), new GUIStyle(GUI.skin.textField) { fixedWidth = 40f }, Array.Empty()), out var result) && result != num2 && !valueOrDefault) { num2 = result; flag = true; } string text = GUILayout.TextField(req.itemName, new GUIStyle(GUI.skin.textField) { fixedWidth = num - 40 - 67 - 21 - 21 - 12 }, Array.Empty()); string text2 = (valueOrDefault ? req.itemName : text); flag = flag || text2 != req.itemName; bool flag2 = req.recover; if (GUILayout.Toggle(req.recover, "Recover", new GUIStyle(GUI.skin.toggle) { fixedWidth = 67f }, Array.Empty()) != req.recover) { flag2 = !flag2; flag = true; } if (GUILayout.Button("x", new GUIStyle(GUI.skin.button) { fixedWidth = 21f }, Array.Empty()) && !valueOrDefault) { flag = true; } else { list.Add(new Requirement { amount = num2, itemName = text2, recover = flag2 }); } if (GUILayout.Button("+", new GUIStyle(GUI.skin.button) { fixedWidth = 21f }, Array.Empty()) && !valueOrDefault) { flag = true; list.Add(new Requirement { amount = 1, itemName = "", recover = false }); } GUILayout.EndHorizontal(); } GUILayout.EndVertical(); if (flag) { cfg.BoxedValue = new SerializedRequirements(list).ToString(); } } private static ConfigEntry config<[Nullable(2)] T>(string group, string name, T value, ConfigDescription description) { ConfigEntry val = plugin.Config.Bind(group, name, value, description); configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T)) .Invoke(configSync, new object[1] { val }); return val; } private static ConfigEntry config<[Nullable(2)] T>(string group, string name, T value, string description) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty())); } } public static class GoExtensions { [NullableContext(1)] public static T GetOrAddComponent<[Nullable(0)] T>(this GameObject gameObject) where T : Component { return gameObject.GetComponent() ?? gameObject.AddComponent(); } } [NullableContext(1)] [PublicAPI] [Nullable(0)] public class LocalizeKey { private static readonly List keys = new List(); public readonly string Key; public readonly Dictionary Localizations = new Dictionary(); public LocalizeKey(string key) { Key = key.Replace("$", ""); keys.Add(this); } public void Alias(string alias) { Localizations.Clear(); if (!alias.Contains("$")) { alias = "$" + alias; } Localizations["alias"] = alias; if (Localization.m_instance != null) { Localization.instance.AddWord(Key, Localization.instance.Localize(alias)); } } public LocalizeKey English(string key) { return addForLang("English", key); } public LocalizeKey Swedish(string key) { return addForLang("Swedish", key); } public LocalizeKey French(string key) { return addForLang("French", key); } public LocalizeKey Italian(string key) { return addForLang("Italian", key); } public LocalizeKey German(string key) { return addForLang("German", key); } public LocalizeKey Spanish(string key) { return addForLang("Spanish", key); } public LocalizeKey Russian(string key) { return addForLang("Russian", key); } public LocalizeKey Romanian(string key) { return addForLang("Romanian", key); } public LocalizeKey Bulgarian(string key) { return addForLang("Bulgarian", key); } public LocalizeKey Macedonian(string key) { return addForLang("Macedonian", key); } public LocalizeKey Finnish(string key) { return addForLang("Finnish", key); } public LocalizeKey Danish(string key) { return addForLang("Danish", key); } public LocalizeKey Norwegian(string key) { return addForLang("Norwegian", key); } public LocalizeKey Icelandic(string key) { return addForLang("Icelandic", key); } public LocalizeKey Turkish(string key) { return addForLang("Turkish", key); } public LocalizeKey Lithuanian(string key) { return addForLang("Lithuanian", key); } public LocalizeKey Czech(string key) { return addForLang("Czech", key); } public LocalizeKey Hungarian(string key) { return addForLang("Hungarian", key); } public LocalizeKey Slovak(string key) { return addForLang("Slovak", key); } public LocalizeKey Polish(string key) { return addForLang("Polish", key); } public LocalizeKey Dutch(string key) { return addForLang("Dutch", key); } public LocalizeKey Portuguese_European(string key) { return addForLang("Portuguese_European", key); } public LocalizeKey Portuguese_Brazilian(string key) { return addForLang("Portuguese_Brazilian", key); } public LocalizeKey Chinese(string key) { return addForLang("Chinese", key); } public LocalizeKey Japanese(string key) { return addForLang("Japanese", key); } public LocalizeKey Korean(string key) { return addForLang("Korean", key); } public LocalizeKey Hindi(string key) { return addForLang("Hindi", key); } public LocalizeKey Thai(string key) { return addForLang("Thai", key); } public LocalizeKey Abenaki(string key) { return addForLang("Abenaki", key); } public LocalizeKey Croatian(string key) { return addForLang("Croatian", key); } public LocalizeKey Georgian(string key) { return addForLang("Georgian", key); } public LocalizeKey Greek(string key) { return addForLang("Greek", key); } public LocalizeKey Serbian(string key) { return addForLang("Serbian", key); } public LocalizeKey Ukrainian(string key) { return addForLang("Ukrainian", key); } private LocalizeKey addForLang(string lang, string value) { Localizations[lang] = value; if (Localization.m_instance != null) { if (Localization.instance.GetSelectedLanguage() == lang) { Localization.instance.AddWord(Key, value); } else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key)) { Localization.instance.AddWord(Key, value); } } return this; } [HarmonyPriority(300)] internal static void AddLocalizedKeys(Localization __instance, string language) { foreach (LocalizeKey key in keys) { string value2; if (key.Localizations.TryGetValue(language, out var value) || key.Localizations.TryGetValue("English", out value)) { __instance.AddWord(key.Key, value); } else if (key.Localizations.TryGetValue("alias", out value2)) { __instance.AddWord(key.Key, Localization.instance.Localize(value2)); } } } } [Nullable(0)] [NullableContext(1)] public static class LocalizationCache { private static readonly Dictionary localizations = new Dictionary(); internal static void LocalizationPostfix(Localization __instance, string language) { string key = localizations.FirstOrDefault([NullableContext(0)] (KeyValuePair l) => l.Value == __instance).Key; if (key != null) { localizations.Remove(key); } if (!localizations.ContainsKey(language)) { localizations.Add(language, __instance); } } public static Localization ForLanguage([Nullable(2)] string language = null) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out var value)) { return value; } value = new Localization(); if (language != null) { value.SetupLanguage(language); } return value; } } [Nullable(0)] [NullableContext(1)] public class AdminSyncing { [CompilerGenerated] private sealed class <g__WatchAdminListChanges|2_0>d : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; [Nullable(new byte[] { 0, 1 })] private List 5__2; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public <g__WatchAdminListChanges|2_0>d(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -1; if (!ZNet.instance.m_adminList.GetList().SequenceEqual(5__2)) { 5__2 = new List(ZNet.instance.m_adminList.GetList()); List list = (from p in ZNet.instance.GetPeers() where ZNet.instance.ListContainsId(ZNet.instance.m_adminList, p.m_rpc.GetSocket().GetHostName()) select p).ToList(); g__SendAdmin|2_2(ZNet.instance.GetPeers().Except(list).ToList(), isAdmin: false); g__SendAdmin|2_2(list, isAdmin: true); } } else { <>1__state = -1; 5__2 = new List(ZNet.instance.m_adminList.GetList()); } <>2__current = (object)new WaitForSeconds(30f); <>1__state = 1; return true; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class <>c__DisplayClass3_0 { [Nullable(0)] public ZPackage package; [NullableContext(0)] internal IEnumerator b__1(ZNetPeer p) { return TellPeerAdminStatus(p, package); } } [StructLayout(LayoutKind.Auto)] [CompilerGenerated] private struct <>c__DisplayClass4_0 { [Nullable(0)] public ZNetPeer peer; [Nullable(0)] public ZRoutedRpc rpc; } [CompilerGenerated] private sealed class d__4 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; private bool <>2__current; [Nullable(0)] public ZNetPeer peer; [Nullable(0)] public ZPackage package; bool IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__4(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { if (<>1__state != 0) { return false; } <>1__state = -1; <>c__DisplayClass4_0 <>c__DisplayClass4_ = default(<>c__DisplayClass4_0); <>c__DisplayClass4_.peer = peer; <>c__DisplayClass4_.rpc = ZRoutedRpc.instance; if (<>c__DisplayClass4_.rpc == null) { return false; } g__SendPackage|4_0(package, ref <>c__DisplayClass4_); 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(); } } [CompilerGenerated] private sealed class d__3 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; [Nullable(0)] public ZPackage package; [Nullable(new byte[] { 0, 1 })] public List peers; [Nullable(new byte[] { 0, 1 })] private List> 5__2; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__3(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown switch (<>1__state) { default: return false; case 0: { <>1__state = -1; <>c__DisplayClass3_0 CS$<>8__locals0 = new <>c__DisplayClass3_0 { package = package }; if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return false; } byte[] array = CS$<>8__locals0.package.GetArray(); if (array != null && array.LongLength > 10000) { ZPackage val = new ZPackage(); val.Write(4); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal)) { deflateStream.Write(array, 0, array.Length); } val.Write(memoryStream.ToArray()); CS$<>8__locals0.package = val; } 5__2 = (from peer in peers where peer.IsReady() select peer into p select TellPeerAdminStatus(p, CS$<>8__locals0.package)).ToList(); 5__2.RemoveAll((IEnumerator writer) => !writer.MoveNext()); break; } case 1: <>1__state = -1; 5__2.RemoveAll((IEnumerator writer) => !writer.MoveNext()); break; } if (5__2.Count > 0) { <>2__current = null; <>1__state = 1; return true; } 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(); } } private static bool isServer; internal static bool registeredOnClient; [HarmonyPriority(700)] internal static void AdminStatusSync(ZNet __instance) { isServer = __instance.IsServer(); if (BuildPiece._plugin != null) { if (isServer) { ZRoutedRpc.instance.Register(BuildPiece._plugin.Info.Metadata.Name + " PMAdminStatusSync", (Action)RPC_AdminPieceAddRemove); } else if (!registeredOnClient) { ZRoutedRpc.instance.Register(BuildPiece._plugin.Info.Metadata.Name + " PMAdminStatusSync", (Action)RPC_AdminPieceAddRemove); registeredOnClient = true; } } if (isServer) { ((MonoBehaviour)ZNet.instance).StartCoroutine(WatchAdminListChanges()); } [IteratorStateMachine(typeof(<g__WatchAdminListChanges|2_0>d))] static IEnumerator WatchAdminListChanges() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <g__WatchAdminListChanges|2_0>d(0); } } [IteratorStateMachine(typeof(d__3))] private static IEnumerator sendZPackage(List peers, ZPackage package) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__3(0) { peers = peers, package = package }; } [IteratorStateMachine(typeof(d__4))] private static IEnumerator TellPeerAdminStatus(ZNetPeer peer, ZPackage package) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__4(0) { peer = peer, package = package }; } internal static void RPC_AdminPieceAddRemove(long sender, ZPackage package) { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Expected O, but got Unknown ZNetPeer peer = ZNet.instance.GetPeer(sender); bool flag = false; try { flag = package.ReadBool(); } catch { } if (isServer) { ZRoutedRpc instance = ZRoutedRpc.instance; long everybody = ZRoutedRpc.Everybody; BaseUnityPlugin plugin = BuildPiece._plugin; instance.InvokeRoutedRPC(everybody, ((plugin != null) ? plugin.Info.Metadata.Name : null) + " PMAdminStatusSync", new object[1] { (object)new ZPackage() }); if (ZNet.instance.ListContainsId(ZNet.instance.m_adminList, peer.m_rpc.GetSocket().GetHostName())) { ZPackage val = new ZPackage(); val.Write(true); ZRpc rpc = peer.m_rpc; BaseUnityPlugin plugin2 = BuildPiece._plugin; rpc.Invoke(((plugin2 != null) ? plugin2.Info.Metadata.Name : null) + " PMAdminStatusSync", new object[1] { val }); } return; } foreach (BuildPiece registeredPiece in BuildPiece.registeredPieces) { if (!registeredPiece.SpecialProperties.AdminOnly) { continue; } Piece component = registeredPiece.Prefab.GetComponent(); string name = component.m_name; Localization.instance.Localize(name).Trim(); if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || (Object)(object)ObjectDB.instance.GetItemPrefab("YmirRemains") == (Object)null) { continue; } Piece[] array = Object.FindObjectsByType((FindObjectsSortMode)0); foreach (Piece val2 in array) { if (flag) { if (val2.m_name == name) { val2.m_enabled = true; } } else if (val2.m_name == name) { val2.m_enabled = false; } } List pieces = ObjectDB.instance.GetItemPrefab("Hammer").GetComponent().m_itemData.m_shared.m_buildPieces.m_pieces; if (flag) { if (!pieces.Contains(ZNetScene.instance.GetPrefab(((Object)component).name))) { pieces.Add(ZNetScene.instance.GetPrefab(((Object)component).name)); } } else if (pieces.Contains(ZNetScene.instance.GetPrefab(((Object)component).name))) { pieces.Remove(ZNetScene.instance.GetPrefab(((Object)component).name)); } } } [CompilerGenerated] internal static void g__SendAdmin|2_2(List peers, bool isAdmin) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ZPackage val = new ZPackage(); val.Write(isAdmin); ((MonoBehaviour)ZNet.instance).StartCoroutine(sendZPackage(peers, val)); } [CompilerGenerated] internal static void g__SendPackage|4_0(ZPackage pkg, ref <>c__DisplayClass4_0 P_1) { BaseUnityPlugin plugin = BuildPiece._plugin; string text = ((plugin != null) ? plugin.Info.Metadata.Name : null) + " PMAdminStatusSync"; if (isServer) { P_1.peer.m_rpc.Invoke(text, new object[1] { pkg }); } else { P_1.rpc.InvokeRoutedRPC(P_1.peer.m_server ? 0 : P_1.peer.m_uid, text, new object[1] { pkg }); } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [Nullable(0)] [NullableContext(1)] internal class RegisterClientRPCPatch { private static void Postfix(ZNet __instance, ZNetPeer peer) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown if (!__instance.IsServer()) { ZRpc rpc = peer.m_rpc; BaseUnityPlugin plugin = BuildPiece._plugin; rpc.Register(((plugin != null) ? plugin.Info.Metadata.Name : null) + " PMAdminStatusSync", (Action)RPC_InitialAdminSync); return; } ZPackage val = new ZPackage(); val.Write(__instance.ListContainsId(__instance.m_adminList, peer.m_rpc.GetSocket().GetHostName())); ZRpc rpc2 = peer.m_rpc; BaseUnityPlugin plugin2 = BuildPiece._plugin; rpc2.Invoke(((plugin2 != null) ? plugin2.Info.Metadata.Name : null) + " PMAdminStatusSync", new object[1] { val }); } private static void RPC_InitialAdminSync(ZRpc rpc, ZPackage package) { AdminSyncing.RPC_AdminPieceAddRemove(0L, package); } } [Nullable(0)] [NullableContext(1)] public static class PiecePrefabManager { [Nullable(0)] private struct BundleId { [UsedImplicitly] public string assetBundleFileName; [UsedImplicitly] public string folderName; } private static readonly Dictionary bundleCache; private static readonly List piecePrefabs; private static readonly Dictionary PieceCategories; private static readonly Dictionary OtherPieceCategories; private static readonly Dictionary VanillaLabels; internal static bool CategoryRefreshNeeded; static PiecePrefabManager() { //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_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Expected O, but got Unknown //IL_0078: 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_00b3: Expected O, but got Unknown //IL_00b4: 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_00ef: Expected O, but got Unknown //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Expected O, but got Unknown //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Expected O, but got Unknown //IL_0168: 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_01a3: Expected O, but got Unknown //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Expected O, but got Unknown //IL_01e0: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Expected O, but got Unknown //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_024a: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_0258: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_0293: Expected O, but got Unknown //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_02c1: Unknown result type (might be due to invalid IL or missing references) //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Expected O, but got Unknown //IL_02e9: Expected O, but got Unknown //IL_02ea: Unknown result type (might be due to invalid IL or missing references) //IL_0318: Unknown result type (might be due to invalid IL or missing references) //IL_0325: Expected O, but got Unknown //IL_0326: Unknown result type (might be due to invalid IL or missing references) //IL_0354: Unknown result type (might be due to invalid IL or missing references) //IL_0361: Expected O, but got Unknown //IL_0362: Unknown result type (might be due to invalid IL or missing references) //IL_038f: Unknown result type (might be due to invalid IL or missing references) //IL_039d: Expected O, but got Unknown //IL_039e: Unknown result type (might be due to invalid IL or missing references) //IL_03cc: Unknown result type (might be due to invalid IL or missing references) //IL_03d9: Expected O, but got Unknown //IL_03da: Unknown result type (might be due to invalid IL or missing references) //IL_0408: Unknown result type (might be due to invalid IL or missing references) //IL_0415: Expected O, but got Unknown //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_0450: Expected O, but got Unknown bundleCache = new Dictionary(); piecePrefabs = new List(); PieceCategories = new Dictionary(); OtherPieceCategories = new Dictionary(); VanillaLabels = new Dictionary(); Harmony val = new Harmony("org.bepinex.helpers.PieceManager"); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(BuildPiece), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_ObjectDBInit", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(BuildPiece), "Patch_ObjectDBInit", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "CopyOtherDB", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_ObjectDBInit", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(AdminSyncing), "AdminStatusSync", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNetScene), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_ZNetSceneAwake", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNetScene), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "RefFixPatch_ZNetSceneAwake", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "UpdateAvailable", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "UpdateAvailable_Transpiler", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(PieceTable), "UpdateAvailable", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "UpdateAvailable_Prefix", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "UpdateAvailable_Postfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Player), "SetPlaceMode", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Patch_SetPlaceMode", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Hud), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "Hud_AwakeCreateTabs", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Hud), "UpdateBuild", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "RepositionCatsIfNeeded", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Hud), "LateUpdate", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "RepositionCatsIfNeeded", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Enum), "GetValues", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "EnumGetValuesPatch", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Enum), "GetNames", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "EnumGetNamesPatch", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static AssetBundle RegisterAssetBundle(string assetBundleFileName, string folderName = "assets") { BundleId bundleId = default(BundleId); bundleId.assetBundleFileName = assetBundleFileName; bundleId.folderName = folderName; BundleId key = bundleId; if (!bundleCache.TryGetValue(key, out var value)) { Dictionary dictionary = bundleCache; AssetBundle? obj = ((IEnumerable)Resources.FindObjectsOfTypeAll()).FirstOrDefault((Func)([NullableContext(0)] (AssetBundle a) => ((Object)a).name == assetBundleFileName)) ?? AssetBundle.LoadFromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + folderName + "." + assetBundleFileName)); AssetBundle result = obj; dictionary[key] = obj; return result; } return value; } public static IEnumerable FixRefs(AssetBundle assetBundle) { return assetBundle.LoadAllAssets(); } public static GameObject RegisterPrefab(string assetBundleFileName, string prefabName, string folderName = "assets") { return RegisterPrefab(RegisterAssetBundle(assetBundleFileName, folderName), prefabName); } public static GameObject RegisterPrefab(AssetBundle assets, string prefabName) { if ((Object)(object)assets == (Object)null) { Debug.LogError((object)"Failed to load asset bundle. Please make sure to mark all asset bundles as embedded resources."); return null; } GameObject val = assets.LoadAsset(prefabName); if ((Object)(object)val == (Object)null) { Debug.LogError((object)("Failed to load prefab " + prefabName + " from asset bundle " + ((Object)assets).name)); return null; } piecePrefabs.Add(val); return val; } public static Sprite RegisterSprite(string assetBundleFileName, string prefabName, string folderName = "assets") { return RegisterSprite(RegisterAssetBundle(assetBundleFileName, folderName), prefabName); } public static Sprite RegisterSprite(AssetBundle assets, string prefabName) { return assets.LoadAsset(prefabName); } private static void EnumGetValuesPatch(Type enumType, ref Array __result) { if (!(enumType != typeof(PieceCategory)) && PieceCategories.Count != 0) { PieceCategory[] array = (PieceCategory[])(object)new PieceCategory[__result.Length + PieceCategories.Count]; __result.CopyTo(array, 0); PieceCategories.Values.CopyTo(array, __result.Length); __result = array; } } private static void EnumGetNamesPatch(Type enumType, ref string[] __result) { if (!(enumType != typeof(PieceCategory)) && PieceCategories.Count != 0) { __result = CollectionExtensions.AddRangeToArray(__result, PieceCategories.Keys.ToArray()); } } public static Dictionary GetPieceCategoriesMap() { //IL_0032: Unknown result type (might be due to invalid IL or missing references) Array values = Enum.GetValues(typeof(PieceCategory)); string[] names = Enum.GetNames(typeof(PieceCategory)); Dictionary dictionary = new Dictionary(); for (int i = 0; i < values.Length; i++) { dictionary[(PieceCategory)values.GetValue(i)] = names[i]; } return dictionary; } public static PieceCategory GetCategory(string name) { //IL_000b: 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_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: 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_00b0: 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) if (Enum.TryParse(name, ignoreCase: true, out PieceCategory result)) { return result; } if (PieceCategories.TryGetValue(name, out result)) { return result; } if (OtherPieceCategories.TryGetValue(name, out result)) { return result; } Dictionary pieceCategoriesMap = GetPieceCategoriesMap(); foreach (KeyValuePair item in pieceCategoriesMap) { if (item.Value == name) { result = item.Key; OtherPieceCategories[name] = result; return result; } } result = (PieceCategory)(pieceCategoriesMap.Count - 1); PieceCategories[name] = result; string categoryToken = GetCategoryToken(name); Localization.instance.AddWord(categoryToken, name); return result; } internal static void CreateCategoryTabs() { if (Object.op_Implicit((Object)(object)Hud.instance)) { int num = ModifiedMaxCategory(); for (int i = Hud.instance.m_pieceCategoryTabs.Length; i < num; i++) { GameObject val = CreateCategoryTab(); Hud.instance.m_pieceCategoryTabs = CollectionExtensions.AddItem((IEnumerable)Hud.instance.m_pieceCategoryTabs, val).ToArray(); } if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)Player.m_localPlayer.m_buildPieces)) { RepositionCategories(Player.m_localPlayer.m_buildPieces); Player.m_localPlayer.UpdateAvailablePiecesList(); } } } private static GameObject CreateCategoryTab() { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) GameObject val = Hud.instance.m_pieceCategoryTabs[0]; GameObject val2 = Object.Instantiate(Hud.instance.m_pieceCategoryTabs[0], val.transform.parent); val2.SetActive(false); UIInputHandler orAddComponent = val2.GetOrAddComponent(); orAddComponent.m_onLeftDown = (Action)Delegate.Combine(orAddComponent.m_onLeftDown, new Action(Hud.instance.OnLeftClickCategory)); TMP_Text[] componentsInChildren = val2.GetComponentsInChildren(); foreach (TMP_Text obj in componentsInChildren) { obj.rectTransform.offsetMin = new Vector2(3f, 1f); obj.rectTransform.offsetMax = new Vector2(-3f, -1f); obj.enableAutoSizing = true; obj.fontSizeMin = 12f; obj.fontSizeMax = 20f; obj.lineSpacing = 0.8f; obj.textWrappingMode = (TextWrappingModes)1; obj.overflowMode = (TextOverflowModes)3; } return val2; } private static int ModifiedMaxCategory() { return Enum.GetValues(typeof(PieceCategory)).Length - 1; } private static int GetMaxCategoryOrDefault() { try { return (int)Enum.Parse(typeof(PieceCategory), "Max"); } catch (ArgumentException) { Debug.LogWarning((object)"Could not find Piece.PieceCategory.Max, using fallback value 4"); return 4; } } private static List TranspileMaxCategory(IEnumerable instructions, int maxOffset) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Expected O, but got Unknown int num = GetMaxCategoryOrDefault() + maxOffset; List list = new List(); foreach (CodeInstruction instruction in instructions) { if (CodeInstructionExtensions.LoadsConstant(instruction, (long)num)) { list.Add(new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(PiecePrefabManager), "ModifiedMaxCategory", (Type[])null, (Type[])null))); if (maxOffset != 0) { list.Add(new CodeInstruction(OpCodes.Ldc_I4, (object)maxOffset)); list.Add(new CodeInstruction(OpCodes.Add, (object)null)); } } else { list.Add(instruction); } } return list; } private static IEnumerable UpdateAvailable_Transpiler(IEnumerable instructions) { return TranspileMaxCategory(instructions, 0); } private static HashSet CategoriesInPieceTable(PieceTable pieceTable) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) HashSet hashSet = new HashSet(); Piece val = default(Piece); foreach (GameObject item in pieceTable.m_pieces.Where([NullableContext(0)] (GameObject pieceFab) => (Object)(object)pieceFab != (Object)null)) { if (item.TryGetComponent(ref val)) { hashSet.Add(val.m_category); } } return hashSet; } private static void RepositionCatsIfNeeded() { if (CategoryRefreshNeeded) { CategoryRefreshNeeded = false; CreateCategoryTabs(); RepositionCats(); } } private static void RepositionCats() { if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)Player.m_localPlayer.m_buildPieces)) { RepositionCategories(Player.m_localPlayer.m_buildPieces); } } private static void RepositionCategories(PieceTable pieceTable) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown //IL_0026: 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_0040: Expected O, but got Unknown //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_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0089: 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_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_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: 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_0239: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Expected O, but got Unknown //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_0271: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Unknown result type (might be due to invalid IL or missing references) RectTransform val = (RectTransform)Hud.instance.m_pieceCategoryTabs[0].transform; RectTransform val2 = (RectTransform)Hud.instance.m_pieceCategoryRoot.transform; RectTransform val3 = (RectTransform)Hud.instance.m_pieceSelectionWindow.transform; HorizontalLayoutGroup val4 = default(HorizontalLayoutGroup); if (((Component)((Transform)val).parent).TryGetComponent(ref val4)) { Object.DestroyImmediate((Object)(object)val4); } Rect rect = val.rect; Vector2 size = ((Rect)(ref rect)).size; GridLayoutGroup val5 = default(GridLayoutGroup); GridLayoutGroup obj = (((Component)((Transform)val).parent).TryGetComponent(ref val5) ? val5 : ((Component)((Transform)val).parent).gameObject.AddComponent()); obj.cellSize = size; obj.spacing = new Vector2(0f, 1f); obj.constraint = (Constraint)1; obj.constraintCount = 5; ((LayoutGroup)obj).childAlignment = (TextAnchor)4; HashSet hashSet = CategoriesInPieceTable(pieceTable); UpdatePieceTableCategories(pieceTable, hashSet); rect = val2.rect; int num = Mathf.Max((int)(((Rect)(ref rect)).width / size.x), 1); int count = pieceTable.m_categories.Count; float num2 = (0f - size.x) * (float)num / 2f + size.x / 2f; float num3 = (size.y + 1f) * Mathf.Floor((float)(count - 1) / (float)num) + 5f; new Vector2(num2, num3); int num4 = Mathf.CeilToInt((float)count / (float)num); float num5 = (size.y + 1f) * (float)num4; RectTransform component = ((Component)((Transform)val).parent).GetComponent(); component.anchoredPosition = new Vector2(component.anchoredPosition.x, num5 / 2f); int num6 = 0; for (int i = 0; i < Hud.instance.m_pieceCategoryTabs.Length; i++) { GameObject val6 = Hud.instance.m_pieceCategoryTabs[i]; if ((Object)(object)val6 == (Object)null) { continue; } if (i >= pieceTable.m_categories.Count) { val6.SetActive(false); continue; } PieceCategory item = pieceTable.m_categories[i]; string text = pieceTable.m_categoryLabels[i]; if (hashSet.Contains(item)) { num6++; } val6.GetComponentInChildren().text = Localization.instance.Localize(text); } Transform obj2 = ((Transform)val3).Find("Bkg2"); RectTransform val7 = (RectTransform)((obj2 != null) ? ((Component)obj2).transform : null); if (Object.op_Implicit((Object)(object)val7)) { float num7 = (size.y + 1f) * (float)Mathf.Max(0, Mathf.FloorToInt((float)(num6 - 1) / (float)num)); val7.offsetMax = new Vector2(val7.offsetMax.x, num7); } else { Debug.LogWarning((object)"RefreshCategories: Could not find background image"); } ((Component)Hud.instance).GetComponentInParent().RefreshLocalization(); } private static void UpdatePieceTableCategories(PieceTable pieceTable, HashSet visibleCategories) { //IL_0005: 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_003b: 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_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002f: 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_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: 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_00cc: 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_0152: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < GetMaxCategoryOrDefault(); i++) { PieceCategory val = (PieceCategory)i; if (visibleCategories.Contains(val) && !pieceTable.m_categories.Contains(val)) { pieceTable.m_categories.Add(val); pieceTable.m_categoryLabels.Add(GetVanillaLabel(val)); } if (!visibleCategories.Contains(val) && pieceTable.m_categories.Contains(val)) { int index = pieceTable.m_categories.IndexOf(val); pieceTable.m_categories.RemoveAt(index); pieceTable.m_categoryLabels.RemoveAt(index); } } foreach (KeyValuePair pieceCategory in PieceCategories) { string key = pieceCategory.Key; PieceCategory value = pieceCategory.Value; if (visibleCategories.Contains(value) && !pieceTable.m_categories.Contains(value)) { pieceTable.m_categories.Add(value); pieceTable.m_categoryLabels.Add("$" + GetCategoryToken(key)); } if (visibleCategories.Contains(value) && !pieceTable.m_categoryLabels.Contains("$" + GetCategoryToken(key))) { pieceTable.m_categoryLabels.Add("$" + GetCategoryToken(key)); } if (!visibleCategories.Contains(value) && pieceTable.m_categories.Contains(value)) { int index2 = pieceTable.m_categories.IndexOf(value); pieceTable.m_categories.RemoveAt(index2); pieceTable.m_categoryLabels.RemoveAt(index2); } } } private static string GetVanillaLabel(PieceCategory category) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (!VanillaLabels.ContainsKey(category)) { SearchVanillaLabels(); } if (!VanillaLabels.TryGetValue(category, out var value)) { return string.Empty; } return value; } private static void SearchVanillaLabels() { //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_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) PieceTable[] array = Resources.FindObjectsOfTypeAll(); foreach (PieceTable val in array) { for (int j = 0; j < val.m_categories.Count; j++) { PieceCategory key = val.m_categories[j]; if (j < val.m_categoryLabels.Count && !VanillaLabels.ContainsKey(key) && !string.IsNullOrEmpty(val.m_categoryLabels[j])) { VanillaLabels[key] = val.m_categoryLabels[j]; } } } } private static string GetCategoryToken(string name) { char[] endChars = Localization.instance.m_endChars; string text = string.Concat(name.ToLower().Split(endChars)); return "piecemanager_cat_" + text; } private static void Patch_SetPlaceMode(Player __instance) { if (Object.op_Implicit((Object)(object)__instance.m_buildPieces)) { RepositionCategories(__instance.m_buildPieces); } } private static void UpdateAvailable_Prefix(PieceTable __instance) { if (__instance.m_availablePieces.Count > 0) { int num = ModifiedMaxCategory() - __instance.m_availablePieces.Count; for (int i = 0; i < num; i++) { __instance.m_availablePieces.Add(new List()); } } } private static void UpdateAvailable_Postfix(PieceTable __instance) { Array.Resize(ref __instance.m_selectedPiece, __instance.m_availablePieces.Count); Array.Resize(ref __instance.m_lastSelectedPiece, __instance.m_availablePieces.Count); } [HarmonyPriority(200)] private static void Hud_AwakeCreateTabs() { CreateCategoryTabs(); } [HarmonyPriority(700)] private static void Patch_ZNetSceneAwake(ZNetScene __instance) { foreach (GameObject piecePrefab in piecePrefabs) { if (!__instance.m_prefabs.Contains(piecePrefab)) { __instance.m_prefabs.Add(piecePrefab); } } } [HarmonyPriority(700)] private static void RefFixPatch_ZNetSceneAwake(ZNetScene __instance) { //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) foreach (GameObject piecePrefab in piecePrefabs) { if (__instance.m_prefabs.Contains(piecePrefab) && Object.op_Implicit((Object)(object)piecePrefab.GetComponent())) { piecePrefab.GetComponent().m_isUpgrade = true; piecePrefab.GetComponent().m_connectionPrefab = __instance.GetPrefab("piece_workbench_ext3").GetComponent().m_connectionPrefab; piecePrefab.GetComponent().m_connectionOffset = __instance.GetPrefab("piece_workbench_ext3").GetComponent().m_connectionOffset; } } } [HarmonyPriority(300)] private static void Patch_ObjectDBInit(ObjectDB __instance) { foreach (BuildPiece registeredPiece in BuildPiece.registeredPieces) { string[] activeTools = registeredPiece.activeTools; foreach (string text in activeTools) { GameObject itemPrefab = __instance.GetItemPrefab(text); PieceTable val = ((itemPrefab != null) ? itemPrefab.GetComponent().m_itemData.m_shared.m_buildPieces : null); if (val != null && !val.m_pieces.Contains(registeredPiece.Prefab)) { val.m_pieces.Add(registeredPiece.Prefab); } } } } } [PublicAPI] [Nullable(0)] [NullableContext(1)] public class Conversion { [Nullable(0)] internal class ConversionConfig { public ConfigEntry input; public ConfigEntry output; } public string Input; public string Output; [Nullable(2)] internal ConversionConfig config; public Conversion(BuildPiece conversionPiece) { conversionPiece.Conversions.Add(this); } } } namespace wackydatabase { [NullableContext(1)] [Nullable(0)] public abstract class DataManager<[Nullable(2)] T> { protected static readonly ColorConverter cc = new ColorConverter(); protected static readonly TextureConverter tc = new TextureConverter(); protected static readonly ValheimTimeConverter vtc = new ValheimTimeConverter(); protected FileSystemWatcher fileSystemWatcher; public static readonly ISerializer Serializer = new SerializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).WithTypeConverter(cc).WithTypeConverter(tc) .WithTypeConverter(vtc) .Build(); public static readonly IDeserializer Deserializer = new DeserializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).WithTypeConverter(cc).WithTypeConverter(tc) .WithTypeConverter(vtc) .Build(); protected string Storage { get; set; } protected string Name { get; set; } public CustomSyncedValue> YamlData { get; set; } public event EventHandler OnSync; public event EventHandler> OnDataChange; public DataManager(string path, string name) { Storage = path; Name = name; YamlData = new CustomSyncedValue>(WMRecipeCust.ConfigSync, name + " YAML", new Dictionary()); YamlData.AssignLocalValue(Reload()); YamlData.ValueChanged += SyncDetected; fileSystemWatcher = new FileSystemWatcher(Storage, "*.yml"); fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.Created += FileSystemWatcher_Changed; fileSystemWatcher.Changed += FileSystemWatcher_Changed; fileSystemWatcher.Renamed += FileSystemWatcher_Changed; fileSystemWatcher.EnableRaisingEvents = true; } public abstract void Cache(T item); private void FileSystemWatcher_Changed(object sender, FileSystemEventArgs evt) { Debug.Log((object)("[WackysDatabase]: " + Name + " Change: " + evt.Name)); try { if (WMRecipeCust.ConfigSync.IsSourceOfTruth) { T data = LoadFile(evt.FullPath); this.OnDataChange?.Invoke(null, new DataEventArgs(data)); if (WMRecipeCust.ConfigSync.IsSourceOfTruth) { YamlData.AssignLocalValue(Reload()); } else { YamlData.Value = Reload(); } } } catch (Exception ex) { Debug.LogError((object)("Detected " + Name + " file change, but importing failed with an error.\n" + ex.Message + ((ex.InnerException != null) ? (": " + ex.InnerException.Message) : ""))); } } private void SyncDetected() { Debug.Log((object)("[WackysDatabase]: " + Name + " sync detected")); try { LoadSyncedValue(YamlData.Value); this.OnSync?.Invoke(this, new EventArgs()); if (!WMRecipeCust.ConfigSync.IsSourceOfTruth) { SaveCache(YamlData.Value); } } catch (Exception ex) { Debug.LogError((object)("Detected " + Name + " sync, but importing failed with an error.\n" + ex.Message + ((ex.InnerException != null) ? (": " + ex.InnerException.Message) : ""))); } } public void LoadFiles() { Debug.Log((object)("[WackysDatabase]: Searching for files: " + Storage)); string[] files = Directory.GetFiles(Storage, "*.yml", SearchOption.AllDirectories); foreach (string text in files) { string text2 = text.Split(new char[1] { '\\' }).Last(); Debug.Log((object)("[WackysDatabase]: Loading " + Name + ": " + text2)); LoadFile(text); } } public virtual T LoadFile(string path) { try { string yaml = File.ReadAllText(path); return LoadYaml(yaml); } catch (Exception ex) { Debug.LogError((object)("[WackysDatabase]: Failed to load data from " + path + " - " + ex.Message)); return default(T); } } public void Save(Dictionary data) { foreach (KeyValuePair datum in data) { File.WriteAllText(Path.Combine(Storage, datum.Key), datum.Value); } } public void SaveCache(Dictionary data) { WMRecipeCust.WLog.LogInfo((object)"Mat SaveCache"); foreach (KeyValuePair datum in data) { int stableHashCode = StringExtensionMethods.GetStableHashCode(datum.Key); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathCache, "_" + stableHashCode + ".mat"), datum.Value); } } private void EnsureFolder(string path) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } public void Export(T data, string name) { string contents = Serializer.Serialize(data); EnsureFolder(Storage); File.WriteAllText(Path.Combine(Storage, name + ".yml"), contents); } public void LoadSyncedValue(Dictionary data) { foreach (KeyValuePair datum in data) { LoadYaml(datum.Value); } } protected Dictionary Reload() { Dictionary dictionary = new Dictionary(); WMRecipeCust.WLog.LogInfo((object)"Mat Cache Save"); string[] files = Directory.GetFiles(Storage, "*.yml", SearchOption.AllDirectories); foreach (string text in files) { try { string fileName = Path.GetFileName(Storage); if (!dictionary.ContainsKey(fileName)) { dictionary.Add(fileName, File.ReadAllText(text)); } else { dictionary[fileName] = File.ReadAllText(text); } int stableHashCode = StringExtensionMethods.GetStableHashCode(dictionary[fileName]); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathCache, "_" + stableHashCode + ".mat"), dictionary[fileName]); } catch (Exception ex) { Debug.LogError((object)("[WackysDatabase]: Failed to load data from " + text + " - " + ex.Message)); } } return dictionary; } public T LoadYaml(string yaml) { try { T val = Deserializer.Deserialize(yaml); Cache(val); return val; } catch (Exception ex) { Debug.LogError((object)("Found WackysDatabase config error in yaml.\n" + ex.Message + ((ex.InnerException != null) ? (": " + ex.InnerException.Message) : ""))); return default(T); } } } [Nullable(0)] [NullableContext(1)] public class DataEventArgs<[Nullable(2)] T> : EventArgs { public T Data { get; private set; } public DataEventArgs(T data) { Data = data; } } [Nullable(new byte[] { 0, 1 })] [NullableContext(1)] public class MaterialDataManager : DataManager { public static MaterialDataManager Instance = new MaterialDataManager(); public Dictionary materials; public event EventHandler OnMaterialAdd; public event EventHandler OnMaterialChange; public event EventHandler OnMaterialOverwrite; public MaterialDataManager() : base(WMRecipeCust.assetPathMaterials, "Material") { materials = new Dictionary(); } public override void Cache(MaterialInstance mi) { try { if (mi.overwrite) { if (WMRecipeCust.originalMaterials.ContainsKey(mi.original)) { new MaterialManipulator(mi.changes).Invoke(WMRecipeCust.originalMaterials[mi.original], null); return; } Debug.LogError((object)("[WackysDatabase]: Unable to pull material from cache: " + mi.original)); } if (!WMRecipeCust.originalMaterials.ContainsKey(mi.original)) { Debug.LogError((object)("[WackysDatabase]: Failed to get material from cache: " + mi.original)); } else if (!materials.ContainsKey(mi.name)) { Debug.Log((object)("[WackysDatabase]: Adding Material: " + mi.name)); Material val = Object.Instantiate(WMRecipeCust.originalMaterials[mi.original]); ((Object)val).name = mi.name; if (!WMRecipeCust.originalMaterials.ContainsKey(mi.name)) { WMRecipeCust.originalMaterials.Add(mi.name, val); } else { WMRecipeCust.originalMaterials[mi.name] = val; } materials.Add(mi.name, val); new MaterialManipulator(mi.changes).Invoke(val, null); } else if (materials.ContainsKey(mi.name)) { this.OnMaterialChange?.Invoke(this, new MaterialEventArgs(materials[mi.name], mi)); } } catch (Exception ex) { Debug.LogError((object)("[WackysDatabase]: Failed to cache material: " + mi.name + " - " + ex.Message + " - " + ex.StackTrace)); } } public static void WackyForce(MaterialInstance mi) { try { if (WMRecipeCust.originalMaterials.ContainsKey(mi.original)) { new MaterialManipulator(mi.changes).ForceTextures(mi.changes); } } catch (Exception ex) { Debug.LogError((object)("[WackysDatabase]: Failed to cache material: " + mi.name + " - " + ex.Message + " - " + ex.StackTrace)); } } public Material[] GetMaterials(string[] mats) { Material[] array = (Material[])(object)new Material[mats.Length]; for (int i = 0; i < mats.Length; i++) { if (!materials.ContainsKey(mats[i])) { Debug.LogError((object)("[WackysDatabase]: Failed to get new material: " + mats[i])); continue; } Material val = materials[mats[i]]; array[i] = val; } return array; } public Material GetMaterial(string material) { if (!materials.ContainsKey(material)) { Debug.LogError((object)("[WackysDatabase]: Failed to get material: " + material)); return null; } return materials[material]; } } [NullableContext(1)] [Nullable(0)] public class MaterialEventArgs : EventArgs { public Material Material { get; private set; } public MaterialInstance MaterialInstance { get; private set; } public MaterialEventArgs(Material m, MaterialInstance mi) { Material = m; MaterialInstance = mi; } } [Nullable(0)] [NullableContext(1)] public static class TextureDataManager { public static Dictionary textureCache = new Dictionary(); public static void SaveTexture(string name, Material material, string property) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown byte[] bytes = ImageConversion.EncodeToPNG((Texture2D)material.GetTexture(property)); File.WriteAllBytes(Path.Combine(WMRecipeCust.assetPathTextures, name + ".png"), bytes); } public static void SaveTexture(string name, Texture t) { byte[] bytes = ImageConversion.EncodeToPNG(Colour.CloneTexture((Texture2D)(object)((t is Texture2D) ? t : null))); File.WriteAllBytes(Path.Combine(WMRecipeCust.assetPathTextures, name + ".png"), bytes); } public static Texture2D LoadTexture(string name) { //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: Expected O, but got Unknown //IL_0039: Expected O, but got Unknown string path = Path.Combine(WMRecipeCust.assetPathTextures, name + ".png"); if (!File.Exists(path)) { return null; } byte[] array = File.ReadAllBytes(path); Texture2D val = new Texture2D(16, 16); ImageConversion.LoadImage(val, array); return val; } public static Texture2D GetTexture(string name) { if (!textureCache.ContainsKey(name)) { textureCache[name] = LoadTexture(name); } return textureCache[name]; } public static Dictionary GetTextures(Dictionary textures) { Dictionary dictionary = new Dictionary(); foreach (KeyValuePair texture in textures) { dictionary[texture.Key] = texture.Value; } return dictionary; } } [NullableContext(1)] public interface IMaterialEffect { void Apply(Material m); void Apply(MaterialPropertyBlock m); } [NullableContext(1)] [Nullable(0)] public abstract class MaterialEffect<[Nullable(2)] T> { protected string Name; protected T Value; public MaterialEffect(string name, T value) { Name = name; Value = value; } } [NullableContext(1)] [Nullable(0)] public class MaterialColorEffect : MaterialEffect, IMaterialEffect { public MaterialColorEffect(string name, Color value) : base(name, value) { }//IL_0002: Unknown result type (might be due to invalid IL or missing references) public void Apply(Material m) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) m.SetColor(Name, Value); } public void Apply(MaterialPropertyBlock m) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) m.SetColor(Name, Value); } } [Nullable(0)] [NullableContext(1)] public class MaterialFloatEffect : MaterialEffect, IMaterialEffect { public MaterialFloatEffect(string name, float value) : base(name, value) { } public void Apply(Material m) { m.SetFloat(Name, Value); } public void Apply(MaterialPropertyBlock m) { m.SetFloat(Name, Value); } } [NullableContext(1)] [Nullable(new byte[] { 0, 1 })] public class MaterialTextureEffect : MaterialEffect, IMaterialEffect { public MaterialTextureEffect(string name, Texture value) : base(name, value) { } public void Apply(Material m) { m.SetTexture(Name, Value); } public void Apply(MaterialPropertyBlock m) { m.SetTexture(Name, Value); } } [NullableContext(1)] [Nullable(0)] internal class MaterialManipulator { private List properties = new List(); public MaterialManipulator(MaterialData data) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) if (data.colors != null) { foreach (KeyValuePair color in data.colors) { AddValue(new MaterialColorEffect(color.Key, color.Value)); } } if (data.floats != null) { foreach (KeyValuePair @float in data.floats) { AddValue(new MaterialFloatEffect(@float.Key, @float.Value)); } } if (data.textures == null) { return; } foreach (KeyValuePair texture in TextureDataManager.GetTextures(data.textures)) { AddValue(new MaterialTextureEffect(texture.Key, (Texture)(object)texture.Value)); } } public void ForceTextures(MaterialData data) { foreach (KeyValuePair texture in data.textures) { AddValue(new MaterialTextureEffect(texture.Key, (Texture)(object)TextureDataManager.GetTexture(texture.Key))); } } public void Invoke(Renderer smr, GameObject prefab) { properties.ForEach(delegate(IMaterialEffect p) { Material[] sharedMaterials = smr.sharedMaterials; foreach (Material val in sharedMaterials) { if (Object.op_Implicit((Object)(object)val)) { p.Apply(val); } } }); } public void Invoke(Material m, GameObject prefab) { properties.ForEach(delegate(IMaterialEffect e) { if (Object.op_Implicit((Object)(object)m)) { e.Apply(m); } }); } public void AddValue(IMaterialEffect p) { if (p != null) { properties.Add(p); } } } [Nullable(0)] [NullableContext(1)] public static class PrefabAssistant { public static List GetRenderers(GameObject item) { Transform val = item.transform.Find("attach_skin"); Transform val2 = item.transform.Find("attach"); Transform dropChild = GetDropChild(item); List list = new List(); Renderer[] array = (Renderer[])(object)(((Object)(object)val != (Object)null) ? ((Component)val).GetComponentsInChildren(true) : null); Renderer[] array2 = array; array = (Renderer[])(object)(((Object)(object)dropChild != (Object)null) ? ((Component)dropChild).GetComponentsInChildren(true) : null); Renderer[] array3 = array; array = (Renderer[])(object)(((Object)(object)val2 != (Object)null) ? ((Component)val2).GetComponentsInChildren(true) : null); Renderer[] array4 = array; if (array2 != null) { list.AddRange(array2); } if (array3 != null) { list.AddRange(array3); } if (array4 != null) { list.AddRange(array4); } return list; } public static Transform GetDropChild(GameObject item) { for (int i = 0; i < item.transform.childCount; i++) { Transform child = item.transform.GetChild(i); if (!((Object)child).name.Contains("attach")) { return child; } } return null; } public static Transform AddFlare(Transform t) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) Transform obj = Object.Instantiate(ObjectDB.instance.GetItemPrefab("BattleaxeCrystal").transform.Find("attach").Find("flare"), t, false); ((Object)obj).name = "flare"; obj.localPosition = Vector3.zero; return obj; } public static DescriptorData Describe(string prefabName) { //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Invalid comparison between Unknown and I4 //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Invalid comparison between Unknown and I4 //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Invalid comparison between Unknown and I4 //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Invalid comparison between Unknown and I4 //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Unknown result type (might be due to invalid IL or missing references) DescriptorData descriptorData = new DescriptorData { Name = prefabName }; GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(prefabName); if (!Object.op_Implicit((Object)(object)itemPrefab)) { WMRecipeCust.WLog.LogInfo((object)" item describe is null"); return descriptorData; } Transform val = itemPrefab.transform.Find("attach_skin") ?? itemPrefab.transform.Find("attach") ?? itemPrefab.transform; Renderer[] array = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponentsInChildren(true) : itemPrefab.GetComponentsInChildren(true)); for (int i = 0; i < array.Length; i++) { RendererDescriptor rendererDescriptor = new RendererDescriptor { Name = ((Object)val).name }; for (int j = 0; j < array[i].sharedMaterials.Length; j++) { Material val2 = array[i].sharedMaterials[j]; MaterialDescriptor materialDescriptor = new MaterialDescriptor { Name = ((Object)array[i].sharedMaterials[j]).name, Shader = ((Object)val2.shader).name }; int propertyCount = val2.shader.GetPropertyCount(); for (int k = 0; k < propertyCount; k++) { ShaderPropertyType propertyType = val2.shader.GetPropertyType(k); string propertyName = val2.shader.GetPropertyName(k); MaterialPropertyDescriptor obj = new MaterialPropertyDescriptor { Name = propertyName, Type = ((object)(ShaderPropertyType)(ref propertyType)).ToString(), Range = (((int)propertyType == 3) ? $"{val2.shader.GetPropertyRangeLimits(k).x} to {val2.shader.GetPropertyRangeLimits(k).y}" : null) }; object value; if ((int)propertyType != 0) { if ((int)propertyType != 3) { if ((int)propertyType != 2) { if ((int)propertyType != 1) { value = null; } else { Vector4 vector = val2.GetVector(propertyName); value = ((object)(Vector4)(ref vector)).ToString(); } } else { value = val2.GetFloat(propertyName).ToString(); } } else { value = val2.GetFloat(propertyName).ToString(); } } else { Color color = val2.GetColor(propertyName); value = ((object)(Color)(ref color)).ToString(); } obj.Value = (string)value; MaterialPropertyDescriptor item = obj; materialDescriptor.MaterialProperties.Add(item); } rendererDescriptor.Materials.Add(materialDescriptor); } descriptorData.Renderers.Add(rendererDescriptor); } WMRecipeCust.WLog.LogInfo((object)"done with describe data"); return descriptorData; } private static string SaveMaterial(Material material, string actualName) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected I4, but got Unknown //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Expected O, but got Unknown YamlLoader yamlLoader = new YamlLoader(); MaterialInstance materialInstance = new MaterialInstance { original = actualName, name = actualName + "_clone", overwrite = false }; int propertyCount = material.shader.GetPropertyCount(); for (int i = 0; i < propertyCount; i++) { ShaderPropertyType propertyType = material.shader.GetPropertyType(i); string propertyName = material.shader.GetPropertyName(i); switch ((int)propertyType) { case 0: materialInstance.changes.colors.Add(propertyName, material.GetColor(propertyName)); break; case 1: case 2: case 3: materialInstance.changes.floats.Add(propertyName, material.GetFloat(propertyName)); break; case 4: { Texture texture = material.GetTexture(propertyName); try { if ((Object)(object)texture != (Object)null) { materialInstance.changes.textures.Add(propertyName, (Texture2D)texture); TextureDataManager.SaveTexture(((Object)texture).name, texture); } } catch (Exception ex) { Debug.LogError((object)("[WackysDatabase]: Unable to write texture for property: " + propertyName + " - " + ex.Message)); } break; } } } yamlLoader.Write(Path.Combine(WMRecipeCust.assetPathMaterials, materialInstance.name + ".yml"), materialInstance); return materialInstance.name; } public static string SaveMaterial(string materialName) { string actualName = null; Material val = null; if (WMRecipeCust.originalMaterials.ContainsKey(materialName)) { val = WMRecipeCust.originalMaterials[materialName]; actualName = materialName; } else { string text = materialName.Replace('_', ' '); if (WMRecipeCust.originalMaterials.ContainsKey(text)) { val = WMRecipeCust.originalMaterials[text]; actualName = text; } } if ((Object)(object)val == (Object)null) { return null; } return SaveMaterial(val, actualName); } public static void UpdateItemMaterialReference(GameObject prefab, Material m) { prefab.GetComponent().m_itemData.m_shared.m_armorMaterial = m; } public static void UpdateChestTexture(GameObject prefab, Texture2D texture) { prefab.GetComponent().m_itemData.m_shared.m_armorMaterial.SetTexture("_ChestTex", (Texture)(object)texture); } public static void UpdateLegTexture(GameObject prefab, Texture2D texture) { prefab.GetComponent().m_itemData.m_shared.m_armorMaterial.SetTexture("_LegTex", (Texture)(object)texture); } public static void UpdateIcon(ItemDrop item, Vector3 r) { //IL_0018: 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_006e: 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_00d0: 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_00dc: 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_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_0186: 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_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: 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_01d7: 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_020e: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Unknown result type (might be due to invalid IL or missing references) //IL_0245: 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_0265: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Unknown result type (might be due to invalid IL or missing references) //IL_029c: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Expected O, but got Unknown //IL_02a5: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: 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) Camera component = new GameObject("Camera", new Type[1] { typeof(Camera) }).GetComponent(); component.backgroundColor = Color.clear; component.clearFlags = (CameraClearFlags)2; component.fieldOfView = 0.5f; component.farClipPlane = 10000000f; component.cullingMask = 1073741824; Light component2 = new GameObject("Light", new Type[1] { typeof(Light) }).GetComponent(); ((Component)component2).transform.rotation = Quaternion.Euler(60f, -5f, 0f); component2.type = (LightType)1; component2.cullingMask = 1073741824; component2.intensity = 0.7f; try { Rect val = default(Rect); ((Rect)(ref val))..ctor(0f, 0f, 64f, 64f); Quaternion val2 = Quaternion.Euler(r.x, r.y, r.z); Transform val3 = ((Component)item).transform.Find("attach"); if (!Object.op_Implicit((Object)(object)val3)) { val3 = GetDropChild(((Component)item).gameObject); } GameObject val4 = Object.Instantiate(((Component)val3).gameObject, Vector3.zero, val2); Transform[] componentsInChildren = val4.GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren.Length; i++) { ((Component)componentsInChildren[i]).gameObject.layer = 30; } Renderer[] componentsInChildren2 = val4.GetComponentsInChildren(true); Vector3 val5 = componentsInChildren2.Aggregate(Vector3.positiveInfinity, [NullableContext(0)] (Vector3 cur, Renderer renderer) => { //IL_001d: 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_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (!(renderer is ParticleSystemRenderer)) { Bounds bounds2 = renderer.bounds; return Vector3.Min(cur, ((Bounds)(ref bounds2)).min); } return cur; }); Vector3 val6 = componentsInChildren2.Aggregate(Vector3.negativeInfinity, [NullableContext(0)] (Vector3 cur, Renderer renderer) => { //IL_001d: 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_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (!(renderer is ParticleSystemRenderer)) { Bounds bounds = renderer.bounds; return Vector3.Max(cur, ((Bounds)(ref bounds)).max); } return cur; }); Vector3 val7 = val6 - val5; component.targetTexture = RenderTexture.GetTemporary((int)((Rect)(ref val)).width, (int)((Rect)(ref val)).height); float num = Mathf.Max(val7.x, val7.y) * 1.05f / Mathf.Tan(component.fieldOfView * ((float)Math.PI / 180f)); Transform transform = ((Component)component).transform; transform.position = (val5 + val6) / 2f + new Vector3(0f, 0f, 0f - num); ((Component)component2).transform.position = transform.position + new Vector3(-2f, 0.2f) / 3f * num; component.Render(); RenderTexture active = RenderTexture.active; RenderTexture.active = component.targetTexture; Texture2D val8 = new Texture2D((int)((Rect)(ref val)).width, (int)((Rect)(ref val)).height, (TextureFormat)4, false); val8.ReadPixels(val, 0, 0); val8.Apply(); RenderTexture.active = active; item.m_itemData.m_shared.m_icons = (Sprite[])(object)new Sprite[1] { Sprite.Create(val8, val, new Vector2(0.5f, 0.5f)) }; Object.DestroyImmediate((Object)(object)val4); component.targetTexture.Release(); } catch (Exception ex) { Debug.LogError((object)("[WackysDatabase]: Failed to update icon - " + ex.Message)); } finally { Object.Destroy((Object)(object)component); Object.Destroy((Object)(object)component2); } } public static void UpdateMaterialReference(Renderer r, Material m) { if ((Object)(object)m == (Object)null) { Debug.LogError((object)"[WackysDatabase]: Failed to retrieve material"); return; } if (WMRecipeCust.isDebugString.Value) { Debug.Log((object)("[WackysDatabase]: " + ((Object)r).name + " - Updating material to: " + ((Object)m).name)); } if (r.sharedMaterials.Length > 1) { Material[] sharedMaterials = r.sharedMaterials; for (int i = 0; i < sharedMaterials.Length; i++) { sharedMaterials[i] = m; } r.sharedMaterials = sharedMaterials; } else { r.sharedMaterial = m; } } public static void UpdateMaterialReferences(Renderer r, Material[] materials) { Debug.Log((object)"Updating material references"); if (r.sharedMaterials.Length > 1) { r.sharedMaterials = materials; } else { r.sharedMaterial = materials[0]; } } } [NullableContext(1)] public interface ITextureEffect { void Apply(Material m, Texture2D t = null); void Apply(MaterialPropertyBlock m, Texture2D t = null); } [Nullable(0)] [NullableContext(1)] public abstract class TextureEffect<[Nullable(2)] T> { public T Value { get; set; } public string Name { get; set; } protected Texture2D Cache { get; set; } public TextureEffect(string name, T value) { Name = name; Value = value; } public abstract Texture2D Resolve(Texture2D texture, T color); public void Apply(Material m, Texture2D tex = null) { if ((Object)(object)tex == (Object)null) { tex = GetTexture(m); } if ((Object)(object)tex != (Object)null && m.HasProperty(Name)) { m.SetTexture(Name, (Texture)(object)Resolve(tex, Value)); } } public void Apply(MaterialPropertyBlock m, Texture2D tex = null) { if ((Object)(object)tex == (Object)null) { tex = GetTexture(m); } if ((Object)(object)tex != (Object)null) { m.SetTexture(Name, (Texture)(object)Resolve(tex, Value)); } } public Texture2D GetTexture(Material m) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown if (!Object.op_Implicit((Object)(object)Cache)) { Cache = (Texture2D)m.GetTexture(Name); } return Cache; } public Texture2D GetTexture(MaterialPropertyBlock m) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown if (!Object.op_Implicit((Object)(object)Cache)) { Cache = (Texture2D)m.GetTexture(Name); } return Cache; } } [Nullable(0)] [NullableContext(1)] public class TextureManipulator { private List effects = new List(); private Texture2D _texture; public TextureManipulator(TextureData data, Texture2D texture = null) { //IL_006a: 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 (Object.op_Implicit((Object)(object)texture)) { _texture = texture; } switch (data.Effect) { case TextureEffect.Multiply: AddValue(new TextureMultiplyEffect(data.Name, data.Colors[0])); break; case TextureEffect.Screen: AddValue(new TextureScreenEffect(data.Name, data.Colors[0])); break; case TextureEffect.Edge: AddValue(new TextureToonEffect(data.Name, data.Colors.ToArray())); break; case TextureEffect.Overlay: break; } } public void AddValue(ITextureEffect value) { if (value != null) { effects.Add(value); } } public void Invoke(Renderer smr) { effects.ForEach(delegate(ITextureEffect e) { Material[] sharedMaterials = smr.sharedMaterials; foreach (Material m in sharedMaterials) { e.Apply(m, _texture); } }); } public void Invoke(Material m) { effects.ForEach(delegate(ITextureEffect e) { e.Apply(m, _texture); }); } } public class TextureMultiplyEffect : TextureEffect, ITextureEffect { [NullableContext(1)] public TextureMultiplyEffect(string name, Color value) : base(name, value) { }//IL_0002: Unknown result type (might be due to invalid IL or missing references) [NullableContext(1)] public override Texture2D Resolve(Texture2D texture, Color color) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return Colour.AsMultiply(texture, color); } } public class TextureScreenEffect : TextureEffect, ITextureEffect { [NullableContext(1)] public TextureScreenEffect(string name, Color value) : base(name, value) { }//IL_0002: Unknown result type (might be due to invalid IL or missing references) [NullableContext(1)] public override Texture2D Resolve(Texture2D texture, Color color) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return Colour.AsScreen(texture, color); } } [NullableContext(1)] [Nullable(new byte[] { 0, 1 })] public class TextureToonEffect : TextureEffect, ITextureEffect { public TextureToonEffect(string name, Color[] value) : base(name, value) { } public override Texture2D Resolve(Texture2D texture, Color[] color) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_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_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) return Colour.AsCell(texture, Color32.op_Implicit(base.Value[0]), Color32.op_Implicit(base.Value[1]), Color32.op_Implicit(base.Value[2])); } } [BepInPlugin("WackyMole.WackysDatabase", "WackysDatabase", "2.4.79")] [NullableContext(1)] [Nullable(0)] public class WMRecipeCust : BaseUnityPlugin { [NullableContext(0)] private class ConfigurationManagerAttributes { public bool? Browsable = false; } internal const string ModName = "WackysDatabase"; internal const string ModVersion = "2.4.79"; internal const string Author = "WackyMole"; internal const string ModGUID = "WackyMole.WackysDatabase"; internal static string ConfigFileName = "WackyMole.WackysDatabase.cfg"; internal static string ConfigFileFullPath; internal static WMRecipeCust context; internal readonly Harmony _harmony = new Harmony("WackyMole.WackysDatabase"); public static readonly ManualLogSource WLog; internal static readonly ConfigSync ConfigSync; public static ConfigEntry NexusModID; public static ConfigEntry modEnabled; public static ConfigEntry isDebug; public static ConfigEntry isautoreload; public static ConfigEntry isDebugString; public static ConfigEntry WaterName; public static ConfigEntry globalArmorDurabilityLossMult; public static ConfigEntry globalArmorMovementModMult; public static ConfigEntry waterModifierName; public static ConfigEntry ServerDedLoad; public static ConfigEntry extraSecurity; public static ConfigEntry enableYMLWatcher; public static ConfigEntry clonedcache; public static ConfigEntry showLogs; public static ConfigEntry extraEffectList; [Nullable(2)] internal static ConfigEntry _serverConfigLocked; internal static readonly CustomSyncedValue skillConfigData; internal static readonly CustomSyncedValue largeTransfer; public static readonly ConditionalWeakTable requirementQuality; internal static bool issettoSinglePlayer; internal static bool isSettoAutoReload; internal static bool recieveServerInfo; internal static bool NoMoreLoading; internal static bool LoadinMultiplayerFirst; internal static string ConnectionError; internal static bool Firstrun; internal static bool AwakeHasRun; internal static bool FirstSessionRun; internal static bool FirstSS; internal static int spawnedinWorld; internal static bool dedLoad; internal static bool ssLock; internal static int ssLockcount; internal static bool waitingforFirstLoad; public static List recipeDatasYml; public static List itemDatasYml; public static List pieceDatasYml; public static List armorDatasYml; public static List effectDataYml; public static List creatureDatasYml; public static List pickableDatasYml; public static List treebaseDatasYml; public static List cacheItemsYML; public static List cacheMaterials; public static List cacheStatusYML; public static List ClonedI; public static List ClonedINoZ; public static Dictionary MasterCloneList; public static readonly Dictionary ClonedPrefabsMap; public static List ClonedP; public static List ClonedR; public static List ClonedE; public static List ClonedPI; public static List ClonedPTB; public static List ClonedC; public static Dictionary ClonedCC; public static List ClonedCR; public static List MockI; public static List BlacklistClone; public static List MultiplayerApproved; public static List SnapshotPiecestoDo; internal static string assetPath; internal static string assetPathconfig; internal static string assetPathItems; internal static string assetPathRecipes; internal static string assetPathPieces; internal static string assetPathTextures; internal static string assetPathMaterials; internal static string assetPathObjects; internal static string assetPathCreatures; internal static string assetPathPickables; internal static string assetPathOldJsons; internal static string assetPathBulkYML; internal static string assetPathBulkYMLItems; internal static string assetPathBulkYMLPieces; internal static string assetPathBulkYMLEffects; internal static string assetPathBulkYMLRecipes; internal static string assetPathBulkYMLCreatures; internal static string assetPathBulkYMLPickables; internal static string assetPathIcons; internal static string assetPathEffects; internal static string assetPathCache; internal static string jsonstring; internal static string ymlstring; internal static char StringSeparator; internal static bool Admin; public static List pieceWithLvl; internal static GameObject Root; internal static GameObject MockItemBase; public static PieceTable selectedPiecehammer; public static PieceTable[] MaybePieceStations; public static Dictionary AdminPiecesOnly; public static List RealPieceStations; public static List NewCraftingStations; public static Dictionary originalMaterials; public static Dictionary originalVFX; public static Dictionary originalSFX; public static Dictionary originalFX; public static Dictionary extraEffects; public static Dictionary RecipeMaxStationLvl; public static Dictionary> AttackSpeed; public static Dictionary> SEWeaponChoice; public static Dictionary hiddenRecipeUpgrade; public static Dictionary crossbowReloadingTime; public static Dictionary RequiredUpgradeItemsString; public static Dictionary RequiredCraftItemsString; public static Dictionary EndingStatusEffect; public static readonly Dictionary SEaddBonus; public static ReadFiles readFiles; public static Reload CurrentReload; public static List NoNotTheseSEs; internal static int kickcount; internal static bool jsonsFound; public static bool ForceLogout; internal static bool LobbyRegistered; internal static bool HasLobbied; internal static IEnumerable jsonfiles; internal static bool ReloadingOkay; internal static int ProcessWait; internal static int ProcessWaitforRead; internal static float WaitTime; internal static bool LockReload; internal static bool Reloading; internal static bool IsDedServer => (int)SystemInfo.graphicsDeviceType == 4; public void Awake() { StartupConfig(); assetPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "wackysDatabase"); string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; assetPathconfig = Path.Combine(Path.GetDirectoryName(configPath + directorySeparatorChar), "wackysDatabase"); assetPathItems = Path.Combine(assetPathconfig, "Items"); assetPathRecipes = Path.Combine(assetPathconfig, "Recipes"); assetPathPieces = Path.Combine(assetPathconfig, "Pieces"); assetPathMaterials = Path.Combine(assetPathconfig, "Materials"); assetPathTextures = Path.Combine(assetPathconfig, "Textures"); assetPathEffects = Path.Combine(assetPathconfig, "Effects"); assetPathObjects = Path.Combine(assetPathconfig, "Objects"); assetPathCreatures = Path.Combine(assetPathconfig, "Creatures"); assetPathPickables = Path.Combine(assetPathconfig, "Pickables"); string configPath2 = Paths.ConfigPath; directorySeparatorChar = Path.DirectorySeparatorChar; assetPathOldJsons = Path.Combine(Path.GetDirectoryName(configPath2 + directorySeparatorChar), "wackysDatabase-OldJsons"); string configPath3 = Paths.ConfigPath; directorySeparatorChar = Path.DirectorySeparatorChar; assetPathBulkYML = Path.Combine(Path.GetDirectoryName(configPath3 + directorySeparatorChar), "wackyDatabase-BulkYML"); assetPathBulkYMLItems = Path.Combine(assetPathBulkYML, "Items"); assetPathBulkYMLPieces = Path.Combine(assetPathBulkYML, "Pieces"); assetPathBulkYMLRecipes = Path.Combine(assetPathBulkYML, "Recipes"); assetPathBulkYMLEffects = Path.Combine(assetPathBulkYML, "Effects"); assetPathBulkYMLCreatures = Path.Combine(assetPathBulkYML, "Creatures"); assetPathBulkYMLPickables = Path.Combine(assetPathBulkYML, "Pickables"); assetPathIcons = Path.Combine(assetPathconfig, "Icons"); assetPathCache = Path.Combine(assetPathconfig, "Cache"); AnimationSpeedManager.Add(delegate(Character character, double speed) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 Player val = (Player)(object)((character is Player) ? character : null); if (val == null || !((Character)val).InAttack() || ((Humanoid)val).m_currentAttack == null) { return speed; } if ((int)((Humanoid)val).GetCurrentWeapon().m_shared.m_skillType == 11) { return speed; } GameObject val2 = ((Humanoid)val).GetCurrentWeapon()?.m_dropPrefab; Dictionary value; return ((Object)(object)val2 != (Object)null && AttackSpeed.TryGetValue(((Object)val2).name, out value)) ? (((Humanoid)val).m_currentAttackIsSecondary ? (speed * (double)value[true]) : (speed * (double)value[false])) : speed; }); Assembly executingAssembly = Assembly.GetExecutingAssembly(); _harmony.PatchAll(executingAssembly); ((MonoBehaviour)context).StartCoroutine(readFiles.GetDataFromFiles()); AwakeHasRun = true; readFiles.SetupWatcher(); skillConfigData.ValueChanged += CustomSyncEventDetected; largeTransfer.ValueChanged += LargeTransferDetected; } public static void Dbgl(string str = "", bool pref = true) { if (isDebug.Value) { Debug.Log((object)((pref ? "WackysDatabase " : "") + str)); } } private void StartupConfig() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Expected O, but got Unknown _serverConfigLocked = config("General", "Force Server Config", value: true, "Force Server Config"); ConfigSync.AddLockingConfigEntry(_serverConfigLocked); Root = new GameObject("myroot"); Root.SetActive(false); Object.DontDestroyOnLoad((Object)(object)Root); context = this; modEnabled = config("General", "Enabled", value: true, "Enable this mod"); NexusModID = config("General", "NexusModID", "1825", "NexusModID Number", synchronizedSetting: false); isDebug = config("General", "IsDebug", value: true, "Enable debug logs", synchronizedSetting: false); isDebugString = config("General", "StringisDebug", value: false, "Do You want to see the String Debug Log - extra logs"); isautoreload = config("General", "IsAutoReload", value: false, new ConfigDescription("Enable auto reload after wackydb_save or wackydb_clone for singleplayer", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Browsable = false } })); WaterName = config("Armor", "WaterName", "Water", "Water name for Armor Resistance", synchronizedSetting: false); ServerDedLoad = config("General", "DedServer load Memory", value: true, "Dedicated Servers will load wackydb files as a client would"); showLogs = config("General", "Display Normal Logs", value: true, "This should be left on, unless you have 2000+ yamls"); extraSecurity = config("General", "ExtraSecurity on Servers", value: true, "Makes sure a player can't load into a server after going into Singleplayer -resulting in Game Ver .0.0.1, - Recommended to keep this enabled"); enableYMLWatcher = config("General", "FileWatcher for YMLs", value: true, "EnableYMLWatcher Servers/Singleplayer, YMLs will autoreload if Wackydatabase folder changes(created,renamed,edited) - disable for some servers that auto reload too much"); extraEffectList = config("Effects", "List of Extra Effects", "lightningAOE", "Extra Effects to look for from base game or Mods - (Use_a_comma,No_spaces)"); ConfigSync.CurrentVersion = "2.4.79"; WLog.LogDebug((object)("Mod Version " + ConfigSync.CurrentVersion)); if (isautoreload.Value) { isSettoAutoReload = true; } else { isSettoAutoReload = false; } } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); } private void ReadConfigValues(object sender, FileSystemEventArgs e) { if (!File.Exists(ConfigFileFullPath)) { return; } try { ((BaseUnityPlugin)this).Config.Reload(); } catch { WLog.LogError((object)"There was an issue loading Config File "); } } private ConfigEntry config<[Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry val2 = ((BaseUnityPlugin)this).Config.Bind(group, name, value, val); ConfigSync.AddConfigEntry(val2).SynchronizedConfig = synchronizedSetting; return val2; } private ConfigEntry config<[Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty()), synchronizedSetting); } internal static void AddBlacklistClone(string prefab) { if (prefab != null && !BlacklistClone.Contains(prefab)) { BlacklistClone.Add(prefab); } } private void CustomSyncEventDetected() { if (!NoMoreLoading) { CurrentReload.SyncEventDetected(); } } private void LargeTransferDetected() { HandleData.RecievedData(); } internal static void CheckModFolder() { if (!Directory.Exists(assetPathconfig)) { Dbgl("Creating Config Mod folder"); Directory.CreateDirectory(assetPathconfig); Directory.CreateDirectory(assetPathItems); Directory.CreateDirectory(assetPathPieces); Directory.CreateDirectory(assetPathRecipes); Directory.CreateDirectory(assetPathTextures); Directory.CreateDirectory(assetPathMaterials); } if (!Directory.Exists(assetPathItems)) { Dbgl("Creating Items Folder"); Directory.CreateDirectory(assetPathItems); } if (!Directory.Exists(assetPathPieces)) { Dbgl("Creating Pieces Folder"); Directory.CreateDirectory(assetPathPieces); } if (!Directory.Exists(assetPathRecipes)) { Dbgl("Creating Recipes Folder"); Directory.CreateDirectory(assetPathRecipes); } if (!Directory.Exists(assetPathIcons)) { Dbgl("Creating Icons Folder"); Directory.CreateDirectory(assetPathIcons); } if (!Directory.Exists(assetPathEffects)) { Dbgl("Creating Effects folder"); Directory.CreateDirectory(assetPathEffects); } if (!Directory.Exists(assetPathCache)) { Dbgl("Creating Cache folder"); Directory.CreateDirectory(assetPathCache); } if (!Directory.Exists(assetPathObjects)) { Dbgl("Creating Objects folder"); Directory.CreateDirectory(assetPathObjects); } if (!Directory.Exists(assetPathTextures)) { Dbgl("Creating Texture folder"); Directory.CreateDirectory(assetPathTextures); } if (!Directory.Exists(assetPathMaterials)) { Dbgl("Creating Materials folder"); Directory.CreateDirectory(assetPathMaterials); } if (!Directory.Exists(assetPathCreatures)) { Dbgl("Creating Creature folder"); Directory.CreateDirectory(assetPathCreatures); } if (!Directory.Exists(assetPathPickables)) { Dbgl("Creating Pickable folder"); Directory.CreateDirectory(assetPathPickables); } } public static void DeleteCache() { string path = Path.Combine(assetPathCache, "Last_Cleared.txt"); Directory.Delete(assetPathCache, recursive: true); Directory.CreateDirectory(assetPathCache); File.WriteAllText(path, "2.4.79"); } public static void AdminReload(long peer, ZPackage go) { WLog.LogInfo((object)"Recieved Admin Request to Reload"); ReadFiles readFiles = new ReadFiles(); ((MonoBehaviour)context).StartCoroutine(readFiles.GetDataFromFiles()); WMRecipeCust.readFiles = readFiles; skillConfigData.Value = ymlstring; Reload reload = (CurrentReload = new Reload()); WLog.LogInfo((object)"Sent YML to clients"); if (ServerDedLoad.Value) { ((MonoBehaviour)context).StartCoroutine(reload.LoadAllRecipeData(reload: true, slowmode: true)); } } public static void GetAllMaterials(bool skipMD = false) { Material[] array = Resources.FindObjectsOfTypeAll(); GameObject[] array2 = Resources.FindObjectsOfTypeAll(); originalMaterials = new Dictionary(); originalVFX = new Dictionary(); originalSFX = new Dictionary(); originalFX = new Dictionary(); extraEffects = new Dictionary(); Material[] array3 = array; foreach (Material val in array3) { originalMaterials[((Object)val).name] = val; } List list = extraEffectList.Value.Split(new char[1] { ',' }).ToList(); GameObject[] array4 = array2; foreach (GameObject val2 in array4) { if (!((Object)(object)val2.GetComponent() != (Object)null) && !((Object)(object)val2.GetComponent() != (Object)null) && !((Object)(object)val2.GetComponent() != (Object)null)) { string text = ((Object)val2).name.ToLower(); bool flag = (Object)(object)val2.GetComponentInChildren() != (Object)null; bool flag2 = val2.GetComponentsInChildren().Any([NullableContext(0)] (Component c) => (Object)(object)c != (Object)null && ((object)c).GetType().Name == "AudioSource"); if (list.Contains(((Object)val2).name)) { extraEffects[((Object)val2).name] = val2; } if (text.Contains("vfx") || flag) { originalVFX[((Object)val2).name] = val2; } if (text.Contains("sfx") || flag2) { originalSFX[((Object)val2).name] = val2; } if (text.Contains("fx_") || (flag && flag2)) { originalFX[((Object)val2).name] = val2; } } } if (!skipMD) { MaterialDataManager.Instance.LoadFiles(); } } static WMRecipeCust() { string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName; WLog = Logger.CreateLogSource("WackysDatabase"); ConfigSync = new ConfigSync("WackyMole.WackysDatabase") { DisplayName = "WackysDatabase", MinimumRequiredVersion = "2.4.79" }; skillConfigData = new CustomSyncedValue(ConfigSync, "skillConfig", ""); largeTransfer = new CustomSyncedValue(ConfigSync, "largeTransfer", ""); requirementQuality = new ConditionalWeakTable(); issettoSinglePlayer = false; isSettoAutoReload = false; recieveServerInfo = false; NoMoreLoading = false; LoadinMultiplayerFirst = false; ConnectionError = ""; Firstrun = true; AwakeHasRun = false; FirstSessionRun = false; FirstSS = true; spawnedinWorld = 0; dedLoad = false; ssLock = false; ssLockcount = 0; waitingforFirstLoad = false; recipeDatasYml = new List(); itemDatasYml = new List(); pieceDatasYml = new List(); armorDatasYml = new List(); effectDataYml = new List(); creatureDatasYml = new List(); pickableDatasYml = new List(); treebaseDatasYml = new List(); cacheItemsYML = new List(); cacheMaterials = new List(); cacheStatusYML = new List(); ClonedI = new List(); ClonedINoZ = new List(); MasterCloneList = new Dictionary(); ClonedPrefabsMap = new Dictionary(); ClonedP = new List(); ClonedR = new List(); ClonedE = new List(); ClonedPI = new List(); ClonedPTB = new List(); ClonedC = new List(); ClonedCC = new Dictionary(); ClonedCR = new List(); MockI = new List(); BlacklistClone = new List(); MultiplayerApproved = new List(); SnapshotPiecestoDo = new List(); StringSeparator = 'Ⰴ'; Admin = true; pieceWithLvl = new List(); RealPieceStations = new List(); NewCraftingStations = new List(); RecipeMaxStationLvl = new Dictionary(); AttackSpeed = new Dictionary>(); SEWeaponChoice = new Dictionary>(); crossbowReloadingTime = new Dictionary(); RequiredUpgradeItemsString = new Dictionary(); RequiredCraftItemsString = new Dictionary(); EndingStatusEffect = new Dictionary(); SEaddBonus = new Dictionary(StringComparer.Ordinal); readFiles = new ReadFiles(); CurrentReload = new Reload(); NoNotTheseSEs = new List { "GoblinShaman_shield", "SE_Dvergr_heal", "SE_Greydwarf_shaman_heal" }; kickcount = 0; jsonsFound = false; ForceLogout = false; LobbyRegistered = false; HasLobbied = false; ReloadingOkay = false; ProcessWait = 10; ProcessWaitforRead = 10; WaitTime = 0.3f; LockReload = false; Reloading = false; } } [Nullable(0)] [NullableContext(1)] public class Colour { private static Color GRAYSCALE = new Color(0.2126729f, 0.7151522f, 0.072175f); public static Texture2D CloneTextureAsNormal(Texture2D texture) { //IL_000f: 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_0021: Expected O, but got Unknown Texture2D val = new Texture2D(((Texture)texture).width, ((Texture)texture).height, (TextureFormat)4, false, true); val.SetPixels(texture.GetPixels()); return val; } public static Texture2D CloneTexture(Texture2D texture) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0053: 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_0072: Expected O, but got Unknown RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 24, (RenderTextureFormat)0, (RenderTextureReadWrite)2); Graphics.Blit((Texture)(object)texture, temporary); RenderTexture active = RenderTexture.active; RenderTexture.active = temporary; Texture2D val = new Texture2D(((Texture)texture).width, ((Texture)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); return val; } public static Color Screen(Color pixel, Color screen) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_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_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_0021: Unknown result type (might be due to invalid IL or missing references) Color result = pixel + screen - pixel * screen; result.a = pixel.a; return result; } public static Color Multiply(Color pixel, Color multiply) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_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_0015: Unknown result type (might be due to invalid IL or missing references) Color result = pixel * multiply; result.a = pixel.a; return result; } public static Color Overlay(Color pixel, Color overlay) { //IL_0052: 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_0058: 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_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_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) if (!((double)((Color)(ref pixel)).grayscale < 0.5)) { return Color.white - Color.white * 2f * (Color.white - pixel) * (Color.white - overlay); } return 2f * pixel * overlay; } private static float Luminance(Color a) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) return GRAYSCALE.r * a.r + GRAYSCALE.g * a.g + GRAYSCALE.b * a.b; } public static Color32 Cell(Color32 initial, Color32 high, Color32 low, Color32 mid, float midHigh = 0.66f, float midLow = 0.33f) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0072: 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_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_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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_006b: 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) float num = Luminance(Color32.op_Implicit(initial)); if (num >= midHigh) { Color val = Color.Lerp(Color32.op_Implicit(initial), Color32.op_Implicit(high), num / 2f); val.a = (int)initial.a; return Color32.op_Implicit(val); } if (num <= midLow) { Color val2 = Color.Lerp(Color32.op_Implicit(initial), Color32.op_Implicit(low), num / 2f); val2.a = (int)initial.a; return Color32.op_Implicit(val2); } return Color32.op_Implicit(Color.Lerp(Color32.op_Implicit(initial), Color32.op_Implicit(mid), num / 2f)); } public static Texture2D AsGrayscale(Texture2D texture) { //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_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) Texture2D val = CloneTexture(texture); try { Color[] pixels = val.GetPixels(); Color[] array = (Color[])(object)new Color[pixels.Length]; for (uint num = 0u; num < ((Texture)texture).width; num++) { for (uint num2 = 0u; num2 < ((Texture)texture).height; num2++) { Color val2 = pixels[num + num2 * ((Texture)texture).width]; array[num + num2 * ((Texture)texture).width] = val2 * GRAYSCALE; } } val.SetPixels(array); val.Apply(); } catch (Exception ex) { Debug.Log((object)ex.Message); } return val; } public static Texture2D AsGrayscaleColoured(Texture2D texture, Color colour) { //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_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) Texture2D val = CloneTexture(texture); try { Color[] pixels = val.GetPixels(); Color[] array = (Color[])(object)new Color[pixels.Length]; for (uint num = 0u; num < ((Texture)texture).width; num++) { for (uint num2 = 0u; num2 < ((Texture)texture).height; num2++) { Color val2 = pixels[num + num2 * ((Texture)texture).width]; array[num + num2 * ((Texture)texture).width] = Screen(val2 * GRAYSCALE, colour); } } val.SetPixels(array); val.Apply(); } catch (Exception ex) { Debug.Log((object)ex.Message); } return val; } public static Texture2D AsScreen(Texture2D texture, Color colour) { //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_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) Texture2D val = CloneTexture(texture); try { Color32[] pixels = val.GetPixels32(); Color32[] array = (Color32[])(object)new Color32[pixels.Length]; for (uint num = 0u; num < ((Texture)texture).width; num++) { for (uint num2 = 0u; num2 < ((Texture)texture).height; num2++) { Color32 val2 = pixels[num + num2 * ((Texture)texture).width]; array[num + num2 * ((Texture)texture).width] = Color32.op_Implicit(Screen(Color32.op_Implicit(val2), colour)); } } val.SetPixels32(array); val.Apply(); } catch (Exception ex) { Debug.Log((object)ex.Message); } return val; } public static Texture2D AsMultiply(Texture2D texture, Color colour) { //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_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) Texture2D val = CloneTexture(texture); try { Color32[] pixels = val.GetPixels32(); Color32[] array = (Color32[])(object)new Color32[pixels.Length]; for (uint num = 0u; num < ((Texture)texture).width; num++) { for (uint num2 = 0u; num2 < ((Texture)texture).height; num2++) { Color32 val2 = pixels[num + num2 * ((Texture)texture).width]; array[num + num2 * ((Texture)texture).width] = Color32.op_Implicit(Multiply(Color32.op_Implicit(val2), colour)); } } val.SetPixels32(array); val.Apply(); } catch (Exception ex) { Debug.Log((object)ex.Message); } return val; } public static Texture2D AsCell(Texture2D texture, Color32 high, Color32 low, Color32? mid) { //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_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_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_009c: 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_0058: 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_005c: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) Texture2D val = CloneTexture(texture); try { Color32[] pixels = val.GetPixels32(); Color32[] array = (Color32[])(object)new Color32[pixels.Length]; for (uint num = 0u; num < ((Texture)texture).width; num++) { for (uint num2 = 0u; num2 < ((Texture)texture).height; num2++) { Color32 val2 = pixels[num + num2 * ((Texture)texture).width]; if (mid.HasValue) { array[num + num2 * ((Texture)texture).width] = Cell(val2, high, low, mid.Value); } else { array[num + num2 * ((Texture)texture).width] = Cell(val2, high, low, val2); } } } val.SetPixels32(array); val.Apply(); } catch (Exception ex) { Debug.Log((object)ex.Message); } return val; } } [NullableContext(1)] [Nullable(0)] public static class VisualController { static VisualController() { MaterialDataManager.Instance.OnMaterialAdd += DataManager_OnMaterialAdd; MaterialDataManager.Instance.OnMaterialChange += DataManager_OnMaterialChange; MaterialDataManager.Instance.OnMaterialOverwrite += DataManager_OnMaterialOverwrite; } private static void DataManager_OnMaterialChange(object sender, MaterialEventArgs e) { new MaterialManipulator(e.MaterialInstance.changes).Invoke(e.Material, null); } private static void DataManager_OnMaterialAdd(object sender, MaterialEventArgs e) { Debug.Log((object)("[WackysDatabase]: Setting material properties for: " + ((Object)e.Material).name)); new MaterialManipulator(e.MaterialInstance.changes).Invoke(e.Material, null); } private static void DataManager_OnMaterialOverwrite(object sender, MaterialEventArgs e) { new MaterialManipulator(e.MaterialInstance.changes).Invoke(e.Material, null); } public static void UpdatePrefab(string name, CustomVisual visual) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(name); if ((Object)(object)itemPrefab == (Object)null) { Debug.LogError((object)("[WackysDatabase]: Failed to find prefab " + name)); return; } if (visual == null) { Debug.LogError((object)("[WackysDatabase]: No custom visuals for " + name)); return; } Debug.Log((object)(name + ": Base: " + visual.base_mat + ", Legs: " + visual.legs + ", Chest: " + visual.chest)); try { List renderers = PrefabAssistant.GetRenderers(itemPrefab); if (visual.chest != null && visual.chest != "") { Material material = MaterialDataManager.Instance.GetMaterial(visual.chest); if ((Object)(object)material != (Object)null) { PrefabAssistant.UpdateItemMaterialReference(itemPrefab, material); } else { Debug.LogWarning((object)("[WackysDatabase]: Failed to get chest material " + visual.chest)); } } if (visual.legs != null && visual.legs != "") { Material material2 = MaterialDataManager.Instance.GetMaterial(visual.legs); if ((Object)(object)material2 != (Object)null) { PrefabAssistant.UpdateItemMaterialReference(itemPrefab, material2); } else { Debug.LogWarning((object)("[WackysDatabase]: Failed to get leg material " + visual.legs)); } } if (visual.base_mat != null && visual.base_mat != "") { Material material3 = MaterialDataManager.Instance.GetMaterial(visual.base_mat); for (int i = 0; i < renderers.Count; i++) { PrefabAssistant.UpdateMaterialReference(renderers[i], material3); } } } catch (Exception ex) { Debug.LogError((object)("[WackysDatabase]: Failed to update material - " + ex.Message + " - " + ex.StackTrace)); } } public static void Export(DescriptorData data) { string contents = DataManager.Serializer.Serialize(data); string assetPathconfig = WMRecipeCust.assetPathconfig; if (!Directory.Exists(assetPathconfig)) { Directory.CreateDirectory(assetPathconfig); } File.WriteAllText(Path.Combine(assetPathconfig, "Describe_" + data.Name + ".yml"), contents); } } } namespace wackydatabase.Util { public static class CheckIt { [NullableContext(1)] public static void SetWhenNotNull(string mightBeNull, ref string notNullable) { if (mightBeNull != null) { notNullable = mightBeNull; } } } public static class Ob { [NullableContext(1)] public static T Cast<[Nullable(2)] T>(this Object myobj) { Type type = ((object)myobj).GetType(); Type typeFromHandle = typeof(T); object obj = Activator.CreateInstance(typeFromHandle, nonPublic: false); _ = from source in type.GetMembers().ToList() where source.MemberType == MemberTypes.Property select source; IEnumerable d = from source in typeFromHandle.GetMembers().ToList() where source.MemberType == MemberTypes.Property select source; foreach (MemberInfo item in d.Where((MemberInfo memberInfo) => d.Select((MemberInfo c) => c.Name).ToList().Contains(memberInfo.Name)).ToList()) { PropertyInfo? property = typeof(T).GetProperty(item.Name); object value = ((object)myobj).GetType().GetProperty(item.Name).GetValue(myobj, null); property.SetValue(obj, value, null); } return (T)obj; } } [Nullable(0)] [NullableContext(1)] public class Functions { [CompilerGenerated] private sealed class <>c__DisplayClass14_0 { public Quaternion? cameraRotation; public float lightIntensity; [Nullable(0)] public ItemDrop item; public Quaternion? itemRotation; } [Nullable(2)] private static BaseUnityPlugin _plugin; private static BaseUnityPlugin plugin { get { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown if (_plugin == null) { IEnumerable source; try { source = Assembly.GetExecutingAssembly().DefinedTypes.ToList(); } catch (ReflectionTypeLoadException ex) { source = from t in ex.Types where t != null select t.GetTypeInfo(); } _plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); } return _plugin; } } internal static FieldInfo CompField(Type ClassTyp, string fieldname) { return ClassTyp.GetField(fieldname, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } internal static T getCast<[Nullable(2)] T>(Type ClassTyp, string fieldname, StatusEffect effect) { FieldInfo fieldInfo = CompField(ClassTyp, fieldname); if (fieldInfo == null) { return default(T); } if (typeof(T).IsAssignableFrom(fieldInfo.FieldType)) { return (T)fieldInfo.GetValue(effect); } throw new InvalidCastException($"Cannot cast {fieldInfo.FieldType} to {typeof(T)}."); } internal static void setValue(Type type, object go, string name, float? value = null, int? value2 = null, [Nullable(2)] string value3 = null, [Nullable(2)] List value4 = null, SkillType? value5 = null, Vector3? value6 = null, DamageTypes? value7 = null) { //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) FieldInfo fieldInfo = CompField(type, name); if (fieldInfo == null) { return; } object obj = null; if (value.HasValue) { obj = value.Value; } else if (value2.HasValue) { obj = value2.Value; } else if (value3 != null) { obj = value3; } else if (value4 != null) { obj = value4; } else if (value5.HasValue) { obj = value5.Value; } else if (value6.HasValue) { obj = value6.Value; } else if (value7.HasValue) { obj = value7.Value; } if (obj == null) { return; } try { Type fieldType = fieldInfo.FieldType; Type type2 = Nullable.GetUnderlyingType(fieldType) ?? fieldType; if (type2.IsInstanceOfType(obj)) { fieldInfo.SetValue(go, obj); return; } object obj2 = null; if (type2.IsEnum) { obj2 = ((!(obj is string value8)) ? Enum.ToObject(type2, obj) : Enum.Parse(type2, value8)); } else if (obj is IConvertible) { obj2 = Convert.ChangeType(obj, type2, CultureInfo.InvariantCulture); } else if (type2 == typeof(Vector3) && obj is Vector3) { obj2 = obj; } else if (type2.IsAssignableFrom(obj.GetType())) { obj2 = obj; } if (obj2 != null) { fieldInfo.SetValue(go, obj2); } else { fieldInfo.SetValue(go, obj); } } catch (Exception ex) { WMRecipeCust.WLog.LogDebug((object)("Reflection setValue failed for field '" + name + "' on '" + type.FullName + "': " + ex.Message)); } } internal static string ComputeSha256Hash(string rawData) { using SHA256 sHA = SHA256.Create(); byte[] array = sHA.ComputeHash(Encoding.UTF8.GetBytes(rawData)); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < array.Length; i++) { stringBuilder.Append(array[i].ToString("x2")); } return stringBuilder.ToString(); } public static float stringtoFloat(string data) { data = data.Split(new char[1] { ':' }).Last(); return float.Parse(data, CultureInfo.InvariantCulture.NumberFormat); } public static string GetAllMaterialsFile() { string text = ""; Material[] array = Resources.FindObjectsOfTypeAll(); foreach (Material val in array) { Dbgl("Material " + ((Object)val).name); text = text + ((Object)val).name + Environment.NewLine; } return text; } public static string GetAllVFXFile() { string text = ""; GameObject[] array = Resources.FindObjectsOfTypeAll(); WMRecipeCust.originalVFX = new Dictionary(); HashSet hashSet = new HashSet(); GameObject[] array2 = array; foreach (GameObject val in array2) { if (!hashSet.Contains(((Object)val).name) && !((Object)(object)val.GetComponent() != (Object)null) && !((Object)(object)val.GetComponent() != (Object)null) && !((Object)(object)val.GetComponent() != (Object)null) && (((Object)val).name.ToLower().StartsWith("vfx") || (Object)(object)val.GetComponentInChildren() != (Object)null)) { WMRecipeCust.originalVFX[((Object)val).name] = val; text = text + ((Object)val).name + Environment.NewLine; hashSet.Add(((Object)val).name); } } return text; } public static string GetAllSFXFile() { string text = ""; GameObject[] array = Resources.FindObjectsOfTypeAll(); WMRecipeCust.originalSFX = new Dictionary(); HashSet hashSet = new HashSet(); GameObject[] array2 = array; foreach (GameObject val in array2) { if (!hashSet.Contains(((Object)val).name) && !((Object)(object)val.GetComponent() != (Object)null) && !((Object)(object)val.GetComponent() != (Object)null) && !((Object)(object)val.GetComponent() != (Object)null) && (((Object)val).name.ToLower().StartsWith("sfx") || val.GetComponentsInChildren().Any([NullableContext(0)] (Component c) => (Object)(object)c != (Object)null && ((object)c).GetType().Name == "AudioSource"))) { WMRecipeCust.originalSFX[((Object)val).name] = val; text = text + ((Object)val).name + Environment.NewLine; hashSet.Add(((Object)val).name); } } return text; } public static string GetAllFXFile() { string text = ""; GameObject[] array = Resources.FindObjectsOfTypeAll(); WMRecipeCust.originalFX = new Dictionary(); HashSet hashSet = new HashSet(); GameObject[] array2 = array; foreach (GameObject val in array2) { if (!hashSet.Contains(((Object)val).name) && !((Object)(object)val.GetComponent() != (Object)null) && !((Object)(object)val.GetComponent() != (Object)null) && !((Object)(object)val.GetComponent() != (Object)null) && (((Object)val).name.ToLower().StartsWith("fx_") || ((Object)(object)val.GetComponentInChildren() != (Object)null && val.GetComponentsInChildren().Any([NullableContext(0)] (Component c) => (Object)(object)c != (Object)null && ((object)c).GetType().Name == "AudioSource")))) { WMRecipeCust.originalFX[((Object)val).name] = val; text = text + ((Object)val).name + Environment.NewLine; hashSet.Add(((Object)val).name); } } return text; } public static void Dbgl(string str = "", bool pref = true) { if (WMRecipeCust.isDebug.Value) { Debug.Log((object)((pref ? "WackysDatabase " : "") + str)); } } public static void SnapshotPiece(GameObject prefab, float lightIntensity = 1.3f, Quaternion? cameraRotation = null) { if (Object.op_Implicit((Object)(object)ObjectDB.instance)) { Do2(); } void Do2() { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_008e: 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_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_0190: 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_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_0227: 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_0267: Unknown result type (might be due to invalid IL or missing references) //IL_026c: 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_027a: Unknown result type (might be due to invalid IL or missing references) //IL_027f: 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_028d: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Unknown result type (might be due to invalid IL or missing references) //IL_02e5: Unknown result type (might be due to invalid IL or missing references) //IL_02ec: Unknown result type (might be due to invalid IL or missing references) //IL_032d: Unknown result type (might be due to invalid IL or missing references) //IL_033e: Unknown result type (might be due to invalid IL or missing references) //IL_0343: Unknown result type (might be due to invalid IL or missing references) //IL_0375: Unknown result type (might be due to invalid IL or missing references) //IL_037c: Expected O, but got Unknown //IL_039a: Unknown result type (might be due to invalid IL or missing references) //IL_03db: Unknown result type (might be due to invalid IL or missing references) //IL_03e0: Unknown result type (might be due to invalid IL or missing references) //IL_03ea: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)prefab == (Object)null) && (prefab.GetComponentsInChildren().Any() || prefab.GetComponentsInChildren().Any())) { Vector3 position = ((Component)Player.m_localPlayer).transform.position; 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; position.y = -100f; GameObject val = Object.Instantiate(prefab.gameObject, position, Quaternion.Euler(23f, 51f, 25.8f)); Transform[] componentsInChildren = val.GetComponentsInChildren(); for (int i = 0; i < componentsInChildren.Length; i++) { ((Component)componentsInChildren[i]).gameObject.layer = 3; } val.transform.position = Vector3.zero; val.transform.rotation = Quaternion.Euler(23f, 51f, 25.8f); MeshRenderer[] componentsInChildren2 = val.GetComponentsInChildren(); Vector3 val2 = componentsInChildren2.Aggregate(Vector3.positiveInfinity, [NullableContext(0)] (Vector3 cur, MeshRenderer 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)renderer).bounds; return Vector3.Min(cur, ((Bounds)(ref bounds2)).min); }); Vector3 val3 = componentsInChildren2.Aggregate(Vector3.negativeInfinity, [NullableContext(0)] (Vector3 cur, MeshRenderer 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)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; val.AddComponent().Trigger(1f); Rect val5 = default(Rect); ((Rect)(ref val5))..ctor(0f, 0f, 128f, 128f); component.targetTexture = RenderTexture.GetTemporary((int)((Rect)(ref val5)).width, (int)((Rect)(ref val5)).height); component.fieldOfView = 20f; float num = (Mathf.Max(val4.x, val4.y) + 0.1f) / Mathf.Tan(component.fieldOfView * ((float)Math.PI / 180f)) * 1.1f; ((Component)component).transform.position = new Vector3(10000f, 10000f, 10000f) + new Vector3(0f, 0f, num); component.Render(); RenderTexture active = RenderTexture.active; RenderTexture.active = component.targetTexture; Texture2D val6 = new Texture2D((int)((Rect)(ref val5)).width, (int)((Rect)(ref val5)).height, (TextureFormat)4, false); val6.ReadPixels(new Rect(0f, 0f, (float)(int)((Rect)(ref val5)).width, (float)(int)((Rect)(ref val5)).height), 0, 0); val6.Apply(); RenderTexture.active = active; prefab.GetComponent().m_icon = Sprite.Create(val6, new Rect(0f, 0f, (float)(int)((Rect)(ref val5)).width, (float)(int)((Rect)(ref val5)).height), Vector2.one / 2f); Object.DestroyImmediate((Object)(object)val.GetComponent()); ((Component)component2).gameObject.SetActive(false); component.targetTexture.Release(); ((Component)component).gameObject.SetActive(false); val.SetActive(false); Object.Destroy((Object)(object)component); Object.Destroy((Object)(object)component2); Object.Destroy((Object)(object)((Component)component).gameObject); Object.Destroy((Object)(object)((Component)component2).gameObject); } } } public static void SnapshotItem(ItemDrop item, float lightIntensity = 1.3f, Quaternion? cameraRotation = null, Quaternion? itemRotation = null) { <>c__DisplayClass14_0 CS$<>8__locals0 = new <>c__DisplayClass14_0(); CS$<>8__locals0.cameraRotation = cameraRotation; CS$<>8__locals0.lightIntensity = lightIntensity; CS$<>8__locals0.item = item; CS$<>8__locals0.itemRotation = itemRotation; if (Object.op_Implicit((Object)(object)ObjectDB.instance)) { ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(WackyDelay()); } else { ((MonoBehaviour)plugin).StartCoroutine(Delay()); } [IteratorStateMachine(typeof(<>c__DisplayClass14_0.<g__Delay|1>d))] IEnumerator Delay() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <>c__DisplayClass14_0.<g__Delay|1>d(0) { <>4__this = CS$<>8__locals0 }; } [IteratorStateMachine(typeof(<>c__DisplayClass14_0.<g__WackyDelay|2>d))] IEnumerator WackyDelay() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <>c__DisplayClass14_0.<g__WackyDelay|2>d(0) { <>4__this = CS$<>8__locals0 }; } } } } namespace wackydatabase.Read { [NullableContext(1)] [Nullable(0)] public class ReadFiles { [CompilerGenerated] private sealed class d__4 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; public bool slowmode; [Nullable(0)] public ReadFiles <>4__this; [Nullable(0)] private YamlLoader 5__2; [Nullable(0)] private YamlLoader 5__3; [Nullable(0)] private string[] <>7__wrap3; private int <>7__wrap4; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__4(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; 5__3 = null; <>7__wrap3 = null; <>1__state = -2; } private bool MoveNext() { //IL_0668: Unknown result type (might be due to invalid IL or missing references) //IL_0672: Expected O, but got Unknown //IL_0706: Unknown result type (might be due to invalid IL or missing references) //IL_0710: Expected O, but got Unknown //IL_07a5: Unknown result type (might be due to invalid IL or missing references) //IL_07af: Expected O, but got Unknown //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Expected O, but got Unknown //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Expected O, but got Unknown //IL_02bc: Unknown result type (might be due to invalid IL or missing references) //IL_02c6: Expected O, but got Unknown //IL_0378: Unknown result type (might be due to invalid IL or missing references) //IL_0382: Expected O, but got Unknown //IL_0434: Unknown result type (might be due to invalid IL or missing references) //IL_043e: Expected O, but got Unknown //IL_04f0: Unknown result type (might be due to invalid IL or missing references) //IL_04fa: Expected O, but got Unknown //IL_05ac: Unknown result type (might be due to invalid IL or missing references) //IL_05b6: Expected O, but got Unknown int num = <>1__state; ReadFiles readFiles = <>4__this; int num2; switch (num) { default: return false; case 0: <>1__state = -1; WMRecipeCust.recipeDatasYml.Clear(); WMRecipeCust.itemDatasYml.Clear(); WMRecipeCust.pieceDatasYml.Clear(); WMRecipeCust.creatureDatasYml.Clear(); WMRecipeCust.pieceWithLvl.Clear(); WMRecipeCust.effectDataYml.Clear(); WMRecipeCust.pickableDatasYml.Clear(); WMRecipeCust.treebaseDatasYml.Clear(); WMRecipeCust.ymlstring = ""; WMRecipeCust.CheckModFolder(); 5__2 = new YamlLoader(); num2 = 0; if (slowmode) { WMRecipeCust.WLog.LogInfo((object)"Beginning SLOW Reading"); WMRecipeCust.LockReload = true; } <>7__wrap3 = Directory.GetFiles(WMRecipeCust.assetPathconfig, "?tem_*.yml", SearchOption.AllDirectories); <>7__wrap4 = 0; goto IL_016e; case 1: <>1__state = -1; num2 = 0; goto IL_0160; case 2: <>1__state = -1; num2 = 0; goto IL_021c; case 3: <>1__state = -1; num2 = 0; goto IL_02d8; case 4: <>1__state = -1; num2 = 0; goto IL_0394; case 5: <>1__state = -1; num2 = 0; goto IL_0450; case 6: <>1__state = -1; num2 = 0; goto IL_050c; case 7: <>1__state = -1; num2 = 0; goto IL_05c8; case 8: <>1__state = -1; num2 = 0; goto IL_0684; case 9: <>1__state = -1; num2 = 0; goto IL_0723; case 10: { <>1__state = -1; num2 = 0; goto IL_07c2; } IL_021c: <>7__wrap4++; goto IL_022a; IL_016e: if (<>7__wrap4 < <>7__wrap3.Length) { string text = <>7__wrap3[<>7__wrap4]; string text2 = File.ReadAllText(text); if (text2.Contains("m_weight")) { 5__2.Load(text, WMRecipeCust.itemDatasYml, text2); } num2++; if ((num2 > WMRecipeCust.ProcessWaitforRead) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 1; return true; } goto IL_0160; } <>7__wrap3 = null; <>7__wrap3 = Directory.GetFiles(WMRecipeCust.assetPathconfig, "?iece_*.yml", SearchOption.AllDirectories); <>7__wrap4 = 0; goto IL_022a; IL_0160: <>7__wrap4++; goto IL_016e; IL_022a: if (<>7__wrap4 < <>7__wrap3.Length) { string text3 = <>7__wrap3[<>7__wrap4]; string text4 = File.ReadAllText(text3); if (text4.Contains("piecehammer")) { 5__2.Load(text3, WMRecipeCust.pieceDatasYml, text4); } num2++; if ((num2 > WMRecipeCust.ProcessWaitforRead) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 2; return true; } goto IL_021c; } <>7__wrap3 = null; <>7__wrap3 = Directory.GetFiles(WMRecipeCust.assetPathconfig, "?ecipe_*.yml", SearchOption.AllDirectories); <>7__wrap4 = 0; goto IL_02e6; IL_07c2: <>7__wrap4++; goto IL_07d0; IL_02e6: if (<>7__wrap4 < <>7__wrap3.Length) { string text5 = <>7__wrap3[<>7__wrap4]; string text6 = File.ReadAllText(text5); if (text6.Contains("reqs")) { 5__2.Load(text5, WMRecipeCust.recipeDatasYml, text6); } num2++; if ((num2 > WMRecipeCust.ProcessWaitforRead) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 3; return true; } goto IL_02d8; } <>7__wrap3 = null; <>7__wrap3 = Directory.GetFiles(WMRecipeCust.assetPathconfig, "SE_*.yml", SearchOption.AllDirectories); <>7__wrap4 = 0; goto IL_03a2; IL_02d8: <>7__wrap4++; goto IL_02e6; IL_03a2: if (<>7__wrap4 < <>7__wrap3.Length) { string text7 = <>7__wrap3[<>7__wrap4]; string text8 = File.ReadAllText(text7); if (text8.Contains("Status_m_name")) { 5__2.Load(text7, WMRecipeCust.effectDataYml, text8); } num2++; if ((num2 > WMRecipeCust.ProcessWaitforRead) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 4; return true; } goto IL_0394; } <>7__wrap3 = null; <>7__wrap3 = Directory.GetFiles(WMRecipeCust.assetPathconfig, "?reature_*.yml", SearchOption.AllDirectories); <>7__wrap4 = 0; goto IL_045e; IL_0394: <>7__wrap4++; goto IL_03a2; IL_045e: if (<>7__wrap4 < <>7__wrap3.Length) { string text9 = <>7__wrap3[<>7__wrap4]; string text10 = File.ReadAllText(text9); if (text10.Contains("mob_display_name")) { 5__2.Load(text9, WMRecipeCust.creatureDatasYml, text10); } num2++; if ((num2 > WMRecipeCust.ProcessWaitforRead) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 5; return true; } goto IL_0450; } <>7__wrap3 = null; <>7__wrap3 = Directory.GetFiles(WMRecipeCust.assetPathconfig, "?ickable_*.yml", SearchOption.AllDirectories); <>7__wrap4 = 0; goto IL_051a; IL_0450: <>7__wrap4++; goto IL_045e; IL_051a: if (<>7__wrap4 < <>7__wrap3.Length) { string text11 = <>7__wrap3[<>7__wrap4]; string text12 = File.ReadAllText(text11); if (text12.Contains("itemPrefab")) { 5__2.Load(text11, WMRecipeCust.pickableDatasYml, text12); } num2++; if ((num2 > WMRecipeCust.ProcessWaitforRead) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 6; return true; } goto IL_050c; } <>7__wrap3 = null; <>7__wrap3 = Directory.GetFiles(WMRecipeCust.assetPathconfig, "?reebase_*.yml", SearchOption.AllDirectories); <>7__wrap4 = 0; goto IL_05d6; IL_050c: <>7__wrap4++; goto IL_051a; IL_05d6: if (<>7__wrap4 < <>7__wrap3.Length) { string text13 = <>7__wrap3[<>7__wrap4]; string text14 = File.ReadAllText(text13); if (text14.Contains("treeHealth")) { 5__2.Load(text13, WMRecipeCust.treebaseDatasYml, text14); } num2++; if ((num2 > WMRecipeCust.ProcessWaitforRead) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 7; return true; } goto IL_05c8; } <>7__wrap3 = null; WMRecipeCust.ymlstring = 5__2.ToString(); 5__3 = new YamlLoader(); <>7__wrap3 = Directory.GetFiles(WMRecipeCust.assetPathCache, "*.zz", SearchOption.AllDirectories); <>7__wrap4 = 0; goto IL_0692; IL_05c8: <>7__wrap4++; goto IL_05d6; IL_0692: if (<>7__wrap4 < <>7__wrap3.Length) { string file = <>7__wrap3[<>7__wrap4]; 5__3.Load(file, WMRecipeCust.cacheItemsYML); num2++; if ((num2 > WMRecipeCust.ProcessWaitforRead) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 8; return true; } goto IL_0684; } <>7__wrap3 = null; <>7__wrap3 = Directory.GetFiles(WMRecipeCust.assetPathCache, "*.mat", SearchOption.AllDirectories); <>7__wrap4 = 0; goto IL_0731; IL_0684: <>7__wrap4++; goto IL_0692; IL_0731: if (<>7__wrap4 < <>7__wrap3.Length) { string file2 = <>7__wrap3[<>7__wrap4]; 5__3.Load(file2, WMRecipeCust.cacheMaterials); num2++; if ((num2 > WMRecipeCust.ProcessWaitforRead) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 9; return true; } goto IL_0723; } <>7__wrap3 = null; <>7__wrap3 = Directory.GetFiles(WMRecipeCust.assetPathCache, "*.se", SearchOption.AllDirectories); <>7__wrap4 = 0; goto IL_07d0; IL_0723: <>7__wrap4++; goto IL_0731; IL_07d0: if (<>7__wrap4 < <>7__wrap3.Length) { string file3 = <>7__wrap3[<>7__wrap4]; 5__3.Load(file3, WMRecipeCust.cacheStatusYML); num2++; if ((num2 > WMRecipeCust.ProcessWaitforRead) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 10; return true; } goto IL_07c2; } <>7__wrap3 = null; readFiles.GetAllTextures(); WMRecipeCust.LockReload = false; if (slowmode) { WMRecipeCust.WLog.LogInfo((object)"Finished SLOW Reading"); } WMRecipeCust.WLog.LogInfo((object)"Finished reading YML files"); if (WMRecipeCust.isDebugString.Value) { WMRecipeCust.WLog.LogInfo((object)WMRecipeCust.ymlstring); } 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(); } } [CompilerGenerated] private sealed class d__3 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__3(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>2__current = (object)new WaitForSeconds(10f); <>1__state = 1; return true; case 1: <>1__state = -1; WMRecipeCust.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 void SetupWatcher() { WMRecipeCust.CheckModFolder(); FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(WMRecipeCust.assetPathconfig); fileSystemWatcher.Changed += ReadYMLValues; fileSystemWatcher.Created += ReadYMLValues; fileSystemWatcher.Renamed += ReadYMLValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private void ReadYMLValues(object sender, FileSystemEventArgs e) { if (!File.Exists(WMRecipeCust.ConfigFileFullPath) || e.FullPath.Contains("Visuals") || e.FullPath.Contains("Materials") || !e.FullPath.Contains("yml")) { return; } try { if (((ZNet.instance.IsServer() && ZNet.instance.IsDedicated() && WMRecipeCust.enableYMLWatcher.Value) || (ZNet.instance.IsServer() && WMRecipeCust.isSettoAutoReload && WMRecipeCust.enableYMLWatcher.Value)) && !WMRecipeCust.Reloading) { WMRecipeCust.Dbgl("YML files have changed. Server or Singleplayer and Autoreload is on"); ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(GetDataFromFiles()); ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(StartReloadingTimer()); WMRecipeCust.skillConfigData.Value = WMRecipeCust.ymlstring; WMRecipeCust.Reloading = true; } } catch { if (WMRecipeCust.issettoSinglePlayer) { WMRecipeCust.WLog.LogError((object)"Please check your YML entries for spelling and format!"); } else { WMRecipeCust.WLog.LogDebug((object)"Not checking YML Files because either in Main Screen or ...."); } } } public void GetCacheClonesOnly() { WMRecipeCust.cacheItemsYML.Clear(); WMRecipeCust.cacheStatusYML.Clear(); YamlLoader yamlLoader = new YamlLoader(); string[] files = Directory.GetFiles(WMRecipeCust.assetPathCache, "*.zz", SearchOption.AllDirectories); foreach (string file in files) { yamlLoader.Load(file, WMRecipeCust.cacheItemsYML); } files = Directory.GetFiles(WMRecipeCust.assetPathCache, "*.se", SearchOption.AllDirectories); foreach (string file2 in files) { yamlLoader.Load(file2, WMRecipeCust.cacheStatusYML); } } [IteratorStateMachine(typeof(d__3))] internal IEnumerator StartReloadingTimer() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__3(0); } [IteratorStateMachine(typeof(d__4))] internal IEnumerator GetDataFromFiles(bool slowmode = false, bool singleplayeronly = false) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__4(0) { <>4__this = this, slowmode = slowmode }; } public void GetAllTextures() { string[] files = Directory.GetFiles(WMRecipeCust.assetPathTextures, "*.png", SearchOption.AllDirectories); for (int i = 0; i < files.Length; i++) { TextureDataManager.GetTexture(new FileInfo(files[i]).Name); } } } } namespace wackydatabase.Startup { internal class Closing { [HarmonyPatch(typeof(ZNet), "Shutdown")] private class PatchZNetDisconnect { private static void Prefix() { WMRecipeCust.Dbgl("logoff"); WMRecipeCust.LobbyRegistered = false; WMRecipeCust.FirstSS = true; if (WMRecipeCust.issettoSinglePlayer) { DestroyClones(); } else { DestroyClones(); } WMRecipeCust.NoMoreLoading = true; } } [HarmonyPatch(typeof(ZNet), "OnDestroy")] private class PatchZNetDestory { private static void Postfix() { WMRecipeCust.recieveServerInfo = false; WMRecipeCust.NoMoreLoading = false; } } internal static void DestroyClones() { ZNetScene instance = ZNetScene.instance; ObjectDB instance2 = ObjectDB.instance; GameObject val = null; foreach (string item in WMRecipeCust.ClonedR) { try { for (int num = ObjectDB.instance.m_recipes.Count - 1; num > 0; num--) { if (((Object)ObjectDB.instance.m_recipes[num]).name == item) { instance2.m_recipes.RemoveAt(num); } } } catch { WMRecipeCust.Dbgl("Error Disabling recipe " + item); } } foreach (KeyValuePair item2 in WMRecipeCust.ClonedCC) { try { int stableHashCode = StringExtensionMethods.GetStableHashCode(item2.Key); instance.m_prefabs.Remove(item2.Value); instance.m_namedPrefabs.Remove(stableHashCode); Object.Destroy((Object)(object)item2.Value); } catch { WMRecipeCust.Dbgl($"Error Destorying Creature {item2}"); } } foreach (string item3 in WMRecipeCust.ClonedP) { val = null; WMRecipeCust.selectedPiecehammer = null; try { GameObject val2 = DataHelpers.GetModdedPieces(item3); if ((Object)(object)val2 == (Object)null) { val2 = DataHelpers.CheckforSpecialObjects(item3); val = ObjectDB.instance.GetItemPrefab("Hammer"); } if ((Object)(object)WMRecipeCust.selectedPiecehammer != (Object)null) { WMRecipeCust.selectedPiecehammer.m_pieces.Remove(val2); } else { val.GetComponent().m_itemData.m_shared.m_buildPieces.m_pieces.Remove(val2); } instance.m_prefabs.Remove(val2); int stableHashCode2 = StringExtensionMethods.GetStableHashCode(((Object)val2).name); instance.m_namedPrefabs.Remove(stableHashCode2); } catch { WMRecipeCust.Dbgl("Error Destorying piece " + item3); } } WMRecipeCust.ClonedR.Clear(); WMRecipeCust.ClonedP.Clear(); WMRecipeCust.ClonedC.Clear(); WMRecipeCust.ClonedCC.Clear(); WMRecipeCust.ClonedCR.Clear(); WMRecipeCust.Dbgl("All cloned objects, except items, Destroyed"); } } internal class Startup { [HarmonyPatch(typeof(FejdStartup), "SetupObjectDB")] private static class FejdStartupObjectDBSetup { private static void Postfix() { if (!WMRecipeCust.IsDedServer) { WMRecipeCust.Dbgl("Checking Cache Folder and Loading Any Item/Mock Clones"); new ReadFiles().GetCacheClonesOnly(); Reload reload = new Reload(); reload.LoadCacheStatus(); reload.LoadClonedCachedItems(); if (WMRecipeCust.FirstSessionRun) { new Reload().AddClonedItemstoObjectDB(); } if (!WMRecipeCust.FirstSessionRun) { WMRecipeCust.FirstSessionRun = true; } } } } [HarmonyPatch(typeof(ZoneSystem), "Start")] [HarmonyPriority(500)] private static class ZoneSystemStart { private static void Prefix() { if (ZNet.instance.IsServer() && ZNet.instance.IsDedicated()) { WMRecipeCust.WLog.LogInfo((object)"Dedicated with loaded memory"); Reload reload = (WMRecipeCust.CurrentReload = new Reload()); if (WMRecipeCust.ServerDedLoad.Value) { WMRecipeCust.dedLoad = true; ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(reload.LoadAllRecipeData(reload: true)); } else { WMRecipeCust.CheckModFolder(); WMRecipeCust.Firstrun = false; WMRecipeCust.WLog.LogInfo((object)"Dedicated with no load memory"); WMRecipeCust.skillConfigData.Value = WMRecipeCust.ymlstring; } } if (ZNet.instance.IsServer() && (!ZNet.instance.IsServer() || !ZNet.instance.IsDedicated())) { Reload reload2 = (WMRecipeCust.CurrentReload = new Reload()); ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(reload2.LoadAllRecipeData(reload: true)); } } } [HarmonyPatch(typeof(ObjectDB), "Awake")] [HarmonyPriority(100)] private static class ObjectAwake { private static void Postfix() { if (!WMRecipeCust.modEnabled.Value) { return; } if (WMRecipeCust.dedLoad) { PrepareLoadData(); } if (!WMRecipeCust.FirstSessionRun) { return; } WMRecipeCust.Dbgl("ObjectDB 2nd Awake Load"); if ((Object)(object)ZNet.instance != (Object)null) { WMRecipeCust.Dbgl("ZnetActive in ObjectDB Awake "); if (!WMRecipeCust.IsDedServer) { new Reload().AddClonedItemstoObjectDB(); } if (ZNet.instance.IsServer()) { PrepareLoadData(); } if (!ZNet.instance.IsServer() && WMRecipeCust.HasLobbied) { WMRecipeCust.ForceLogout = true; } } } } [HarmonyPatch(typeof(ZNetScene), "Awake")] private static class ZNetScene_Awake_Patch_LastWackysDatabase { private static void Postfix() { if (WMRecipeCust.modEnabled.Value) { WMRecipeCust.CurrentReload.LoadZDOsForClones(); if (WMRecipeCust.ServerDedLoad.Value && WMRecipeCust.IsDedServer) { WMRecipeCust.dedLoad = true; } } } } [HarmonyPatch(typeof(FejdStartup), "Start")] public static class FejdStartupPatch { [NullableContext(1)] private static void Postfix(FejdStartup __instance) { if (!WMRecipeCust.IsDedServer) { WMRecipeCust.WLog.LogInfo((object)"extra YML read"); ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(WMRecipeCust.readFiles.GetDataFromFiles(slowmode: false, singleplayeronly: true)); } } } [HarmonyPatch(typeof(ZNet), "OpenServer")] public static class OpenServerWacky { [NullableContext(1)] private static void Postfix(ZNet __instance) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (!ZNet.m_isServer) { return; } try { if ((int)ZNet.m_onlineBackend == 1) { gamepassServer(); } else if ((int)ZNet.m_onlineBackend == 0) { steamServer(); } } catch { WMRecipeCust.WLog.LogWarning((object)"Steam or Gamepass wasn't found"); } } private static void steamServer() { WMRecipeCust.WLog.LogWarning((object)"Steam Lobby is active"); WMRecipeCust.LobbyRegistered = true; WMRecipeCust.skillConfigData.Value = WMRecipeCust.ymlstring; } private static void gamepassServer() { WMRecipeCust.WLog.LogWarning((object)"Zplay Lobby is active"); WMRecipeCust.LobbyRegistered = true; WMRecipeCust.skillConfigData.Value = WMRecipeCust.ymlstring; } } [HarmonyPriority(200)] [HarmonyPatch(typeof(Game), "_RequestRespawn")] public static class MainReloadStart { [NullableContext(1)] private static void Prefix(Game __instance) { if (WMRecipeCust.waitingforFirstLoad) { WMRecipeCust.waitingforFirstLoad = false; if (!ZNet.instance.IsServer() && CheckSecurity()) { WMRecipeCust.Dbgl(" Now loading SERVER Files"); ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(WMRecipeCust.CurrentReload.LoadAllRecipeData(reload: true)); WMRecipeCust.FirstSS = false; } } } } [HarmonyPatch(typeof(Game), "SpawnPlayer")] public static class SpawnPost { [NullableContext(1)] private static void Postfix(Game __instance) { foreach (GameObject item in WMRecipeCust.SnapshotPiecestoDo) { Functions.SnapshotPiece(item); } WMRecipeCust.SnapshotPiecestoDo.Clear(); } } public static bool SinglePlayerchecker { get { return WMRecipeCust.issettoSinglePlayer; } set { WMRecipeCust.issettoSinglePlayer = true; } } public static void DestroyStartupItems() { ObjectDB instance = ObjectDB.instance; foreach (string item in WMRecipeCust.ClonedI) { try { GameObject val = DataHelpers.CheckforSpecialObjects(item); if ((Object)(object)val == (Object)null) { val = instance.GetItemPrefab(item); } instance.m_items.Remove(val); Object.Destroy((Object)(object)val); } catch { WMRecipeCust.Dbgl("Error Destorying item " + item); } } WMRecipeCust.Dbgl("Destroyed cloned items used in startup "); WMRecipeCust.ClonedI.Clear(); WMRecipeCust.CurrentReload.UPdateItemHashesWacky(instance); } public static bool CheckSecurity() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) new ZNet(); if (WMRecipeCust.extraSecurity.Value && WMRecipeCust.ForceLogout) { WMRecipeCust.ConfigSync.CurrentVersion = "0.0.1"; WMRecipeCust.WLog.LogError((object)"You ARE kicked from Multiplayer Servers! 0.0.1"); WMRecipeCust.ConnectionError = "WackysDatabase You started a Local Game before Multiplayer. That is Not allowed. -Restart Game"; WMRecipeCust.WLog.LogError((object)WMRecipeCust.ConnectionError); Game.instance.Logout(true, true); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3); return false; } return true; } [NullableContext(1)] public static bool IsLocalInstance(ZNet znet) { if (znet.IsServer() && !znet.IsDedicated() && !WMRecipeCust.LobbyRegistered) { WMRecipeCust.issettoSinglePlayer = true; WMRecipeCust.ForceLogout = true; } if (WMRecipeCust.LobbyRegistered) { WMRecipeCust.ConfigSync.CurrentVersion = "2.4.79"; WMRecipeCust.HasLobbied = true; } return WMRecipeCust.issettoSinglePlayer; } public static void PrepareLoadData() { WMRecipeCust.ReloadingOkay = true; WMRecipeCust.waitingforFirstLoad = true; } } [HarmonyPatch(typeof(ZNetScene), "Awake")] internal static class ZrouteMethodsAdminReloadPushOnServer { internal static void Prefix() { if (ZNet.instance.IsServer()) { WMRecipeCust.WLog.LogInfo((object)"Server Ready to receive AdminReload"); ZRoutedRpc.instance.Register("WackyDBAdminReload", (Action)WMRecipeCust.AdminReload); ZRoutedRpc.instance.Register("WackyDBAdminBigData", (Action)HandleData.SendData); if (WMRecipeCust.Firstrun) { ObjModelLoader.LoadObjs(); if ((ZNet.instance.IsServer() & ZNet.instance.IsDedicated()) && !WMRecipeCust.ServerDedLoad.Value) { WMRecipeCust.Firstrun = false; } } } ZRoutedRpc.instance.Register("WackyDB_ClientMSG", (Action)HandleData.ClientMSG); ZRoutedRpc.instance.Register("WackyDB_AdminLogMsg", (Action)HandleData.AdminLogMsg); ZRoutedRpc.instance.Register("WackyDB_AssetManifest", (Action)HandleData.ReceiveManifest); ZRoutedRpc.instance.Register("WackyDB_AssetRequest", (Action)HandleData.ReceiveRequest); ZRoutedRpc.instance.Register("WackyDB_AssetPayload", (Action)HandleData.ReceivePayload); } } } namespace wackydatabase.SetData { internal class ObjectSetMock { [Nullable(1)] private static GameObject MockItemBase; private static bool CanMockItems; } [NullableContext(1)] [Nullable(0)] public class Reload { [CompilerGenerated] private sealed class d__10 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; public bool reload; public bool slowmode; public bool forcepush; [Nullable(0)] public Reload <>4__this; [Nullable(0)] private ObjectDB 5__2; [Nullable(new byte[] { 0, 1 })] private GameObject[] 5__3; [Nullable(new byte[] { 0, 1 })] private Pickable[] 5__4; [Nullable(new byte[] { 0, 1 })] private TreeBase[] 5__5; [Nullable(0)] private ISerializer 5__6; [Nullable(new byte[] { 0, 1 })] private List.Enumerator <>7__wrap6; [Nullable(new byte[] { 0, 1 })] private List.Enumerator <>7__wrap7; [Nullable(new byte[] { 0, 1 })] private List.Enumerator <>7__wrap8; [Nullable(new byte[] { 0, 1 })] private List.Enumerator <>7__wrap9; [Nullable(new byte[] { 0, 1 })] private List.Enumerator <>7__wrap10; [Nullable(new byte[] { 0, 1 })] private List.Enumerator <>7__wrap11; [Nullable(new byte[] { 0, 1 })] private List.Enumerator <>7__wrap12; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__10(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { switch (<>1__state) { case -3: case 2: try { } finally { <>m__Finally1(); } break; case -4: case 3: try { } finally { <>m__Finally2(); } break; case -5: case 4: try { } finally { <>m__Finally3(); } break; case -6: case 5: try { } finally { <>m__Finally4(); } break; case -7: case 6: try { } finally { <>m__Finally5(); } break; case -8: case 7: try { } finally { <>m__Finally6(); } break; case -9: case 8: try { } finally { <>m__Finally7(); } break; case -10: case 9: try { } finally { <>m__Finally8(); } break; case -11: case 10: try { } finally { <>m__Finally9(); } break; case -12: case 11: try { } finally { <>m__Finally10(); } break; case -13: case 12: try { } finally { <>m__Finally11(); } break; } 5__2 = null; 5__3 = null; 5__4 = null; 5__5 = null; 5__6 = null; <>7__wrap6 = default(List.Enumerator); <>7__wrap7 = default(List.Enumerator); <>7__wrap8 = default(List.Enumerator); <>7__wrap9 = default(List.Enumerator); <>7__wrap10 = default(List.Enumerator); <>7__wrap11 = default(List.Enumerator); <>7__wrap12 = default(List.Enumerator); <>1__state = -2; } private bool MoveNext() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Expected O, but got Unknown //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Expected O, but got Unknown //IL_034f: Unknown result type (might be due to invalid IL or missing references) //IL_0359: Expected O, but got Unknown //IL_0510: Unknown result type (might be due to invalid IL or missing references) //IL_051a: Expected O, but got Unknown //IL_05f8: Unknown result type (might be due to invalid IL or missing references) //IL_0602: Expected O, but got Unknown //IL_06ca: Unknown result type (might be due to invalid IL or missing references) //IL_06d4: Expected O, but got Unknown //IL_07a6: Unknown result type (might be due to invalid IL or missing references) //IL_07b0: Expected O, but got Unknown //IL_0872: Unknown result type (might be due to invalid IL or missing references) //IL_087c: Expected O, but got Unknown //IL_092a: Unknown result type (might be due to invalid IL or missing references) //IL_0934: Expected O, but got Unknown //IL_09ee: Unknown result type (might be due to invalid IL or missing references) //IL_09f8: Expected O, but got Unknown //IL_0b5a: Unknown result type (might be due to invalid IL or missing references) //IL_0b64: Expected O, but got Unknown //IL_0c57: Unknown result type (might be due to invalid IL or missing references) //IL_0c61: Expected O, but got Unknown //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Expected O, but got Unknown //IL_04b0: Unknown result type (might be due to invalid IL or missing references) try { int num = <>1__state; Reload reload = <>4__this; int num2; CraftingStation val = default(CraftingStation); switch (num) { default: return false; case 0: <>1__state = -1; if (this.reload) { wackydatabase.Startup.Startup.IsLocalInstance(new ZNet()); } if (WMRecipeCust.AwakeHasRun && WMRecipeCust.Firstrun) { WMRecipeCust.CheckModFolder(); WMRecipeCust.GetAllMaterials(); DataHelpers.GetPieceStations(); DataHelpers.GetPiecesatStart(); WMRecipeCust.Firstrun = false; if (WMRecipeCust.IsDedServer) { WMRecipeCust.skillConfigData.Value = WMRecipeCust.ymlstring; } else { _ = WMRecipeCust.LobbyRegistered; } } if (!WMRecipeCust.ServerDedLoad.Value && WMRecipeCust.IsDedServer) { return false; } 5__2 = ObjectDB.instance; 5__3 = Resources.FindObjectsOfTypeAll(); WMRecipeCust.SEWeaponChoice.Clear(); if (slowmode) { goto IL_0119; } WMRecipeCust.WLog.LogInfo((object)"Beginning Update"); goto IL_0140; case 1: <>1__state = -1; goto IL_0119; case 2: <>1__state = -3; num2 = 0; goto IL_01ef; case 3: <>1__state = -4; num2 = 0; goto IL_0371; case 4: <>1__state = -5; num2 = 0; goto IL_0532; case 5: <>1__state = -6; num2 = 0; goto IL_061a; case 6: <>1__state = -7; num2 = 0; goto IL_06ec; case 7: <>1__state = -8; num2 = 0; goto IL_07c8; case 8: <>1__state = -9; num2 = 0; goto IL_0894; case 9: <>1__state = -10; num2 = 0; goto IL_094d; case 10: <>1__state = -11; num2 = 0; goto IL_0a11; case 11: <>1__state = -12; num2 = 0; goto IL_0b7d; case 12: { <>1__state = -13; num2 = 0; break; } IL_0140: if (forcepush) { WMRecipeCust.skillConfigData.Value = WMRecipeCust.ymlstring; } num2 = 0; <>7__wrap6 = WMRecipeCust.effectDataYml.GetEnumerator(); <>1__state = -3; goto IL_01ef; IL_061a: while (<>7__wrap9.MoveNext()) { PickableData current = <>7__wrap9.Current; try { SetData.SetPickables(current, 5__4, 5__2); } catch { WMRecipeCust.WLog.LogWarning((object)("Set Pickables for " + current.name + " failed")); } num2++; if ((num2 > WMRecipeCust.ProcessWait) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 5; return true; } } <>m__Finally4(); <>7__wrap9 = default(List.Enumerator); WMRecipeCust.WLog.LogInfo((object)"Setting Treebase "); 5__5 = Resources.FindObjectsOfTypeAll(); <>7__wrap10 = WMRecipeCust.treebaseDatasYml.GetEnumerator(); <>1__state = -7; goto IL_06ec; IL_0b7d: while (<>7__wrap8.MoveNext()) { WItemData current2 = <>7__wrap8.Current; try { if (!string.IsNullOrEmpty(current2.clonePrefabName)) { int stableHashCode = StringExtensionMethods.GetStableHashCode(current2.name); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathCache, "_" + stableHashCode + ".zz"), 5__6.Serialize(current2)); } if (!string.IsNullOrEmpty(current2.mockName)) { int stableHashCode2 = StringExtensionMethods.GetStableHashCode(current2.name); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathCache, "_" + stableHashCode2 + ".zz"), 5__6.Serialize(current2)); } } catch { WMRecipeCust.WLog.LogWarning((object)("Item Cache save for " + current2.name + " failed")); } num2++; if ((num2 > WMRecipeCust.ProcessWait) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 11; return true; } } <>m__Finally10(); <>7__wrap8 = default(List.Enumerator); <>7__wrap6 = WMRecipeCust.effectDataYml.GetEnumerator(); <>1__state = -13; break; IL_01ef: while (<>7__wrap6.MoveNext()) { StatusData current3 = <>7__wrap6.Current; try { SetData.SetStatusData(current3, 5__2); } catch { WMRecipeCust.WLog.LogWarning((object)("SetEffect " + current3.Name + " failed")); } num2++; if ((num2 > WMRecipeCust.ProcessWait) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 2; return true; } } <>m__Finally1(); <>7__wrap6 = default(List.Enumerator); WMRecipeCust.WLog.LogInfo((object)" Set Effects Loaded"); <>7__wrap7 = WMRecipeCust.pieceDatasYml.GetEnumerator(); <>1__state = -4; goto IL_0371; IL_0a11: while (<>7__wrap12.MoveNext()) { CreatureData current4 = <>7__wrap12.Current; try { SetData.SetCreature(current4, 5__3); } catch { WMRecipeCust.WLog.LogWarning((object)("Set Creature for " + current4.name + " failed")); } num2++; if ((num2 > WMRecipeCust.ProcessWait) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 10; return true; } } <>m__Finally9(); <>7__wrap12 = default(List.Enumerator); WMRecipeCust.Dbgl("Building Cloned Cache for Player Items/Mock/Status"); 5__6 = new SerializerBuilder().Build(); new Random(); <>7__wrap8 = WMRecipeCust.itemDatasYml.GetEnumerator(); <>1__state = -12; goto IL_0b7d; IL_0371: while (<>7__wrap7.MoveNext()) { PieceData current5 = <>7__wrap7.Current; if (current5 != null && !string.IsNullOrEmpty(current5.clonePrefabName) && current5.craftingStationData != null) { try { if (DataHelpers.FindPieceObjectName(current5.clonePrefabName).TryGetComponent(ref val) && (Object)(object)DataHelpers.GetCraftingStation(val.m_name) != (Object)null) { SetData.SetPieceRecipeData(current5, 5__2, 5__3); } } catch { WMRecipeCust.WLog.LogWarning((object)("Setting Early Cloned CraftingStation for " + current5.name + " didn't complete")); } } else if (current5.craftingStationData != null && (Object)(object)DataHelpers.GetCraftingStation(current5.m_name) == (Object)null) { try { if ((Object)(object)DataHelpers.GetCraftingStation(current5.m_name) == (Object)null) { SetData.SetPieceRecipeData(current5, 5__2, 5__3); } } catch { WMRecipeCust.WLog.LogWarning((object)("Setting CraftingStation for " + current5.name + " didn't complete")); } } num2++; if ((num2 > WMRecipeCust.ProcessWait) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 3; return true; } } <>m__Finally2(); <>7__wrap7 = default(List.Enumerator); <>7__wrap8 = WMRecipeCust.itemDatasYml.GetEnumerator(); <>1__state = -5; goto IL_0532; IL_07c8: while (<>7__wrap7.MoveNext()) { PieceData current6 = <>7__wrap7.Current; if (!string.IsNullOrEmpty(current6.clonePrefabName)) { try { SetData.SetPieceRecipeData(current6, 5__2, 5__3); } catch { WMRecipeCust.WLog.LogWarning((object)("SetPiece Clone for " + current6.name + " failed")); } num2++; if ((num2 > WMRecipeCust.ProcessWait) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 7; return true; } } } <>m__Finally6(); <>7__wrap7 = default(List.Enumerator); WMRecipeCust.SnapshotPiecestoDo.Clear(); <>7__wrap7 = WMRecipeCust.pieceDatasYml.GetEnumerator(); <>1__state = -9; goto IL_0894; IL_0532: while (<>7__wrap8.MoveNext()) { WItemData current7 = <>7__wrap8.Current; try { SetData.SetItemData(current7, 5__2, 5__3); } catch { WMRecipeCust.WLog.LogWarning((object)("SetItem Data for " + current7.name + " failed")); } if (!string.IsNullOrEmpty(current7.clonePrefabName) || !string.IsNullOrEmpty(current7.mockName)) { WMRecipeCust.MultiplayerApproved.Add(current7.name); } if (current7.customVisual != null) { try { VisualController.UpdatePrefab(current7.name, current7.customVisual); if (DataHelpers.ECheck(current7.customIcon)) { Quaternion? itemRotation = null; if (current7.snapshotRotation != null) { float[] array = current7.snapshotRotation.Split(new char[1] { ',' }).Select(float.Parse).ToArray(); itemRotation = Quaternion.Euler(array[0], array[1], array[2]); } Functions.SnapshotItem(lastItemSet, 1.3f, null, itemRotation); } } catch { WMRecipeCust.WLog.LogWarning((object)("[WackysDatabase]: Failed to update visuals for " + current7.name)); } } num2++; if ((num2 > WMRecipeCust.ProcessWait) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 4; return true; } } <>m__Finally3(); <>7__wrap8 = default(List.Enumerator); reload.UPdateItemHashesWacky(5__2); WMRecipeCust.WLog.LogInfo((object)"Setting Pickables "); 5__4 = Resources.FindObjectsOfTypeAll(); <>7__wrap9 = WMRecipeCust.pickableDatasYml.GetEnumerator(); <>1__state = -6; goto IL_061a; IL_0894: while (<>7__wrap7.MoveNext()) { PieceData current8 = <>7__wrap7.Current; try { SetData.SetPieceRecipeData(current8, 5__2, 5__3); } catch { WMRecipeCust.WLog.LogWarning((object)("SetPiece Data for " + current8.name + " failed")); } num2++; if ((num2 > WMRecipeCust.ProcessWait) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 8; return true; } } <>m__Finally7(); <>7__wrap7 = default(List.Enumerator); <>7__wrap11 = WMRecipeCust.recipeDatasYml.GetEnumerator(); <>1__state = -10; goto IL_094d; IL_0119: if (WMRecipeCust.LockReload) { <>2__current = (object)new WaitForSeconds(1f); <>1__state = 1; return true; } WMRecipeCust.WLog.LogInfo((object)"Beginning SLOW Update"); goto IL_0140; IL_094d: while (<>7__wrap11.MoveNext()) { RecipeData current9 = <>7__wrap11.Current; try { SetData.SetRecipeData(current9, 5__2); } catch { WMRecipeCust.WLog.LogWarning((object)("SetRecipe Data for " + current9.name + " failed")); } num2++; if ((num2 > WMRecipeCust.ProcessWait) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 9; return true; } } <>m__Finally8(); <>7__wrap11 = default(List.Enumerator); WMRecipeCust.Dbgl("Setting Creatures "); <>7__wrap12 = WMRecipeCust.creatureDatasYml.GetEnumerator(); <>1__state = -11; goto IL_0a11; IL_06ec: while (<>7__wrap10.MoveNext()) { TreeBaseData current10 = <>7__wrap10.Current; try { SetData.SetTreeBase(current10, 5__5); } catch { WMRecipeCust.WLog.LogWarning((object)("Set TreeBase for " + current10.name + " failed")); } num2++; if ((num2 > WMRecipeCust.ProcessWait) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 6; return true; } } <>m__Finally5(); <>7__wrap10 = default(List.Enumerator); 5__3 = Resources.FindObjectsOfTypeAll(); <>7__wrap7 = WMRecipeCust.pieceDatasYml.GetEnumerator(); <>1__state = -8; goto IL_07c8; } while (<>7__wrap6.MoveNext()) { StatusData current11 = <>7__wrap6.Current; try { if (!string.IsNullOrEmpty(current11.Name)) { int stableHashCode3 = StringExtensionMethods.GetStableHashCode(current11.Name); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathCache, "_" + stableHashCode3 + ".se"), 5__6.Serialize(current11)); } } catch { WMRecipeCust.WLog.LogWarning((object)("Status Cache save for " + current11.Name + " failed")); } num2++; if ((num2 > WMRecipeCust.ProcessWait) & slowmode) { <>2__current = (object)new WaitForSeconds(WMRecipeCust.WaitTime); <>1__state = 12; return true; } } <>m__Finally11(); <>7__wrap6 = default(List.Enumerator); if (!WMRecipeCust.dedLoad) { reload.removeLocalData(); } reload.SortPieceHammers(); reload.UPdateItemHashesWacky(ObjectDB.instance); WMRecipeCust.WLog.LogInfo((object)" You finished wackydb reload"); Reload.OnAllReloaded?.Invoke(); if (Marketplace_API.IsInstalled() && !WMRecipeCust.dedLoad) { Marketplace_API.ResetTraderItems(); } WMRecipeCust.ssLock = false; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; ((IDisposable)<>7__wrap6).Dispose(); } private void <>m__Finally2() { <>1__state = -1; ((IDisposable)<>7__wrap7).Dispose(); } private void <>m__Finally3() { <>1__state = -1; ((IDisposable)<>7__wrap8).Dispose(); } private void <>m__Finally4() { <>1__state = -1; ((IDisposable)<>7__wrap9).Dispose(); } private void <>m__Finally5() { <>1__state = -1; ((IDisposable)<>7__wrap10).Dispose(); } private void <>m__Finally6() { <>1__state = -1; ((IDisposable)<>7__wrap7).Dispose(); } private void <>m__Finally7() { <>1__state = -1; ((IDisposable)<>7__wrap7).Dispose(); } private void <>m__Finally8() { <>1__state = -1; ((IDisposable)<>7__wrap11).Dispose(); } private void <>m__Finally9() { <>1__state = -1; ((IDisposable)<>7__wrap12).Dispose(); } private void <>m__Finally10() { <>1__state = -1; ((IDisposable)<>7__wrap8).Dispose(); } private void <>m__Finally11() { <>1__state = -1; ((IDisposable)<>7__wrap6).Dispose(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } internal static ItemDrop lastItemSet; public static event Action OnAllReloaded; public void SyncEventDetected() { if (ZNet.instance.IsServer()) { return; } if (WMRecipeCust.Firstrun) { WMRecipeCust.GetAllMaterials(); WMRecipeCust.Firstrun = false; DataHelpers.GetPieceStations(); DataHelpers.GetPiecesatStart(); if (!WMRecipeCust.isDebug.Value) { WMRecipeCust.WLog.LogInfo((object)"Debug is off, which suprisingly, makes it hard to debug"); } } if (WMRecipeCust.NoMoreLoading) { WMRecipeCust.recieveServerInfo = true; WMRecipeCust.NoMoreLoading = false; WMRecipeCust.WLog.LogInfo((object)"Warning any modifcations will still be On Your Local Games Until Restart! "); return; } if (WMRecipeCust.ssLock) { WMRecipeCust.ssLockcount++; if (WMRecipeCust.ssLockcount == 2) { WMRecipeCust.ssLockcount = 0; WMRecipeCust.ssLock = false; WMRecipeCust.WLog.LogWarning((object)" You recieved SERVER files again again, resetting"); } else { WMRecipeCust.WLog.LogWarning((object)" You recieved SERVER files again before finishing current ones, -bug wackydb"); } return; } WMRecipeCust.WLog.LogDebug((object)"CustomSyncEventDetected was called "); WMRecipeCust.Dbgl(" You recieved SERVER Files, so reloading"); WMRecipeCust.Admin = WMRecipeCust.ConfigSync.IsAdmin; WMRecipeCust.recieveServerInfo = true; WMRecipeCust.ssLock = true; if (WMRecipeCust.Admin) { WMRecipeCust.Dbgl(" You are an Admin"); } else { WMRecipeCust.Dbgl(" You are not an admin"); } WMRecipeCust.pieceWithLvl.Clear(); WMRecipeCust.recipeDatasYml.Clear(); WMRecipeCust.itemDatasYml.Clear(); WMRecipeCust.pieceDatasYml.Clear(); WMRecipeCust.effectDataYml.Clear(); WMRecipeCust.cacheItemsYML.Clear(); WMRecipeCust.creatureDatasYml.Clear(); WMRecipeCust.pickableDatasYml.Clear(); WMRecipeCust.treebaseDatasYml.Clear(); WMRecipeCust.MultiplayerApproved.Clear(); WMRecipeCust.SEaddBonus.Clear(); string value = WMRecipeCust.skillConfigData.Value; if (value != null && value != "") { if (WMRecipeCust.isDebugString.Value) { WMRecipeCust.WLog.LogInfo((object)("Synced String was " + value)); } IDeserializer deserializer = new DeserializerBuilder().WithTypeConverter(new ColorConverter()).WithTypeConverter(new TextureConverter()).WithTypeConverter(new ValheimTimeConverter()) .IgnoreUnmatchedProperties() .Build(); string[] array = value.Split(new char[1] { WMRecipeCust.StringSeparator }); foreach (string text in array) { if (WMRecipeCust.isDebugString.Value) { WMRecipeCust.WLog.LogInfo((object)("Current Parsing String is " + text)); } if (text.Contains("m_weight")) { WMRecipeCust.itemDatasYml.Add(deserializer.Deserialize(text)); } else if (text.Contains("piecehammer")) { WMRecipeCust.pieceDatasYml.Add(deserializer.Deserialize(text)); } else if (text.Contains("reqs")) { WMRecipeCust.recipeDatasYml.Add(deserializer.Deserialize(text)); } else if (text.Contains("Status_m_name")) { WMRecipeCust.effectDataYml.Add(deserializer.Deserialize(text)); } else if (text.Contains("mob_display_name")) { WMRecipeCust.creatureDatasYml.Add(deserializer.Deserialize(text)); } else if (text.Contains("itemPrefab")) { WMRecipeCust.pickableDatasYml.Add(deserializer.Deserialize(text)); } else if (text.Contains("treeHealth")) { WMRecipeCust.treebaseDatasYml.Add(deserializer.Deserialize(text)); } } if (WMRecipeCust.LoadinMultiplayerFirst) { WMRecipeCust.LoadinMultiplayerFirst = false; WMRecipeCust.Dbgl(" Delaying Server Reloading Until very end"); return; } if (WMRecipeCust.FirstSS) { WMRecipeCust.waitingforFirstLoad = true; } else { ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(WMRecipeCust.CurrentReload.LoadAllRecipeData(reload: true, slowmode: true)); } WMRecipeCust.WLog.LogDebug((object)"done with customSyncEvent"); } else { WMRecipeCust.WLog.LogWarning((object)("Synced String was blank " + value)); } } public void LoadZDOsForClones() { ZNetScene instance = ZNetScene.instance; if (!Object.op_Implicit((Object)(object)instance)) { return; } WMRecipeCust.WLog.LogInfo((object)"Setting Cloned ZDO Data"); try { foreach (KeyValuePair masterClone in WMRecipeCust.MasterCloneList) { string key = masterClone.Key; int stableHashCode = StringExtensionMethods.GetStableHashCode(key); if (instance.m_namedPrefabs.ContainsKey(stableHashCode)) { WMRecipeCust.WLog.LogWarning((object)("Prefab " + key + " already in ZNetScene")); } else { if ((Object)(object)masterClone.Value.GetComponent() != (Object)null) { instance.m_prefabs.Add(masterClone.Value); } else { instance.m_nonNetViewPrefabs.Add(masterClone.Value); } instance.m_namedPrefabs.Add(stableHashCode, masterClone.Value); WMRecipeCust.WLog.LogDebug((object)("Added prefab " + key)); } instance.m_namedPrefabs[stableHashCode].gameObject.SetActive(false); } } catch { WMRecipeCust.WLog.LogError((object)"Cloned ZDO failed badly "); WMRecipeCust.MasterCloneList.Clear(); } } public void AddClonedItemstoObjectDB() { ObjectDB instance = ObjectDB.instance; foreach (string item in WMRecipeCust.ClonedI) { if (WMRecipeCust.MasterCloneList.ContainsKey(item) && !instance.m_itemByHash.TryGetValue(StringExtensionMethods.GetStableHashCode(item), out var _)) { WMRecipeCust.Dbgl("Adding " + item + " to ObjectDB"); instance.m_items.Add(WMRecipeCust.MasterCloneList[item]); instance.m_itemByHash.Add(StringExtensionMethods.GetStableHashCode(item), WMRecipeCust.MasterCloneList[item]); WMRecipeCust.MasterCloneList[item].SetActive(true); } } foreach (string item2 in WMRecipeCust.MockI) { if (WMRecipeCust.MasterCloneList.ContainsKey(item2) && !instance.m_itemByHash.TryGetValue(StringExtensionMethods.GetStableHashCode(item2), out var _)) { WMRecipeCust.Dbgl("Adding " + item2 + " to ObjectDB"); instance.m_items.Add(WMRecipeCust.MasterCloneList[item2]); instance.m_itemByHash.Add(StringExtensionMethods.GetStableHashCode(item2), WMRecipeCust.MasterCloneList[item2]); WMRecipeCust.MasterCloneList[item2].SetActive(true); } } } public void LoadCacheStatus() { if (WMRecipeCust.AwakeHasRun && WMRecipeCust.Firstrun) { WMRecipeCust.CheckModFolder(); WMRecipeCust.GetAllMaterials(); } WMRecipeCust.WLog.LogInfo((object)"Setting Cache SEs"); ObjectDB instance = ObjectDB.instance; foreach (StatusData item in WMRecipeCust.cacheStatusYML) { try { SetData.SetStatusData(item, instance); } catch { WMRecipeCust.WLog.LogWarning((object)("SetEffect " + item.Name + " failed")); } } } public void LoadClonedCachedItems(bool WithZdo = false) { ObjectDB instance = ObjectDB.instance; UPdateItemHashesWacky(instance); foreach (WItemData item in WMRecipeCust.cacheItemsYML) { bool flag = false; foreach (string item2 in WMRecipeCust.ClonedI) { if (item2 == item.name) { flag = true; WMRecipeCust.WLog.LogInfo((object)("Another item named " + item.name + " has all ready loaded for mainmenu")); } } foreach (string item3 in WMRecipeCust.MockI) { if (item3 == item.name && (Object)(object)instance.GetItemPrefab(item.name) != (Object)null) { flag = true; WMRecipeCust.WLog.LogInfo((object)("Another Mock named " + item.name + " has all ready loaded for mainmenu")); } } if (flag) { continue; } try { GameObject val = SetData.SetClonedItemsDataCache(item, instance); if ((Object)(object)val != (Object)null) { if (WMRecipeCust.MasterCloneList.ContainsKey(item.name)) { WMRecipeCust.MasterCloneList[item.name] = val; } else { WMRecipeCust.MasterCloneList.Add(item.name, val); } } else { WMRecipeCust.WLog.LogInfo((object)("Wackydb cache item " + item.name + " was null, so removing from List")); WMRecipeCust.MockI.Remove(item.name); } } catch { WMRecipeCust.WLog.LogInfo((object)("Wackydb cache item " + item.name + " failed")); } if (item.customVisual != null) { try { VisualController.UpdatePrefab(item.name, item.customVisual); } catch { WMRecipeCust.WLog.LogWarning((object)("[WackysDatabase]: Failed to update visuals for " + item.name)); } } } UPdateItemHashesWacky(instance); } internal void UPdateItemHashesWacky(ObjectDB Instant, bool notclones = false) { GameObject val = null; try { Instant.m_itemByHash.Clear(); foreach (GameObject item in Instant.m_items) { val = item; Instant.m_itemByHash.Add(StringExtensionMethods.GetStableHashCode(((Object)item).name), item); } } catch { Instant.m_items.Remove(val); WMRecipeCust.WLog.LogWarning((object)("Wackydb " + ((Object)val).name + " failed hashes, Please fix yaml or Bug, removing from ObjectDB, rerunning")); UPdateItemHashesWacky(Instant); } } internal void removeLocalData() { if (ZNet.instance.IsServer() || !WMRecipeCust.extraSecurity.Value) { return; } WMRecipeCust.WLog.LogInfo((object)"Removing SinglePlayer Clones not in Multiplayer Server"); foreach (KeyValuePair masterClone in WMRecipeCust.MasterCloneList) { if (!WMRecipeCust.MultiplayerApproved.Contains(masterClone.Key)) { masterClone.Value.SetActive(false); ObjectDB instance = ObjectDB.instance; ZNetScene instance2 = ZNetScene.instance; instance.m_items.Remove(masterClone.Value); int stableHashCode = StringExtensionMethods.GetStableHashCode(masterClone.Key); instance2.m_prefabs.Remove(masterClone.Value); instance2.m_namedPrefabs.Remove(stableHashCode); } } } internal void SortPieceHammers() { WMRecipeCust.WLog.LogInfo((object)"Sorting Piece Categories"); Dictionary dictionary = new Dictionary(); HashSet hashSet = new HashSet(); foreach (PieceData item in WMRecipeCust.pieceDatasYml) { if (!string.IsNullOrEmpty(item.name) && !string.IsNullOrEmpty(item.categoryOrderBeforePrefab)) { dictionary[item.name] = item.categoryOrderBeforePrefab; if (!string.IsNullOrEmpty(item.piecehammer)) { hashSet.Add(item.piecehammer); } } } if (dictionary.Count == 0) { return; } ObjectDB instance = ObjectDB.instance; List list = new List(); foreach (string item2 in hashSet) { GameObject itemPrefab = instance.GetItemPrefab(item2); if ((Object)(object)itemPrefab != (Object)null) { list.Add(itemPrefab); } } string[] array = new string[3] { "Hammer", "Hoe", "Cultivator" }; foreach (string text in array) { if (!hashSet.Contains(text)) { GameObject itemPrefab2 = instance.GetItemPrefab(text); if ((Object)(object)itemPrefab2 != (Object)null) { list.Add(itemPrefab2); } } } foreach (GameObject item3 in list) { ItemDrop component = item3.GetComponent(); if ((Object)(object)component == (Object)null) { continue; } PieceTable buildPieces = component.m_itemData.m_shared.m_buildPieces; if (!((Object)(object)buildPieces == (Object)null)) { if (WMRecipeCust.isDebugString.Value) { WMRecipeCust.WLog.LogInfo((object)("Sorting " + ((Object)item3).name + " pieces")); } SortThis(buildPieces, dictionary); } } } private void SortThis(PieceTable pieceTable, Dictionary pieceOrder) { //IL_0031: 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_0040: 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_009a: 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) Dictionary> dictionary = new Dictionary>(); foreach (GameObject piece in pieceTable.m_pieces) { Piece component = piece.GetComponent(); if (!((Object)(object)component == (Object)null)) { if (!dictionary.ContainsKey(component.m_category)) { dictionary[component.m_category] = new List(); } dictionary[component.m_category].Add(piece); } } List list = new List(); foreach (PieceCategory key in dictionary.Keys) { List list2 = dictionary[key]; List list3 = new List(); List list4 = new List(); foreach (GameObject item in list2) { if (pieceOrder.ContainsKey(((Object)item).name) && !string.IsNullOrEmpty(pieceOrder[((Object)item).name])) { list3.Add(item); } else { list4.Add(item); } } if (list3.Count == 0) { list.AddRange(list2); continue; } List list5 = new List(list4); int num = 100; for (int i = 0; i < num; i++) { if (list3.Count <= 0) { break; } List list6 = new List(); bool flag = false; foreach (GameObject item2 in list3) { string targetName = pieceOrder[((Object)item2).name]; int num2 = list5.FindIndex((GameObject x) => ((Object)x).name == targetName); if (num2 != -1) { list5.Insert(num2, item2); flag = true; } else { list6.Add(item2); } } if (!flag) { foreach (GameObject item3 in list6) { list5.Add(item3); } list3.Clear(); break; } list3 = list6; } if (list3.Count > 0) { foreach (GameObject item4 in list3) { list5.Add(item4); } } list.AddRange(list5); } pieceTable.m_pieces = list; } [IteratorStateMachine(typeof(d__10))] internal IEnumerator LoadAllRecipeData(bool reload, bool slowmode = false, bool forcepush = false) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__10(0) { <>4__this = this, reload = reload, slowmode = slowmode, forcepush = forcepush }; } } [HarmonyPatch(typeof(Player), "OnSpawned")] internal static class OverrideItemMangerOrVanil { private static void Postfix() { PieceTable val = default(PieceTable); foreach (KeyValuePair item in SetData.DisabledPieceandHam) { if (item.Value.TryGetComponent(ref val)) { if (WMRecipeCust.isDebugString.Value) { WMRecipeCust.Dbgl($"Forcing PieceManger or Vanilla to Disable Piece {item.Key}"); } val.m_pieces.Remove(item.Key); } else if (item.Value.GetComponent().m_itemData.m_shared.m_buildPieces.m_pieces.Contains(item.Key)) { item.Value.GetComponent().m_itemData.m_shared.m_buildPieces.m_pieces.Remove(item.Key); } } } } public class WackyStatusEffectBonus { public float? AddHP; public float? AddStamina; public float? AddEitr; } [NullableContext(1)] [Nullable(0)] public class SetData { internal static Dictionary DisabledPieceandHam = new Dictionary(); internal static Renderer[] renderfinder; internal static Renderer[] renderfinder2; internal static void SetStatusData(StatusData data, ObjectDB Instant) { //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: 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_0201: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_0246: Unknown result type (might be due to invalid IL or missing references) //IL_023d: Unknown result type (might be due to invalid IL or missing references) //IL_024b: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) string name = data.Name; StatusEffect statusEffect = Instant.GetStatusEffect(StringExtensionMethods.GetStableHashCode(name)); if ((Object)(object)statusEffect == (Object)null) { statusEffect = ((data.ClonedSE != null) ? Instant.GetStatusEffect(StringExtensionMethods.GetStableHashCode(data.ClonedSE)) : Instant.GetStatusEffect(StringExtensionMethods.GetStableHashCode("SetEffect_TrollArmor"))); WMRecipeCust.ClonedE.Add(name); Transform transform = WMRecipeCust.Root.transform; StatusEffect val = Object.Instantiate(statusEffect, transform, false); ((Object)val).name = name; ObjectDB.instance.m_StatusEffects.Add(val); statusEffect = Instant.GetStatusEffect(StringExtensionMethods.GetStableHashCode(name)); } statusEffect.m_name = data.Status_m_name ?? statusEffect.m_name; statusEffect.m_category = data.Category ?? statusEffect.m_category; if (!DataHelpers.ECheck(data.CustomIcon)) { if (data.CustomIcon == "delete") { statusEffect.m_icon = null; WMRecipeCust.WLog.LogInfo((object)(statusEffect.m_name + " Icon Removed")); } else { string text = Path.Combine(WMRecipeCust.assetPathIcons, data.CustomIcon); if (File.ReadAllBytes(text) != null) { try { Sprite icon = SpriteTools.LoadNewSprite(text, 100f, (SpriteMeshType)1); statusEffect.m_icon = icon; } catch { WMRecipeCust.WLog.LogInfo((object)"customIcon failed"); } } else { WMRecipeCust.WLog.LogInfo((object)("No Img with the name " + data.CustomIcon + " in Icon Folder - ")); } } } statusEffect.m_flashIcon = data.FlashIcon ?? statusEffect.m_flashIcon; statusEffect.m_cooldownIcon = data.CooldownIcon ?? statusEffect.m_cooldownIcon; statusEffect.m_tooltip = data.Tooltip ?? statusEffect.m_tooltip; statusEffect.m_attributes = (StatusAttribute)(((??)data.Attributes) ?? statusEffect.m_attributes); statusEffect.m_startMessageType = (MessageType)(((??)data.StartMessageLoc) ?? statusEffect.m_startMessageType); statusEffect.m_startMessage = data.StartMessage ?? statusEffect.m_startMessage; statusEffect.m_stopMessageType = (MessageType)(((??)data.StopMessageLoc) ?? statusEffect.m_stopMessageType); statusEffect.m_stopMessage = data.StopMessage ?? statusEffect.m_stopMessage; statusEffect.m_repeatMessageType = (MessageType)(((??)data.RepeatMessageLoc) ?? statusEffect.m_repeatMessageType); statusEffect.m_repeatMessage = data.RepeatMessage ?? statusEffect.m_repeatMessage; statusEffect.m_ttl = data.TimeToLive ?? statusEffect.m_ttl; if (!string.IsNullOrEmpty(data.EndingStatusEffect)) { if (WMRecipeCust.EndingStatusEffect.TryGetValue(data.Name, out var _)) { WMRecipeCust.EndingStatusEffect[data.Name] = data.EndingStatusEffect; } else { WMRecipeCust.EndingStatusEffect.Add(data.Name, data.EndingStatusEffect); } } if (data.StartEffect_ != null) { statusEffect.m_startEffects = FindEffect(statusEffect.m_startEffects, data.StartEffect_); } if (data.StopEffect_ != null) { statusEffect.m_stopEffects = FindEffect(statusEffect.m_stopEffects, data.StopEffect_); } if (data.StartEffect_PLUS != null && data.StartEffect_PLUS.Length != 0) { statusEffect.m_startEffects = FindEffect(statusEffect.m_startEffects, data.StartEffect_PLUS); } if (data.StopEffect_PLUS != null && data.StopEffect_PLUS.Length != 0) { statusEffect.m_stopEffects = FindEffect(statusEffect.m_stopEffects, data.StopEffect_PLUS); } statusEffect.m_cooldown = data.Cooldown ?? statusEffect.m_cooldown; statusEffect.m_activationAnimation = data.ActivationAnimation ?? statusEffect.m_activationAnimation; if (data.AddHP.HasValue || data.AddStamina.HasValue || data.AddEitr.HasValue) { string name2 = data.Name; if (!WMRecipeCust.SEaddBonus.TryGetValue(name2, out var value2) || value2 == null) { value2 = new WackyStatusEffectBonus(); WMRecipeCust.SEaddBonus[name2] = value2; } if (data.AddHP.HasValue) { value2.AddHP = data.AddHP.Value; } if (data.AddStamina.HasValue) { value2.AddStamina = data.AddStamina.Value; } if (data.AddEitr.HasValue) { value2.AddEitr = data.AddEitr.Value; } StatusEffect val2 = statusEffect; val2.m_tooltip = val2.m_tooltip + "\n" + (data.AddHP.HasValue ? ("$item_food_health: " + ColorizeSigned(data.AddHP.Value)) : "") + (data.AddStamina.HasValue ? ("\n$item_food_stamina: " + ColorizeSigned(data.AddStamina.Value) + " ") : "") + (data.AddEitr.HasValue ? ("\n$item_food_eitr: " + ColorizeSigned(data.AddEitr.Value)) : ""); } if (data.SeData != null) { Type type = ((object)statusEffect).GetType(); Functions.setValue(type, statusEffect, "m_tickInterval", data.SeData.m_tickInterval); Functions.setValue(type, statusEffect, "m_healthPerTickMinHealthPercentage", data.SeData.m_healthPerTickMinHealthPercentage); Functions.setValue(type, statusEffect, "m_healthPerTick", data.SeData.m_healthPerTick); Functions.setValue(type, statusEffect, "m_healthUpFront", data.SeData.m_heatlhUpFront); Functions.setValue(type, statusEffect, "m_healthOverTime", data.SeData.m_healthOverTime); Functions.setValue(type, statusEffect, "m_healthOverTimeDuration", data.SeData.m_healthOverTimeDuration); Functions.setValue(type, statusEffect, "m_healthOverTimeInterval", data.SeData.m_healthOverTimeInterval); Functions.setValue(type, statusEffect, "m_staminaUpFront", data.SeData.m_staminaUpFront); Functions.setValue(type, statusEffect, "m_staminaOverTime", data.SeData.m_staminaOverTime); Functions.setValue(type, statusEffect, "m_staminaOverTimeDuration", data.SeData.m_staminaOverTimeDuration); Functions.setValue(type, statusEffect, "m_staminaDrainPerSec", data.SeData.m_staminaDrainPerSec); Functions.setValue(type, statusEffect, "m_runStaminaDrainModifier", data.SeData.m_runStaminaDrainModifier); Functions.setValue(type, statusEffect, "m_jumpStaminaUseModifier", data.SeData.m_jumpStaminaUseModifier); Functions.setValue(type, statusEffect, "m_attackStaminaUseModifier", data.SeData.m_attackStaminaUseModifier); Functions.setValue(type, statusEffect, "m_blockStaminaUseModifier", data.SeData.m_blockStaminaUseModifier); Functions.setValue(type, statusEffect, "m_dodgeStaminaUseModifier", data.SeData.m_dodgeStaminaUseModifier); Functions.setValue(type, statusEffect, "m_swimStaminaUseModifier", data.SeData.m_swimStaminaUseModifier); Functions.setValue(type, statusEffect, "m_homeItemStaminaUseModifier", data.SeData.m_homeItemStaminaUseModifier); Functions.setValue(type, statusEffect, "m_sneakStaminaUseModifier", data.SeData.m_sneakStaminaUseModifier); Functions.setValue(type, statusEffect, "m_runStaminaUseModifier", data.SeData.m_runStaminaUseModifier); Functions.setValue(type, statusEffect, "m_blockStaminaUseFlatValue", data.SeData.m_blockStaminaUseFlatValue); Functions.setValue(type, statusEffect, "m_adrenalineUpFront", data.SeData.m_adrenalineUpFront); Functions.setValue(type, statusEffect, "m_adrenalineModifier", data.SeData.m_adrenalineModifier); Functions.setValue(type, statusEffect, "m_staggerModifier", data.SeData.m_staggerModifier); Functions.setValue(type, statusEffect, "m_timedBlockBonus", data.SeData.m_staggerTimeBlockBonus); Functions.setValue(type, statusEffect, "m_eitrUpFront", data.SeData.m_eitrUpFront); Functions.setValue(type, statusEffect, "m_eitrOverTime", data.SeData.m_eitrOverTime); Functions.setValue(type, statusEffect, "m_eitrOverTimeDuration", data.SeData.m_eitrOverTimeDuration); Functions.setValue(type, statusEffect, "m_healthRegenMultiplier", data.SeData.m_healthRegenMultiplier); Functions.setValue(type, statusEffect, "m_staminaRegenMultiplier", data.SeData.m_staminaRegenMultiplier); Functions.setValue(type, statusEffect, "m_eitrRegenMultiplier", data.SeData.m_eitrRegenMultiplier); Functions.setValue(type, statusEffect, "m_addArmor", data.SeData.m_armorAdd); Functions.setValue(type, statusEffect, "m_armorMultiplier", data.SeData.m_armorMultiplier); Functions.setValue(type, statusEffect, "m_raiseSkill", null, null, null, null, data.SeData.m_raiseSkill); Functions.setValue(type, statusEffect, "m_raiseSkillModifier", data.SeData.m_raiseSkillModifier); Functions.setValue(type, statusEffect, "m_skillLevel", null, null, null, null, data.SeData.m_skillLevel); Functions.setValue(type, statusEffect, "m_skillLevelModifier", data.SeData.m_skillLevelModifier); Functions.setValue(type, statusEffect, "m_skillLevel2", null, null, null, null, data.SeData.m_skillLevel2); Functions.setValue(type, statusEffect, "m_skillLevelModifier2", data.SeData.m_skillLevelModifier2); Functions.setValue(type, statusEffect, "m_mods", null, null, null, data.SeData.m_mods); Functions.setValue(type, statusEffect, "m_modifyAttackSkill", null, null, null, null, data.SeData.m_modifyAttackSkill); Functions.setValue(type, statusEffect, "m_damageModifier", data.SeData.m_damageModifier); Functions.setValue(type, statusEffect, "m_noiseModifier", data.SeData.m_noiseModifier); Functions.setValue(type, statusEffect, "m_stealthModifier", data.SeData.m_stealthModifier); Functions.setValue(type, statusEffect, "m_addMaxCarryWeight", data.SeData.m_addMaxCarryWeight); Functions.setValue(type, statusEffect, "m_speedModifier", data.SeData.m_speedModifier); Functions.setValue(type, statusEffect, "m_jumpModifier", null, null, null, null, null, data.SeData.m_jumpModifier); Functions.setValue(type, statusEffect, "m_maxMaxFallSpeed", data.SeData.m_maxMaxFallSpeed); Functions.setValue(type, statusEffect, "m_fallDamageModifier", data.SeData.m_fallDamageModifier); Functions.setValue(type, statusEffect, "m_tickTimer", data.SeData.m_tickTimer); Functions.setValue(type, statusEffect, "m_healthOverTimeTimer", data.SeData.m_healthOverTimeTimer); Functions.setValue(type, statusEffect, "m_healthOverTimeTicks", data.SeData.m_healthOverTimeTicks); Functions.setValue(type, statusEffect, "m_healthOverTimeTickHP", data.SeData.m_healthOverTimeTickHP); Functions.setValue(type, statusEffect, "m_windMovementModifier", data.SeData.m_windMovementModifier); if (data.SeShield != null) { Functions.setValue(type, statusEffect, "m_absorbDamage", data.SeShield.AbsorbDmg); Functions.setValue(type, statusEffect, "m_absorbDamageWorldLevel", data.SeShield.AbsorbDmgWorldLevel); Functions.setValue(type, statusEffect, "m_levelUpSkillFactor", data.SeShield.LevelUpSkillFactor); Functions.setValue(type, statusEffect, "m_ttlPerItemLevel", null, data.SeShield.TtlPerItemLevel); Functions.setValue(type, statusEffect, "m_absorbDamagePerSkillLevel", data.SeShield.AbsorbDmgPerSkill); } if (data.SePoison != null) { Functions.setValue(type, statusEffect, "m_damageInterval", data.SePoison.m_damageInterval); Functions.setValue(type, statusEffect, "m_baseTTL", data.SePoison.m_baseTTL); Functions.setValue(type, statusEffect, "m_TTLPerDamagePlayer", data.SePoison.m_TTLPerDamagePlayer); Functions.setValue(type, statusEffect, "m_TTLPerDamage", data.SePoison.m_TTLPerDamage); Functions.setValue(type, statusEffect, "m_TTLPower", data.SePoison.m_TTLPower); } if (data.SeFrost != null) { Functions.setValue(type, statusEffect, "m_freezeTimeEnemy", data.SeFrost.m_freezeTimeEnemy); Functions.setValue(type, statusEffect, "m_freezeTimePlayer", data.SeFrost.m_freezeTimePlayer); Functions.setValue(type, statusEffect, "m_minSpeedFactor", data.SeFrost.m_minSpeedFactor); } if (data.SeData.m_percentDamageModifiers.HasValue) { Functions.setValue(type, statusEffect, "m_percentigeDamageModifiers", null, null, null, null, null, null, data.SeData.m_percentDamageModifiers); } } static string ColorizeSigned(float v) { string text2 = v.ToString("+0.##;-0.##;0"); string text3 = ((v < 0f) ? "red" : "orange"); return "" + text2 + ""; } } internal static void SetRecipeData(RecipeData data, ObjectDB Instant) { //IL_0514: Unknown result type (might be due to invalid IL or missing references) //IL_0519: Unknown result type (might be due to invalid IL or missing references) //IL_052c: Unknown result type (might be due to invalid IL or missing references) //IL_0534: Unknown result type (might be due to invalid IL or missing references) //IL_053d: Expected O, but got Unknown //IL_04c7: Unknown result type (might be due to invalid IL or missing references) //IL_04cc: Unknown result type (might be due to invalid IL or missing references) //IL_04df: Unknown result type (might be due to invalid IL or missing references) //IL_04e7: Unknown result type (might be due to invalid IL or missing references) //IL_04f0: Expected O, but got Unknown //IL_0831: Unknown result type (might be due to invalid IL or missing references) //IL_0836: Unknown result type (might be due to invalid IL or missing references) //IL_083e: Unknown result type (might be due to invalid IL or missing references) //IL_0846: Unknown result type (might be due to invalid IL or missing references) //IL_0859: Unknown result type (might be due to invalid IL or missing references) //IL_0863: Expected O, but got Unknown bool flag = false; foreach (string item3 in WMRecipeCust.ClonedR) { if (item3 == data.name) { flag = true; } } string name = data.name; string text = data.name; if (!string.IsNullOrEmpty(data.clonePrefabName)) { if (data.clonePrefabName == "NO") { data.clonePrefabName = null; } else { text = data.clonePrefabName; } } GameObject val = DataHelpers.CheckforSpecialObjects(text); if ((Object)(object)val == (Object)null) { val = Instant.GetItemPrefab(text); } Recipe val2 = null; if ((Object)(object)val == (Object)null) { foreach (Recipe recipe in Instant.m_recipes) { if (((Object)recipe).name == text) { WMRecipeCust.Dbgl("An actual " + data.name + " has been found!-- Only modification allowed"); val2 = recipe; break; } } } if ((Object)(object)val == (Object)null && (Object)(object)val2 == (Object)null) { WMRecipeCust.WLog.LogWarning((object)(" null " + text)); return; } if ((Object)(object)val != (Object)null && (Object)(object)val.GetComponent() == (Object)null) { WMRecipeCust.WLog.LogWarning((object)("Recipe data for " + text + " not found!")); return; } Recipe val3 = null; if (!string.IsNullOrEmpty(data.clonePrefabName) && !flag) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Setting Cloned Recipe for " + name); } val3 = ScriptableObject.CreateInstance(); WMRecipeCust.ClonedR.Add(name); } else if (flag) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("ReSetting Cloned Recipe for " + name); } for (int num = Instant.m_recipes.Count - 1; num >= 0; num--) { if (((Object)Instant.m_recipes[num]).name == name) { val3 = Instant.m_recipes[num]; val3.m_enabled = true; break; } } } else if ((Object)(object)val2 != (Object)null) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("An actual Recipe for " + text); } val3 = val2; val3.m_enabled = true; } else { for (int num2 = Instant.m_recipes.Count - 1; num2 >= 0; num2--) { if (Instant.m_recipes[num2].m_item?.m_itemData.m_shared.m_name == val.GetComponent().m_itemData.m_shared.m_name) { val3 = Instant.m_recipes[num2]; val3.m_enabled = true; WMRecipeCust.Dbgl("Setting Recipe for " + name + " with recipe name " + ((Object)Instant.m_recipes[num2]).name); break; } } } if ((Object)(object)val3 == (Object)null) { WMRecipeCust.Dbgl("Recipe failed inside of " + name); return; } if ((Object)(object)val2 == (Object)null) { val3.m_item = val.GetComponent(); } if (data.craftingStation != null) { val3.m_craftingStation = DataHelpers.GetCraftingStation(data.craftingStation); } if (data.repairStation != null) { val3.m_repairStation = DataHelpers.GetCraftingStation(data.repairStation); } val3.m_minStationLevel = data.minStationLevel ?? val3.m_minStationLevel; val3.m_amount = data.amount ?? val3.m_amount; ((Object)val3).name = name; if (data.maxStationLevelCap.HasValue) { if (!WMRecipeCust.RecipeMaxStationLvl.ContainsKey(((Object)val3.m_item).name)) { WMRecipeCust.RecipeMaxStationLvl.Add(((Object)val3.m_item).name, data.maxStationLevelCap.GetValueOrDefault(-1)); } else { WMRecipeCust.RecipeMaxStationLvl[((Object)val3.m_item).name] = data.maxStationLevelCap.GetValueOrDefault(-1); } } RecipeData recipeData; bool valueOrDefault; if (data.upgrade_reqs != null && data.upgrade_reqs.Any()) { List list = new List(); foreach (string upgrade_req in data.upgrade_reqs) { if (string.IsNullOrEmpty(upgrade_req)) { continue; } string[] array = upgrade_req.Split(new char[1] { ':' }); string text2 = array[0]; if (Object.op_Implicit((Object)(object)Instant.GetItemPrefab(text2))) { int amountPerLevel = ((array.Length < 2) ? 1 : int.Parse(array[1])); int num3 = ((array.Length < 3) ? 1 : int.Parse(array[2])); if (num3 > 1) { Requirement val4 = new Requirement { m_resItem = Instant.GetItemPrefab(text2).GetComponent(), m_amountPerLevel = amountPerLevel, m_amount = 0 }; WMRecipeCust.requirementQuality.Add(val4, new RequirementQuality { quality = num3 }); list.Add(val4); } else { Requirement item = new Requirement { m_resItem = Instant.GetItemPrefab(text2).GetComponent(), m_amountPerLevel = amountPerLevel, m_amount = 0 }; list.Add(item); } } else { WMRecipeCust.WLog.LogWarning((object)("Could not find " + text2 + " for upgrade_reqs in Recipe " + ((Object)val3).name)); } } Recipe val5 = null; string text3 = ((Object)val3).name + "_Upgrade"; foreach (Recipe recipe2 in Instant.m_recipes) { if (((Object)recipe2).name == text3) { val5 = recipe2; break; } } if ((Object)(object)val5 == (Object)null) { val5 = Object.Instantiate(val3); ((Object)val5).name = ((Object)val3).name + "_Upgrade"; val5.m_resources = list.ToArray(); val5.m_enabled = false; Instant.m_recipes.Add(val5); WMRecipeCust.RequiredUpgradeItemsString.Add(val5, value: true); } else { val5.m_resources = list.ToArray(); val5.m_enabled = true; WMRecipeCust.RequiredUpgradeItemsString[val5] = true; } if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" Setting Recipe_Upgrade"); } recipeData = data; valueOrDefault = recipeData.disabledUpgrade.GetValueOrDefault(); bool num4; if (!recipeData.disabledUpgrade.HasValue) { valueOrDefault = false; recipeData.disabledUpgrade = valueOrDefault; num4 = valueOrDefault; } else { num4 = valueOrDefault; } if (num4) { WMRecipeCust.RequiredUpgradeItemsString[val5] = false; if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" Disabling Recipe_Upgrade"); } } if (WMRecipeCust.RequiredCraftItemsString.ContainsKey(val3)) { WMRecipeCust.RequiredCraftItemsString[val3] = true; } else { WMRecipeCust.RequiredCraftItemsString.Add(val3, value: true); } } recipeData = data; valueOrDefault = recipeData.disabledUpgrade.GetValueOrDefault(); bool num5; if (!recipeData.disabledUpgrade.HasValue) { valueOrDefault = false; recipeData.disabledUpgrade = valueOrDefault; num5 = valueOrDefault; } else { num5 = valueOrDefault; } if (num5) { val3.m_item.m_itemData.m_shared.m_maxQuality = 1; WMRecipeCust.Dbgl(" Forcing NO upgrade possible for Item, disabledUpgrade and upgrade_reqs == null"); } List list2 = new List(); val3.m_requireOnlyOneIngredient = data.requireOnlyOneIngredient ?? val3.m_requireOnlyOneIngredient; foreach (string req in data.reqs) { if (string.IsNullOrEmpty(req)) { continue; } string[] array2 = req.Split(new char[1] { ':' }); string text4 = array2[0]; if (Object.op_Implicit((Object)(object)Instant.GetItemPrefab(text4))) { int amount = ((array2.Length < 2) ? 1 : int.Parse(array2[1])); int amountPerLevel2 = ((array2.Length < 3) ? 1 : int.Parse(array2[2])); bool recover = array2.Length != 4 || bool.Parse(array2[3].ToLower()); if (array2.Length >= 5) { int.Parse(array2[4]); } Requirement item2 = new Requirement { m_amount = amount, m_recover = recover, m_resItem = Instant.GetItemPrefab(text4).GetComponent(), m_amountPerLevel = amountPerLevel2 }; list2.Add(item2); } else { WMRecipeCust.WLog.LogWarning((object)("Could not find " + text4 + " for req in Recipe " + ((Object)val3).name)); } } int index = 0; val3.m_resources = list2.ToArray(); if (!string.IsNullOrEmpty(data.clonePrefabName) && !flag) { for (int num6 = Instant.m_recipes.Count - 1; num6 >= 0; num6--) { if (Instant.m_recipes[num6].m_item?.m_itemData.m_shared.m_name == val.GetComponent().m_itemData.m_shared.m_name) { index = num6++; break; } } Instant.m_recipes.Insert(index, val3); } if ((!data.disabled).GetValueOrDefault(true)) { return; } if (WMRecipeCust.RequiredCraftItemsString.ContainsKey(val3)) { WMRecipeCust.RequiredCraftItemsString.Remove(val3); } if (flag) { val3.m_enabled = false; if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Cloned Recipe has been disabled for " + name); } } else if (!flag && !string.IsNullOrEmpty(data.clonePrefabName)) { val3.m_enabled = false; if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Cloned Recipe is disabled for " + name); } } else if ((Object)(object)val2 != (Object)null) { val2.m_enabled = false; if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Actual Recipe is disabled for " + ((Object)val2).name); } } else { val3.m_enabled = false; if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Recipe is disabled for " + ((Object)val3).name); } } } internal static void SetPieceRecipeData(PieceData data, ObjectDB Instant, GameObject[] AllObjects = null, bool cloneonly = false) { //IL_0a6b: Unknown result type (might be due to invalid IL or missing references) //IL_0a70: Unknown result type (might be due to invalid IL or missing references) //IL_0acc: Unknown result type (might be due to invalid IL or missing references) //IL_0adc: Unknown result type (might be due to invalid IL or missing references) //IL_1211: Unknown result type (might be due to invalid IL or missing references) //IL_1216: Unknown result type (might be due to invalid IL or missing references) //IL_122b: Unknown result type (might be due to invalid IL or missing references) //IL_123a: Unknown result type (might be due to invalid IL or missing references) //IL_1249: Unknown result type (might be due to invalid IL or missing references) //IL_1267: Expected O, but got Unknown //IL_0cbc: Unknown result type (might be due to invalid IL or missing references) //IL_0412: Unknown result type (might be due to invalid IL or missing references) //IL_0417: Unknown result type (might be due to invalid IL or missing references) //IL_04a0: Unknown result type (might be due to invalid IL or missing references) //IL_141e: Unknown result type (might be due to invalid IL or missing references) //IL_13f0: Unknown result type (might be due to invalid IL or missing references) //IL_13c0: Unknown result type (might be due to invalid IL or missing references) //IL_1624: Unknown result type (might be due to invalid IL or missing references) //IL_161b: Unknown result type (might be due to invalid IL or missing references) //IL_16e7: Unknown result type (might be due to invalid IL or missing references) //IL_16ec: Unknown result type (might be due to invalid IL or missing references) //IL_1629: Unknown result type (might be due to invalid IL or missing references) //IL_17e1: Unknown result type (might be due to invalid IL or missing references) //IL_17d8: Unknown result type (might be due to invalid IL or missing references) //IL_24b7: Unknown result type (might be due to invalid IL or missing references) //IL_24ae: Unknown result type (might be due to invalid IL or missing references) //IL_17e6: Unknown result type (might be due to invalid IL or missing references) //IL_24bc: Unknown result type (might be due to invalid IL or missing references) //IL_27ad: Unknown result type (might be due to invalid IL or missing references) //IL_27b4: Expected O, but got Unknown //IL_2360: Unknown result type (might be due to invalid IL or missing references) //IL_2367: Expected O, but got Unknown //IL_2858: Unknown result type (might be due to invalid IL or missing references) //IL_285f: Expected O, but got Unknown //IL_3314: Unknown result type (might be due to invalid IL or missing references) //IL_331b: Expected O, but got Unknown //IL_30a5: Unknown result type (might be due to invalid IL or missing references) //IL_309c: Unknown result type (might be due to invalid IL or missing references) //IL_30aa: Unknown result type (might be due to invalid IL or missing references) //IL_36d8: Unknown result type (might be due to invalid IL or missing references) //IL_36df: Expected O, but got Unknown bool flag = false; foreach (string item2 in WMRecipeCust.ClonedP) { if (item2 == data.name) { flag = true; } } string name = data.name; if (!string.IsNullOrEmpty(data.clonePrefabName) && !flag) { data.name = data.clonePrefabName; } GameObject val = DataHelpers.CheckforSpecialObjects(data.name); if ((Object)(object)val == (Object)null) { val = DataHelpers.GetPieces(Instant).Find((GameObject g) => Utils.GetPrefabName(g) == data.name); if ((Object)(object)val == (Object)null) { val = DataHelpers.GetModdedPieces(data.name); if ((Object)(object)val == (Object)null) { GameObject[] array = AllObjects; foreach (GameObject val2 in array) { if ((Object)(object)val2.GetComponent() != (Object)null && ((Object)val2).name == data.name) { val = val2; break; } } if ((Object)(object)val == (Object)null) { WMRecipeCust.WLog.LogWarning((object)("Piece " + data.name + " not found! 4 layer search")); return; } } else { WMRecipeCust.Dbgl($"Piece {data.name} from known hammer {WMRecipeCust.selectedPiecehammer}"); } } } if ((Object)(object)val.GetComponent() == (Object)null) { WMRecipeCust.Dbgl("Piece data not found!"); } else { if (DisabledPieceandHam.ContainsKey(val) && (data.disabled.GetValueOrDefault() || (data.adminonly.GetValueOrDefault() && !WMRecipeCust.Admin))) { return; } if (!string.IsNullOrEmpty(data.clonePrefabName) && !flag) { if (WMRecipeCust.BlacklistClone.Contains(data.clonePrefabName)) { WMRecipeCust.Dbgl("Can not clone " + data.clonePrefabName + " "); return; } if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Piece being set " + name + " is CLONE of " + data.clonePrefabName); } Transform transform = WMRecipeCust.Root.transform; GameObject val3 = Object.Instantiate(val, transform, false); Piece component = val3.GetComponent(); WMRecipeCust.ClonedP.Add(name); ((Object)val3).name = name; ((Object)component).name = name; data.name = name; if (!WMRecipeCust.ClonedPrefabsMap.ContainsKey(name)) { WMRecipeCust.ClonedPrefabsMap.Add(name, data.clonePrefabName); } int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)val3).name); ZNetScene instance = ZNetScene.instance; if (Object.op_Implicit((Object)(object)instance)) { string name2 = ((Object)val3).name; if (instance.m_namedPrefabs.ContainsKey(stableHashCode)) { WMRecipeCust.Dbgl("Prefab " + name2 + " already in ZNetScene"); } else { if ((Object)(object)val3.GetComponent() != (Object)null) { instance.m_prefabs.Add(val3); } else { instance.m_nonNetViewPrefabs.Add(val3); } instance.m_namedPrefabs.Add(stableHashCode, val3); if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Added prefab " + name2); } } } if (data.craftingStation != null) { CraftingStation craftingStation = DataHelpers.GetCraftingStation(data.craftingStation); val3.GetComponent().m_craftingStation = craftingStation; } GameObject itemPrefab = Instant.GetItemPrefab(data.piecehammer); flag = true; if ((Object)(object)itemPrefab == (Object)null) { if (data.piecehammer == "Hoe" || data.piecehammer == "_CultivatorPieceTable") { if (!string.IsNullOrEmpty(data.piecehammerCategory)) { try { component.m_category = (PieceCategory)Enum.Parse(typeof(PieceCategory), data.piecehammerCategory); } catch { WMRecipeCust.Dbgl("piecehammerCategory named " + data.piecehammerCategory + " did not set correctly "); } } WMRecipeCust.selectedPiecehammer.m_pieces.Add(val3); } else if ((Object)(object)WMRecipeCust.selectedPiecehammer == (Object)null) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("piecehammer named " + data.piecehammer + " will not be used because the Item prefab was not found and it is not a PieceTable, so setting the piece to Hammer in Misc"); } itemPrefab = Instant.GetItemPrefab("Hammer"); component.m_category = (PieceCategory)0; itemPrefab.GetComponent().m_itemData.m_shared.m_buildPieces.m_pieces.Add(val3); } else { if (!string.IsNullOrEmpty(data.piecehammerCategory)) { try { BuildPiece.BuildTableConfigChangedWacky(component, data.piecehammerCategory); } catch { WMRecipeCust.Dbgl("piecehammerCategory named " + data.piecehammerCategory + " did not set correctly "); } } WMRecipeCust.selectedPiecehammer.m_pieces.Add(val3); } } else { if (!string.IsNullOrEmpty(data.piecehammerCategory)) { try { BuildPiece.BuildTableConfigChangedWacky(component, data.piecehammerCategory); } catch { WMRecipeCust.Dbgl("piecehammerCategory named " + data.piecehammerCategory + " did not set correctly "); } } if (itemPrefab != null) { itemPrefab.GetComponent().m_itemData.m_shared.m_buildPieces.m_pieces.Add(val3); } } val = DataHelpers.FindPieceObjectName(data.name); if ((Object)(object)val == (Object)null) { WMRecipeCust.Dbgl("Item " + data.name + " not found in SetPiece! after clone"); return; } if ((Object)(object)val.GetComponent() == (Object)null) { WMRecipeCust.Dbgl("Item data for " + data.name + " not found! after clone"); return; } val.GetComponent().m_name = name; } if (!string.IsNullOrEmpty(data.material) || !string.IsNullOrEmpty(data.damagedMaterial)) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Material name searching for " + data.material + " for piece " + data.name); } try { Renderer[] componentsInChildren = val.GetComponentsInChildren(); Renderer[] componentsInChildren2 = val.GetComponentsInChildren(true); if (!string.IsNullOrEmpty(data.material) && (data.material.Contains("same_mat") || data.material.Contains("no_wear"))) { WMRecipeCust.Dbgl("No Wear set for " + data.name); Material val4 = null; Renderer[] array2 = componentsInChildren; foreach (Renderer val5 in array2) { if (val5.receiveShadows) { val4 = val5.sharedMaterial; break; } } if ((Object)(object)val4 != (Object)null) { array2 = componentsInChildren2; foreach (Renderer val6 in array2) { if (val6.receiveShadows) { PrefabAssistant.UpdateMaterialReference(val6, val4); } } } } else if (!string.IsNullOrEmpty(data.material)) { Material value3; if (Enumerable.Contains(data.material, ',')) { string[] array3 = data.material.Split(new char[1] { ',' }); WMRecipeCust.originalMaterials.TryGetValue(array3[0], out var value); WMRecipeCust.originalMaterials.TryGetValue(array3[1], out var value2); Renderer[] array2 = componentsInChildren2; foreach (Renderer val7 in array2) { if (val7.receiveShadows) { if ((Object)(object)value != (Object)null && array3[0] != "none") { PrefabAssistant.UpdateMaterialReference(val7, value); } } else if ((Object)(object)value2 != (Object)null) { PrefabAssistant.UpdateMaterialReference(val7, value2); } } } else if (WMRecipeCust.originalMaterials.TryGetValue(data.material, out value3)) { Renderer[] array2 = componentsInChildren2; foreach (Renderer val8 in array2) { if (val8.receiveShadows) { PrefabAssistant.UpdateMaterialReference(val8, value3); } } } else { WMRecipeCust.WLog.LogWarning((object)(data.material + " was not found")); } } } catch (Exception ex) { WMRecipeCust.WLog.LogWarning((object)("Material was not found or was not set correctly: " + ex.Message)); } } bool flag2 = false; if (!DataHelpers.ECheck(data.customIcon)) { string text = Path.Combine(WMRecipeCust.assetPathIcons, data.customIcon); if (File.Exists(text)) { if (File.ReadAllBytes(text) != null) { try { Sprite icon = SpriteTools.LoadNewSprite(text, 100f, (SpriteMeshType)1); val.GetComponent().m_icon = icon; flag2 = true; } catch { WMRecipeCust.WLog.LogInfo((object)"customIcon failed"); } } else { WMRecipeCust.WLog.LogInfo((object)("No Img with the name " + data.customIcon + " in Icon Folder - ")); } } else { WMRecipeCust.WLog.LogInfo((object)("No Img with the name " + data.customIcon + " in Icon Folder - ")); } } if (!DataHelpers.ECheck(data.material) && !flag2) { try { WMRecipeCust.SnapshotPiecestoDo.Add(val); } catch { WMRecipeCust.WLog.LogInfo((object)"Piece snapshot failed"); } } if (data.craftingStation != null) { CraftingStation craftingStation2 = DataHelpers.GetCraftingStation(data.craftingStation); val.GetComponent().m_craftingStation = craftingStation2; } if (!flag) { Piece component2 = val.GetComponent(); GameObject itemPrefab2 = Instant.GetItemPrefab(data.piecehammer); if (data.piecehammerCategory != null && data.piecehammer != null) { if (data.piecehammer == "Hoe" || data.piecehammer == "_CultivatorPieceTable") { if (!string.IsNullOrEmpty(data.piecehammerCategory)) { try { component2.m_category = (PieceCategory)Enum.Parse(typeof(PieceCategory), data.piecehammerCategory); } catch { WMRecipeCust.Dbgl("piecehammerCategory named " + data.piecehammerCategory + " did not set correctly"); } } if (itemPrefab2 != null) { itemPrefab2.GetComponent().m_itemData.m_shared.m_buildPieces.m_pieces.Add(val); } } else { bool flag3 = false; if (component2.m_category != PiecePrefabManager.GetCategory(data.piecehammerCategory)) { flag3 = true; } if (!flag3) { if ((Object)(object)itemPrefab2 != (Object)null) { PieceTable val9 = itemPrefab2.GetComponent()?.m_itemData.m_shared.m_buildPieces; if ((Object)(object)val9 != (Object)null && !val9.m_pieces.Contains(val)) { flag3 = true; } } else if ((Object)(object)WMRecipeCust.selectedPiecehammer != (Object)null && !WMRecipeCust.selectedPiecehammer.m_pieces.Contains(val)) { flag3 = true; } } if (flag3) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Category or Hammer change detected for " + data.name + ". Disabling old piece and setting new piece location."); } if (WMRecipeCust.MaybePieceStations != null) { PieceTable[] maybePieceStations = WMRecipeCust.MaybePieceStations; foreach (PieceTable val10 in maybePieceStations) { if ((Object)(object)val10 != (Object)null && val10.m_pieces.Contains(val)) { val10.m_pieces.Remove(val); } } } if ((Object)(object)WMRecipeCust.selectedPiecehammer != (Object)null && WMRecipeCust.selectedPiecehammer.m_pieces.Contains(val)) { WMRecipeCust.selectedPiecehammer.m_pieces.Remove(val); } GameObject itemPrefab3 = ObjectDB.instance.GetItemPrefab("Hammer"); if ((Object)(object)itemPrefab3 != (Object)null) { PieceTable val11 = itemPrefab3.GetComponent()?.m_itemData.m_shared.m_buildPieces; if ((Object)(object)val11 != (Object)null && val11.m_pieces.Contains(val)) { val11.m_pieces.Remove(val); } } if ((Object)(object)itemPrefab2 == (Object)null) { if ((Object)(object)WMRecipeCust.selectedPiecehammer == (Object)null) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("piecehammer named " + data.piecehammer + " not found. Defaulting to Hammer in Misc category."); } itemPrefab2 = Instant.GetItemPrefab("Hammer"); component2.m_category = (PieceCategory)0; itemPrefab2.GetComponent().m_itemData.m_shared.m_buildPieces.m_pieces.Add(val); } else { if (!string.IsNullOrEmpty(data.piecehammerCategory)) { try { BuildPiece.BuildTableConfigChangedWacky(component2, data.piecehammerCategory); } catch { WMRecipeCust.Dbgl("piecehammerCategory named " + data.piecehammerCategory + " did not set correctly"); } } WMRecipeCust.selectedPiecehammer.m_pieces.Add(val); } } else { if (!string.IsNullOrEmpty(data.piecehammerCategory)) { try { BuildPiece.BuildTableConfigChangedWacky(component2, data.piecehammerCategory); } catch { WMRecipeCust.Dbgl("piecehammerCategory named " + data.piecehammerCategory + " did not set correctly"); } } if (itemPrefab2 != null) { itemPrefab2.GetComponent().m_itemData.m_shared.m_buildPieces.m_pieces.Add(val); } } } } } } if (data.adminonly.GetValueOrDefault()) { if (WMRecipeCust.Admin) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(data.name + " is set for Adminonly, and you are admin, enjoy this exclusive Piece"); } } else { data.disabled = true; if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(data.name + " is set for Adminonly, you are not an admin"); } } } if (data.disabled.GetValueOrDefault()) { if (WMRecipeCust.IsDedServer) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Disabling the Piece " + data.name + " for users, not dedicated server"); } } else { GameObject val12 = Instant.GetItemPrefab(data.piecehammer); if ((Object)(object)val12 == (Object)null) { val12 = ((Component)WMRecipeCust.selectedPiecehammer).gameObject; } if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl($"Disabling Piece {data.name} with hammer {val12}"); } PieceTable val13 = default(PieceTable); if (val12.TryGetComponent(ref val13)) { val13.m_pieces.Remove(val); if (!DisabledPieceandHam.ContainsKey(val)) { DisabledPieceandHam.Add(val, val12); } } else if (val12.GetComponent().m_itemData.m_shared.m_buildPieces.m_pieces.Contains(val)) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("removing from " + ((Object)val12).name + " Piece " + data.name); } val12.GetComponent().m_itemData.m_shared.m_buildPieces.m_pieces.Remove(val); if (!DisabledPieceandHam.ContainsKey(val)) { DisabledPieceandHam.Add(val, val12); } } } } else { GameObject val14 = Instant.GetItemPrefab(data.piecehammer); if ((Object)(object)val14 == (Object)null) { val14 = ((Component)WMRecipeCust.selectedPiecehammer).gameObject; } val.GetComponent().m_enabled = true; if (!((Object)(object)val14 == (Object)null) && !(data.piecehammer == "_CultivatorPieceTable") && DisabledPieceandHam.ContainsKey(val)) { if (!val14.GetComponent().m_itemData.m_shared.m_buildPieces.m_pieces.Contains(val)) { val14.GetComponent().m_itemData.m_shared.m_buildPieces.m_pieces.Add(val); } DisabledPieceandHam.Remove(val); } } if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Setting Piece data for " + data.name); } if (!string.IsNullOrEmpty(data.m_name)) { val.GetComponent().m_name = data.m_name; val.GetComponent().m_description = data.m_description ?? val.GetComponent().m_description; } CraftingStation item = default(CraftingStation); if (!string.IsNullOrEmpty(data.clonePrefabName) && val.TryGetComponent(ref item)) { if (!WMRecipeCust.NewCraftingStations.Contains(item)) { WMRecipeCust.NewCraftingStations.Add(val.GetComponent()); } ((Object)val.GetComponent()).name = data.name; val.GetComponent().m_name = data.m_name ?? val.GetComponent().m_name; if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" new CraftingStation named " + data.name + " "); } } if (data.minStationLevel > 1) { List pieceWithLvl = WMRecipeCust.pieceWithLvl; string name3 = ((Object)val).name; int? minStationLevel = data.minStationLevel; pieceWithLvl.Add(name3 + "." + minStationLevel); } if (data.build != null) { List list = new List(); foreach (string item3 in data.build) { string[] array4 = item3.Split(new char[1] { ':' }); list.Add(new Requirement { m_resItem = Instant.GetItemPrefab(array4[0]).GetComponent(), m_amount = int.Parse(array4[1]), m_amountPerLevel = int.Parse(array4[2]), m_recover = (array4[3].ToLower() == "true") }); } val.GetComponent().m_resources = list.ToArray(); } Piece component3 = val.GetComponent(); component3.m_name = data.m_name ?? component3.m_name; component3.m_description = data.m_description ?? component3.m_description; Door val15 = default(Door); if (((Component)component3).gameObject.TryGetComponent(ref val15)) { val15.m_name = component3.m_name; } if (data.sizeMultiplier != null) { List list2 = data.sizeMultiplier.Split(new char[1] { '|' }).ToList(); int count = list2.Count; List list3 = new List(); foreach (string item4 in list2) { item4.Replace(",", "."); if (float.TryParse(item4, NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out var result)) { list3.Add(result); } } switch (count) { case 1: if (list3[0] != 1f) { Vector3 localScale3 = default(Vector3); ((Vector3)(ref localScale3))..ctor(list3[0], list3[0], list3[0]); val.transform.localScale = localScale3; } break; case 2: { Vector3 localScale2 = default(Vector3); ((Vector3)(ref localScale2))..ctor(list3[0], list3[1], 1f); val.transform.localScale = localScale2; break; } default: { Vector3 localScale = default(Vector3); ((Vector3)(ref localScale))..ctor(list3[0], list3[1], list3[2]); val.transform.localScale = localScale; break; } } } component3.m_groundPiece = data.groundPiece ?? component3.m_groundPiece; component3.m_groundOnly = data.ground ?? component3.m_groundOnly; component3.m_waterPiece = data.waterPiece ?? component3.m_waterPiece; component3.m_noInWater = data.noInWater ?? component3.m_noInWater; component3.m_notOnFloor = data.notOnFloor ?? component3.m_notOnFloor; component3.m_onlyInTeleportArea = data.onlyinTeleportArea ?? component3.m_onlyInTeleportArea; component3.m_allowedInDungeons = data.allowedInDungeons ?? component3.m_allowedInDungeons; component3.m_canBeRemoved = data.canBeRemoved ?? component3.m_canBeRemoved; component3.m_notOnWood = data.notOnWood ?? component3.m_notOnWood; if (data.comfort != null) { component3.m_comfort = data.comfort.comfort ?? component3.m_comfort; component3.m_comfortGroup = (ComfortGroup)(((??)data.comfort.comfortGroup) ?? component3.m_comfortGroup); if (!string.IsNullOrEmpty(data.comfort.comfortObjectName)) { component3.m_comfortObject = Instant.GetItemPrefab(data.comfort.comfortObjectName) ?? component3.m_comfortObject; } } if (data.wearNTearData != null) { WearNTear val16 = default(WearNTear); val.TryGetComponent(ref val16); val16.m_health = data.wearNTearData.health ?? val16.m_health; if (!string.IsNullOrEmpty(((object)(DamageModifiers)(ref data.wearNTearData.damageModifiers)).ToString())) { val16.m_damages = data.wearNTearData.damageModifiers; } val16.m_noRoofWear = data.wearNTearData.noRoofWear ?? val16.m_noRoofWear; val16.m_noSupportWear = data.wearNTearData.noSupportWear ?? val16.m_noSupportWear; val16.m_supports = data.wearNTearData.supports ?? val16.m_supports; val16.m_triggerPrivateArea = data.wearNTearData.triggerPrivateArea ?? val16.m_triggerPrivateArea; val16.m_materialType = (MaterialType)(((??)data.wearNTearData.materialType) ?? val16.m_materialType); val16.m_burnable = data.wearNTearData.burnable ?? val16.m_burnable; } if (data.craftingStationData != null) { CraftingStation val17 = default(CraftingStation); if (val.TryGetComponent(ref val17)) { val17.m_discoverRange = data.craftingStationData.discoveryRange ?? val17.m_discoverRange; val17.m_rangeBuild = data.craftingStationData.buildRange ?? val17.m_rangeBuild; val17.m_craftRequireRoof = data.craftingStationData.craftRequiresRoof ?? val17.m_craftRequireRoof; val17.m_craftRequireFire = data.craftingStationData.craftRequiresFire ?? val17.m_craftRequireFire; val17.m_showBasicRecipies = data.craftingStationData.showBasicRecipes ?? val17.m_showBasicRecipies; val17.m_useDistance = data.craftingStationData.useDistance ?? val17.m_useDistance; val17.m_useAnimation = data.craftingStationData.useAnimation ?? val17.m_useAnimation; } else { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.WLog.LogInfo((object)" Attemping to making Piece into CraftingStation "); } CraftingStation component4 = new GetDataYML().GetJustThePieceRecipeByName("forge", ObjectDB.instance).GetComponent(); CraftingStation val18 = val.AddComponent(); ((Object)val18).name = data.name; val18.m_icon = component3.m_icon; val18.m_roofCheckPoint = null; val18.m_connectionPoint = null; val18.m_effectAreaCollider = null; val18.m_craftRequireRoof = false; val18.m_craftRequireFire = false; Object.Instantiate(((Component)((Component)component4).transform.Find("PlayerBase")).gameObject).transform.SetParent(val.transform); if (data.cSExtensionDataList != null || data.cSExtensionData != null) { component3.m_name += "\n[$KEY_Use] $piece_use "; } WMRecipeCust.NewCraftingStations.Add(val18); val18.m_areaMarker = null; val18.m_inUseObject = null; val18.m_craftItemDoneEffects = null; val18.m_repairItemDoneEffects = null; val18.m_craftItemEffects = null; val18.m_useAnimation = 2; val18.m_name = data.m_name; val18.m_buildRange = 5f; val18.m_discoverRange = data.craftingStationData.discoveryRange ?? val18.m_discoverRange; val18.m_rangeBuild = data.craftingStationData.buildRange ?? val18.m_rangeBuild; val18.m_showBasicRecipies = data.craftingStationData.showBasicRecipes ?? val18.m_showBasicRecipies; val18.m_useDistance = data.craftingStationData.useDistance ?? val18.m_useDistance; val18.m_useAnimation = data.craftingStationData.useAnimation ?? val18.m_useAnimation; } } if (data.cSExtensionDataList != null || data.cSExtensionData != null) { StationExtension[] components = val.GetComponents(); int num = components.Count(); if (data.cSExtensionData != null) { data.cSExtensionDataList = new List(); data.cSExtensionDataList.Add(data.cSExtensionData); } int num2 = data.cSExtensionDataList.Count(); CraftingStation val20 = default(CraftingStation); foreach (CSExtensionData cSExtensionData in data.cSExtensionDataList) { bool flag4 = false; CraftingStation val19 = null; if ((Object)(object)DataHelpers.GetCraftingStation(cSExtensionData.MainCraftingStationName) == (Object)null) { if ((Object)(object)DataHelpers.GetCraftingStation("$" + cSExtensionData.MainCraftingStationName) == (Object)null) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.WLog.LogInfo((object)(" CraftingStation is null so extra search enabled " + cSExtensionData.MainCraftingStationName)); } GameObject justThePieceRecipeByName = new GetDataYML().GetJustThePieceRecipeByName(cSExtensionData.MainCraftingStationName, ObjectDB.instance); if ((Object)(object)justThePieceRecipeByName != (Object)null && justThePieceRecipeByName.TryGetComponent(ref val20)) { val19 = val20; if (WMRecipeCust.showLogs.Value) { WMRecipeCust.WLog.LogInfo((object)" Found in extra search"); } } } else { cSExtensionData.MainCraftingStationName = "$" + cSExtensionData.MainCraftingStationName; if (WMRecipeCust.showLogs.Value) { WMRecipeCust.WLog.LogInfo((object)(" Adding $ worked " + cSExtensionData.MainCraftingStationName)); } } } StationExtension[] array5 = components; foreach (StationExtension val21 in array5) { if ((Object)(object)val21.m_craftingStation == (Object)(object)DataHelpers.GetCraftingStation(cSExtensionData.MainCraftingStationName) || (Object)(object)val21.m_craftingStation == (Object)(object)val19 || num == num2) { flag4 = true; if (WMRecipeCust.showLogs.Value) { WMRecipeCust.WLog.LogInfo((object)(" Piece has extension on it for " + cSExtensionData.MainCraftingStationName)); } val21.m_craftingStation = DataHelpers.GetCraftingStation(cSExtensionData.MainCraftingStationName) ?? val21.m_craftingStation; val21.m_maxStationDistance = cSExtensionData.maxStationDistance ?? val21.m_maxStationDistance; val21.m_continousConnection = cSExtensionData.continousConnection ?? val21.m_continousConnection; val21.m_stack = cSExtensionData.stack ?? val21.m_stack; break; } } if (!flag4 && (Object)(object)DataHelpers.GetCraftingStation(cSExtensionData.MainCraftingStationName) != (Object)null) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.WLog.LogInfo((object)(" Making Piece into Extension for " + cSExtensionData.MainCraftingStationName)); } StationExtension component5 = new GetDataYML().GetJustThePieceRecipeByName("forge_ext5", ObjectDB.instance).GetComponent(); StationExtension obj9 = val.AddComponent(); obj9.m_connectionPrefab = component5.m_connectionPrefab; obj9.m_craftingStation = DataHelpers.GetCraftingStation(cSExtensionData.MainCraftingStationName); obj9.m_maxStationDistance = cSExtensionData.maxStationDistance.GetValueOrDefault(5f); obj9.m_continousConnection = cSExtensionData.continousConnection.GetValueOrDefault(); obj9.m_stack = cSExtensionData.stack.GetValueOrDefault(); } } } if (data.contData != null) { Container val22 = default(Container); val.TryGetComponent(ref val22); val22.m_autoDestroyEmpty = data.contData.AutoDestoryIfEmpty ?? val22.m_autoDestroyEmpty; val22.m_height = data.contData.Height ?? val22.m_height; val22.m_width = data.contData.Width ?? val22.m_width; } if (data.sapData != null) { SapCollector val23 = default(SapCollector); val.TryGetComponent(ref val23); val23.m_secPerUnit = data.sapData.secPerUnit ?? val23.m_secPerUnit; val23.m_maxLevel = data.sapData.maxLevel ?? val23.m_maxLevel; if (data.sapData.producedItem != null) { val23.m_spawnItem = Instant.GetItemPrefab(data.sapData.producedItem).GetComponent(); } if (data.sapData.connectedToWhat != null) { GameObject[] array = AllObjects; foreach (GameObject val24 in array) { if ((Object)(object)val24.GetComponent() != (Object)null && ((Object)val24).name == data.sapData.connectedToWhat) { val23.m_mustConnectTo = val24.GetComponent(); break; } } } val23.m_extractText = data.sapData.extractText; val23.m_drainingText = data.sapData.drainingText; val23.m_drainingSlowText = data.sapData.drainingSlowText; val23.m_notConnectedText = data.sapData.notConnectedText; val23.m_fullText = data.sapData.fullText; } if (data.shipData != null) { Ship val25 = default(Ship); val.TryGetComponent(ref val25); val25.m_ashlandsReady = data.shipData.ashlandProof ?? val25.m_ashlandsReady; } if (data.fermStationData != null) { Fermenter val26 = default(Fermenter); val.TryGetComponent(ref val26); val26.m_fermentationDuration = data.fermStationData.fermDuration ?? val26.m_fermentationDuration; if (data.fermStationData.fermConversion != null) { List conversion = val26.m_conversion; foreach (FermenterConversionList userlist3 in data.fermStationData.fermConversion) { if (conversion.Exists([NullableContext(0)] (ItemConversion x) => ((Object)((Component)x.m_from).gameObject).name == userlist3.FromName)) { ItemConversion val27 = conversion.Find([NullableContext(0)] (ItemConversion x) => ((Object)((Component)x.m_from).gameObject).name == userlist3.FromName); if (userlist3.ToName != null) { val27.m_to = Instant.GetItemPrefab(userlist3.ToName).GetComponent(); } val27.m_producedItems = userlist3.Amount ?? val27.m_producedItems; if (userlist3.Remove.GetValueOrDefault()) { conversion.Remove(val27); } } else if ((!userlist3.Remove).GetValueOrDefault()) { ItemConversion val28 = new ItemConversion(); if (userlist3.FromName != null) { val28.m_from = Instant.GetItemPrefab(userlist3.FromName).GetComponent(); } if (userlist3.ToName != null) { val28.m_to = Instant.GetItemPrefab(userlist3.ToName).GetComponent(); } val28.m_producedItems = userlist3.Amount ?? val28.m_producedItems; conversion.Add(val28); } } } } if (data.beehiveData != null) { Beehive val29 = default(Beehive); val.TryGetComponent(ref val29); val29.m_effectOnlyInDaylight = data.beehiveData.effectOnlyInDaylight ?? val29.m_effectOnlyInDaylight; val29.m_maxCover = data.beehiveData.maxCover ?? val29.m_maxCover; val29.m_biome = (Biome)(((??)data.beehiveData.biomes) ?? val29.m_biome); val29.m_secPerUnit = data.beehiveData.secPerUnit ?? val29.m_secPerUnit; val29.m_maxHoney = data.beehiveData.maxAmount ?? val29.m_maxHoney; if (data.beehiveData.dropItem != null) { val29.m_honeyItem = Instant.GetItemPrefab(data.beehiveData.dropItem).GetComponent(); } val29.m_spawnEffect = val29.m_spawnEffect ?? val29.m_spawnEffect; if (data.beehiveData.effects != null) { val29.m_spawnEffect = FindEffect(val29.m_spawnEffect, data.beehiveData.effects); } if (data.beehiveData.effectsPLUS.Length != 0 && data.beehiveData.effectsPLUS != null) { val29.m_spawnEffect = FindEffect(val29.m_spawnEffect, data.beehiveData.effectsPLUS); } val29.m_extractText = data.beehiveData.extractText ?? val29.m_extractText; val29.m_checkText = data.beehiveData.checkText ?? val29.m_checkText; val29.m_areaText = data.beehiveData.areaText ?? val29.m_areaText; val29.m_freespaceText = data.beehiveData.freespaceText ?? val29.m_freespaceText; val29.m_sleepText = data.beehiveData.sleepText ?? val29.m_sleepText; val29.m_happyText = data.beehiveData.happyText ?? val29.m_happyText; } if (data.incineratorData != null) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.WLog.LogInfo((object)" Setting Incinerator"); } Incinerator val30 = default(Incinerator); val.TryGetComponent(ref val30); val30.m_defaultCost = data.incineratorData.defaultCostPerDrop ?? val30.m_defaultCost; if (data.incineratorData.defaultDrop != null) { val30.m_defaultResult = Instant.GetItemPrefab(data.incineratorData.defaultDrop).GetComponent(); } if (data.incineratorData.incineratorConversion != null) { val30.m_conversions.Clear(); _ = val30.m_conversions; foreach (ObliteratorList item5 in data.incineratorData.incineratorConversion) { IncineratorConversion val31 = new IncineratorConversion(); val31.m_requireOnlyOneIngredient = item5.RequireOnlyOne.GetValueOrDefault(true); val31.m_resultAmount = item5.ResultAmount.GetValueOrDefault(1); val31.m_priority = item5.Priority.GetValueOrDefault(); if (item5.Result != null) { val31.m_result = Instant.GetItemPrefab(item5.Result).GetComponent(); } else { val31.m_result = Instant.GetItemPrefab("Coal").GetComponent(); } val31.m_requirements = new List(); foreach (ObRequirementList requirement in item5.Requirements) { if (requirement.Name != null) { Requirement val32 = new Requirement(); val32.m_amount = requirement.Amount.GetValueOrDefault(1); val32.m_resItem = Instant.GetItemPrefab(requirement.Name).GetComponent(); val31.m_requirements.Add(val32); } } val30.m_conversions.Add(val31); } } } if (data.teleportWorldData != null) { TeleportWorld val33 = default(TeleportWorld); val.TryGetComponent(ref val33); val33.m_allowAllItems = data.teleportWorldData.AllowAllItems ?? val33.m_allowAllItems; } if (data.shieldGenData != null) { ShieldGenerator val34 = default(ShieldGenerator); val.TryGetComponent(ref val34); val34.m_name = data.shieldGenData.name ?? val34.m_name; val34.m_add = data.shieldGenData.nameAdd ?? val34.m_add; val34.m_fuelPerDamage = data.shieldGenData.fuelPerDamage ?? val34.m_fuelPerDamage; val34.m_offWhenNoFuel = data.shieldGenData.offWhenOutofFuel ?? val34.m_offWhenNoFuel; val34.m_maxFuel = data.shieldGenData.maxFuel ?? val34.m_maxFuel; val34.m_defaultFuel = data.shieldGenData.spawnWithFuel ?? val34.m_defaultFuel; val34.m_maxShieldRadius = data.shieldGenData.maxRadius ?? val34.m_maxShieldRadius; val34.m_minShieldRadius = data.shieldGenData.minRadius ?? val34.m_minShieldRadius; val34.m_enableAttack = data.shieldGenData.attack ?? val34.m_enableAttack; val34.m_attackChargeTime = data.shieldGenData.attackChargeTime ?? val34.m_attackChargeTime; val34.m_damagePlayers = data.shieldGenData.attackPlayers ?? val34.m_damagePlayers; if (data.shieldGenData.fuel != null) { val34.m_fuelItems.Clear(); foreach (string item6 in data.shieldGenData.fuel) { val34.m_fuelItems.Add(Instant.GetItemPrefab(item6).GetComponent()); } } } if (data.batteringRamData != null) { SiegeMachine val35 = default(SiegeMachine); val.TryGetComponent(ref val35); val35.m_chargeTime = data.batteringRamData.chargeTime ?? val35.m_chargeTime; Smelter componentInChildren = val.GetComponentInChildren(); componentInChildren.m_maxOre = data.batteringRamData.maxFuel ?? componentInChildren.m_maxOre; } if (data.fireplaceData != null) { Fireplace val36 = default(Fireplace); val.TryGetComponent(ref val36); val36.m_startFuel = data.fireplaceData.StartFuel ?? val36.m_startFuel; val36.m_maxFuel = data.fireplaceData.MaxFuel ?? val36.m_maxFuel; val36.m_secPerFuel = data.fireplaceData.SecPerFuel ?? val36.m_secPerFuel; val36.m_infiniteFuel = data.fireplaceData.InfiniteFuel ?? val36.m_infiniteFuel; val36.m_igniteChance = data.fireplaceData.IgniteChance ?? val36.m_igniteChance; val36.m_igniteSpread = data.fireplaceData.IgniteSpread ?? val36.m_igniteSpread; val36.m_igniteInterval = data.fireplaceData.IgniteInterval ?? val36.m_igniteInterval; if (data.fireplaceData.FuelType != null) { val36.m_fuelItem = Instant.GetItemPrefab(data.fireplaceData.FuelType).GetComponent(); } } if (data.plantData != null) { Plant val37 = default(Plant); val.TryGetComponent(ref val37); val37.m_name = data.plantData.m_name ?? val37.m_name; val37.m_growTime = data.plantData.GrowTime ?? val37.m_growTime; val37.m_growTimeMax = data.plantData.MaxGrowTime ?? val37.m_growTimeMax; if (data.plantData.GrowPrefab != null) { GameObject val38 = null; GameObject[] array = AllObjects; foreach (GameObject val39 in array) { if (((Object)val39).name == data.plantData.GrowPrefab) { val38 = val39; break; } } if ((Object)(object)val38 != (Object)null) { val37.m_grownPrefabs[0] = val38; } } val37.m_minScale = data.plantData.MinSize ?? val37.m_minScale; val37.m_maxScale = data.plantData.MaxSize ?? val37.m_maxScale; val37.m_growRadius = data.plantData.GrowRadius ?? val37.m_growRadius; val37.m_growRadiusVines = data.plantData.GrowRadiusVines ?? val37.m_growRadiusVines; val37.m_needCultivatedGround = data.plantData.CultivatedGround ?? val37.m_needCultivatedGround; val37.m_destroyIfCantGrow = data.plantData.DestroyIfCantGrow ?? val37.m_destroyIfCantGrow; val37.m_tolerateHeat = data.plantData.TolerateHeat ?? val37.m_tolerateHeat; val37.m_tolerateCold = data.plantData.TolerateCold ?? val37.m_tolerateCold; val37.m_biome = (Biome)(((??)data.plantData.Biomes) ?? val37.m_biome); } if (data.cookingStationData != null) { CookingStation val40 = default(CookingStation); val.TryGetComponent(ref val40); val40.m_addItemTooltip = data.cookingStationData.addItemTooltip ?? val40.m_addItemTooltip; if (data.cookingStationData.overcookedItem != null) { val40.m_overCookedItem = Instant.GetItemPrefab(data.cookingStationData.overcookedItem).GetComponent(); } if (data.cookingStationData.fuelItem != null) { val40.m_fuelItem = Instant.GetItemPrefab(data.cookingStationData.fuelItem).GetComponent(); } val40.m_requireFire = data.cookingStationData.requireFire ?? val40.m_requireFire; val40.m_maxFuel = data.cookingStationData.maxFuel ?? val40.m_maxFuel; val40.m_secPerFuel = data.cookingStationData.secPerFuel ?? val40.m_secPerFuel; if (data.cookingStationData.cookConversion != null) { List conversion2 = val40.m_conversion; foreach (CookStationConversionList userlist2 in data.cookingStationData.cookConversion) { if (conversion2.Exists([NullableContext(0)] (ItemConversion x) => ((Object)((Component)x.m_from).gameObject).name == userlist2.FromName)) { ItemConversion val41 = conversion2.Find([NullableContext(0)] (ItemConversion x) => ((Object)((Component)x.m_from).gameObject).name == userlist2.FromName); if (userlist2.ToName != null) { val41.m_to = Instant.GetItemPrefab(userlist2.ToName).GetComponent(); } val41.m_cookTime = userlist2.CookTime.GetValueOrDefault(10f); if (userlist2.Remove.GetValueOrDefault()) { conversion2.Remove(val41); } } else if ((!userlist2.Remove).GetValueOrDefault()) { ItemConversion val42 = new ItemConversion(); if (userlist2.FromName != null) { val42.m_from = Instant.GetItemPrefab(userlist2.FromName).GetComponent(); } if (userlist2.ToName != null) { val42.m_to = Instant.GetItemPrefab(userlist2.ToName).GetComponent(); } val42.m_cookTime = userlist2.CookTime.GetValueOrDefault(10f); conversion2.Add(val42); } } } } ((object)val).GetType(); Smelter val43 = default(Smelter); if (data.smelterData == null || !val.TryGetComponent(ref val43)) { return; } if (WMRecipeCust.showLogs.Value) { WMRecipeCust.WLog.LogInfo((object)" Setting Smelt"); } val43.m_addOreTooltip = data.smelterData.addOreTooltip ?? val43.m_addOreTooltip; val43.m_emptyOreTooltip = data.smelterData.emptyOreTooltip ?? val43.m_emptyOreTooltip; if (data.smelterData.fuelItem != null) { val43.m_fuelItem = Instant.GetItemPrefab(data.smelterData.fuelItem.name).GetComponent(); } val43.m_maxOre = data.smelterData.maxOre ?? val43.m_maxOre; val43.m_maxFuel = data.smelterData.maxFuel ?? val43.m_maxFuel; val43.m_fuelPerProduct = data.smelterData.fuelPerProduct ?? val43.m_fuelPerProduct; val43.m_secPerProduct = data.smelterData.secPerProduct ?? val43.m_secPerProduct; val43.m_spawnStack = data.smelterData.spawnStack ?? val43.m_spawnStack; val43.m_requiresRoof = data.smelterData.requiresRoof ?? val43.m_requiresRoof; val43.m_addOreAnimationDuration = data.smelterData.addOreAnimationLength ?? val43.m_addOreAnimationDuration; if (data.smelterData.smelterConversion == null) { return; } List conversion3 = val43.m_conversion; foreach (SmelterConversionList userlist in data.smelterData.smelterConversion) { if (conversion3.Exists([NullableContext(0)] (ItemConversion x) => ((Object)((Component)x.m_from).gameObject).name == userlist.FromName)) { ItemConversion val44 = conversion3.Find([NullableContext(0)] (ItemConversion x) => ((Object)((Component)x.m_from).gameObject).name == userlist.FromName); if (userlist.ToName != null) { val44.m_to = Instant.GetItemPrefab(userlist.ToName).GetComponent(); } if (userlist.Remove.GetValueOrDefault()) { conversion3.Remove(val44); } } else if ((!userlist.Remove).GetValueOrDefault()) { ItemConversion val45 = new ItemConversion(); if (userlist.FromName != null) { val45.m_from = Instant.GetItemPrefab(userlist.FromName).GetComponent(); } if (userlist.ToName != null) { val45.m_to = Instant.GetItemPrefab(userlist.ToName).GetComponent(); } conversion3.Add(val45); } } } } internal static GameObject SetClonedItemsDataCache(WItemData data, ObjectDB Instant, bool WithZDO = false) { //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_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Expected O, but got Unknown //IL_0192: 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_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_065c: Unknown result type (might be due to invalid IL or missing references) //IL_0627: Unknown result type (might be due to invalid IL or missing references) //IL_05f0: Unknown result type (might be due to invalid IL or missing references) bool flag = false; bool flag2 = false; foreach (string item in WMRecipeCust.ClonedI) { if (item == data.name) { flag = true; } } foreach (string item2 in WMRecipeCust.MockI) { if (item2 == data.name) { flag2 = true; } } if (data.mockName != null && !flag2) { if (ObjModelLoader._loadedModels.ContainsKey(data.mockName)) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Mock Model is loaded" + data.name); } LayerMask val = LayerMask.op_Implicit(LayerMask.NameToLayer("item")); GameObject val2 = new GameObject("Inactive_MockerBase"); val2.SetActive(false); GameObject val3 = Object.Instantiate(ObjModelLoader.MockItemBase, val2.transform); ((Object)val3).name = data.name; ItemDrop component = val3.GetComponent(); ((Object)component).name = data.name; component.m_itemData.m_shared.m_name = data.m_name ?? "Cube"; if (ObjModelLoader._loadedModels.TryGetValue(data.mockName, out var value)) { ((Component)val3.transform.Find("Cube")).gameObject.SetActive(false); GameObject obj = Object.Instantiate(value, val3.transform); obj.SetActive(true); ((Object)obj).name = "attach"; obj.transform.localScale = Vector3.one * 1f; obj.layer = LayerMask.op_Implicit(val); Transform[] componentsInChildren = obj.GetComponentsInChildren(); for (int i = 0; i < componentsInChildren.Length; i++) { ((Component)componentsInChildren[i]).gameObject.layer = LayerMask.op_Implicit(val); } Instant.m_items.Add(val3); WMRecipeCust.MockI.Add(data.name); if (!string.IsNullOrEmpty(data.material)) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Item " + data.name + " searching for mat " + data.material); } try { Renderer[] componentsInChildren2 = val3.GetComponentsInChildren(true); Material value4; if (Enumerable.Contains(data.material, ',')) { string[] array = data.material.Split(new char[1] { ',' }); WMRecipeCust.originalMaterials.TryGetValue(array[0], out var value2); WMRecipeCust.originalMaterials.TryGetValue(array[1], out var value3); Renderer[] array2 = componentsInChildren2; foreach (Renderer val4 in array2) { if (val4.receiveShadows) { if ((Object)(object)value2 != (Object)null && array[0] != "none") { PrefabAssistant.UpdateMaterialReference(val4, value2); } } else if ((Object)(object)value3 != (Object)null) { PrefabAssistant.UpdateMaterialReference(val4, value3); } } } else if (WMRecipeCust.originalMaterials.TryGetValue(data.material, out value4)) { foreach (Renderer renderer in PrefabAssistant.GetRenderers(val3)) { PrefabAssistant.UpdateMaterialReference(renderer, value4); } } else { WMRecipeCust.WLog.LogWarning((object)(data.material + " was not found")); } } catch (Exception ex) { WMRecipeCust.WLog.LogWarning((object)("Material was not found or was not set correctly: " + ex.Message)); } } return val3; } WMRecipeCust.Dbgl("New Mock failed for some reason" + data.name); return null; } WMRecipeCust.Dbgl("Mock Model is not loaded, please redownload file or rename or goodluck! " + data.name); return null; } if (!flag) { string name = data.name; if (!string.IsNullOrEmpty(data.clonePrefabName)) { data.name = data.clonePrefabName; GameObject val5 = DataHelpers.CheckforSpecialObjects(data.name); if ((Object)(object)val5 == (Object)null) { val5 = Instant.GetItemPrefab(data.name); } if ((Object)(object)val5 == (Object)null) { WMRecipeCust.WLog.LogWarning((object)(" item is null " + data.name)); return null; } if ((Object)(object)val5.GetComponent() == (Object)null) { WMRecipeCust.Dbgl("Item data in SetItemData for " + data.name + " not found!"); return null; } if (string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(data.clonePrefabName)) { WMRecipeCust.WLog.LogWarning((object)"Item cloned name is empty!"); return null; } ItemData itemData = val5.GetComponent().m_itemData; WMRecipeCust.Dbgl("Item CLONE " + name + " from cache "); Transform transform = WMRecipeCust.Root.transform; GameObject val6 = Object.Instantiate(val5, transform, false); ItemDrop component2 = val6.GetComponent(); ((Object)component2).name = name; ((Object)val6).name = name; component2.m_itemData.m_shared.m_name = (DataHelpers.ECheck(data.m_name) ? itemData.m_shared.m_name : data.m_name); int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)val6).name); Instant.m_items.Add(val6); Instant.m_itemByHash.Add(stableHashCode, val6); if (data.sizeMultiplier != null) { List list = data.sizeMultiplier.Split(new char[1] { '|' }).ToList(); int count = list.Count; List list2 = new List(); foreach (string item3 in list) { item3.Replace(",", "."); if (float.TryParse(item3, NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out var result)) { list2.Add(result); } } switch (count) { case 1: if (list2[0] != 1f) { Vector3 localScale3 = default(Vector3); ((Vector3)(ref localScale3))..ctor(list2[0], list2[0], list2[0]); val6.transform.GetChild(0).localScale = localScale3; } break; case 2: { Vector3 localScale2 = default(Vector3); ((Vector3)(ref localScale2))..ctor(list2[0], list2[1], 1f); val6.transform.GetChild(0).localScale = localScale2; break; } default: { Vector3 localScale = default(Vector3); ((Vector3)(ref localScale))..ctor(list2[0], list2[1], list2[2]); val6.transform.GetChild(0).localScale = localScale; break; } } } if (!string.IsNullOrEmpty(data.material)) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Item " + name + " searching for mat " + data.material); } try { if (Enumerable.Contains(data.material, ',')) { renderfinder = val6.GetComponentsInChildren(); string[] array3 = data.material.Split(new char[1] { ',' }); Material m = WMRecipeCust.originalMaterials[array3[0]]; Material m2 = WMRecipeCust.originalMaterials[array3[1]]; Renderer[] array2 = renderfinder; foreach (Renderer val7 in array2) { if (val7.receiveShadows && array3[0] != "none") { PrefabAssistant.UpdateMaterialReference(val7, m); } else if (!val7.receiveShadows) { PrefabAssistant.UpdateMaterialReference(val7, m2); } } } else { Material m3 = WMRecipeCust.originalMaterials[data.material]; foreach (Renderer renderer2 in PrefabAssistant.GetRenderers(val6)) { PrefabAssistant.UpdateMaterialReference(renderer2, m3); } } } catch { WMRecipeCust.WLog.LogWarning((object)"Material was not found or was not set correctly"); } } WMRecipeCust.ClonedI.Add(name); data.name = name; if (!WMRecipeCust.ClonedPrefabsMap.ContainsKey(data.name)) { WMRecipeCust.ClonedPrefabsMap.Add(data.name, data.clonePrefabName); } return val6; } return null; } return null; } internal static void SetItemData(WItemData data, ObjectDB Instant, GameObject[] AllObjects = null, bool ZnetNow = true) { //IL_0b4b: Unknown result type (might be due to invalid IL or missing references) //IL_0b50: Unknown result type (might be due to invalid IL or missing references) //IL_0b2c: Unknown result type (might be due to invalid IL or missing references) //IL_0b31: Unknown result type (might be due to invalid IL or missing references) //IL_0a93: Unknown result type (might be due to invalid IL or missing references) //IL_1cf7: Unknown result type (might be due to invalid IL or missing references) //IL_1cee: Unknown result type (might be due to invalid IL or missing references) //IL_335f: Unknown result type (might be due to invalid IL or missing references) //IL_3356: Unknown result type (might be due to invalid IL or missing references) //IL_1cfc: Unknown result type (might be due to invalid IL or missing references) //IL_3364: Unknown result type (might be due to invalid IL or missing references) //IL_0d81: Unknown result type (might be due to invalid IL or missing references) //IL_0d78: Unknown result type (might be due to invalid IL or missing references) //IL_1d38: Unknown result type (might be due to invalid IL or missing references) //IL_1d2f: Unknown result type (might be due to invalid IL or missing references) //IL_33a0: Unknown result type (might be due to invalid IL or missing references) //IL_3397: 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_00f7: 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_0105: Expected O, but got Unknown //IL_0d86: Unknown result type (might be due to invalid IL or missing references) //IL_1d3d: Unknown result type (might be due to invalid IL or missing references) //IL_33a5: Unknown result type (might be due to invalid IL or missing references) //IL_1d79: Unknown result type (might be due to invalid IL or missing references) //IL_1d70: Unknown result type (might be due to invalid IL or missing references) //IL_33e1: Unknown result type (might be due to invalid IL or missing references) //IL_33d8: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: 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_0d11: Unknown result type (might be due to invalid IL or missing references) //IL_0cdd: Unknown result type (might be due to invalid IL or missing references) //IL_0ca7: Unknown result type (might be due to invalid IL or missing references) //IL_1d7e: Unknown result type (might be due to invalid IL or missing references) //IL_33e6: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_4e8a: Unknown result type (might be due to invalid IL or missing references) //IL_4e81: Unknown result type (might be due to invalid IL or missing references) //IL_4e8f: Unknown result type (might be due to invalid IL or missing references) //IL_4ebc: Unknown result type (might be due to invalid IL or missing references) //IL_4eb3: Unknown result type (might be due to invalid IL or missing references) //IL_4ec1: Unknown result type (might be due to invalid IL or missing references) //IL_4eee: Unknown result type (might be due to invalid IL or missing references) //IL_4ee5: Unknown result type (might be due to invalid IL or missing references) //IL_4ef3: Unknown result type (might be due to invalid IL or missing references) //IL_4f20: Unknown result type (might be due to invalid IL or missing references) //IL_4f17: Unknown result type (might be due to invalid IL or missing references) //IL_4f25: Unknown result type (might be due to invalid IL or missing references) //IL_24b3: Unknown result type (might be due to invalid IL or missing references) //IL_24aa: Unknown result type (might be due to invalid IL or missing references) //IL_3f7e: Unknown result type (might be due to invalid IL or missing references) //IL_24b8: Unknown result type (might be due to invalid IL or missing references) //IL_5380: Unknown result type (might be due to invalid IL or missing references) //IL_538a: Unknown result type (might be due to invalid IL or missing references) //IL_53a4: Unknown result type (might be due to invalid IL or missing references) //IL_53a9: Unknown result type (might be due to invalid IL or missing references) //IL_53ae: Unknown result type (might be due to invalid IL or missing references) //IL_1ace: Unknown result type (might be due to invalid IL or missing references) //IL_1ac5: Unknown result type (might be due to invalid IL or missing references) //IL_1ad3: Unknown result type (might be due to invalid IL or missing references) //IL_3136: Unknown result type (might be due to invalid IL or missing references) //IL_312d: Unknown result type (might be due to invalid IL or missing references) //IL_313b: Unknown result type (might be due to invalid IL or missing references) bool flag = false; bool flag2 = false; foreach (string item in WMRecipeCust.ClonedI) { if (item == data.name) { flag = true; } } if (data.mockName != null) { if (!ObjModelLoader._loadedModels.ContainsKey(data.mockName)) { WMRecipeCust.Dbgl("Mock Model is not loaded, please redownload file or rename or goodluck! " + data.name); return; } if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Mock Model is loaded" + data.name); } foreach (string item2 in WMRecipeCust.MockI) { if (item2 == data.name) { flag2 = true; } } if (!flag2) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Mock Model is loading part 1 " + data.name); } LayerMask val = LayerMask.op_Implicit(LayerMask.NameToLayer("item")); GameObject val2 = new GameObject("Inactive_MockerBase"); val2.SetActive(false); GameObject val3 = Object.Instantiate(ObjModelLoader.MockItemBase, val2.transform); ((Object)val3).name = data.name; ItemDrop component = val3.GetComponent(); ((Object)component).name = data.name; component.m_itemData.m_shared.m_name = data.m_name ?? "Cube"; if (!ObjModelLoader._loadedModels.TryGetValue(data.mockName, out var value)) { WMRecipeCust.Dbgl("New Mock failed for some reason" + data.name); return; } ((Component)val3.transform.Find("Cube")).gameObject.SetActive(false); GameObject obj = Object.Instantiate(value, val3.transform); obj.SetActive(true); ((Object)obj).name = "attach"; obj.transform.localScale = Vector3.one * 1f; obj.layer = LayerMask.op_Implicit(val); Transform[] componentsInChildren = obj.GetComponentsInChildren(); for (int i = 0; i < componentsInChildren.Length; i++) { ((Component)componentsInChildren[i]).gameObject.layer = LayerMask.op_Implicit(val); } GameObject val4 = DataHelpers.CheckforSpecialObjects(data.name); if ((Object)(object)val4 == (Object)null) { val4 = Instant.GetItemPrefab(data.name); } if ((Object)(object)val4 == (Object)null) { Instant.m_items.Add(val3); Instant.m_itemByHash.Add(StringExtensionMethods.GetStableHashCode(((Object)val3).name), val3); ZNetScene.instance.m_namedPrefabs[StringExtensionMethods.GetStableHashCode(data.name)] = val3; WMRecipeCust.MockI.Add(data.name); val3.SetActive(true); if (string.IsNullOrEmpty(data.customIcon)) { try { Functions.SnapshotItem(val3.GetComponent()); } catch { WMRecipeCust.WLog.LogInfo((object)"Icon cloned failed"); } } if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("New Mock Model with New Gameobject, loaded " + data.name); } } else { WMRecipeCust.Dbgl("New Mock Model with an existing Gameobject, doesn't work right now, please create name for mock item " + data.name); } } } string name = data.name; if (!string.IsNullOrEmpty(data.clonePrefabName) && !flag) { data.name = data.clonePrefabName; } GameObject val5 = DataHelpers.CheckforSpecialObjects(data.name); if ((Object)(object)val5 == (Object)null) { val5 = Instant.GetItemPrefab(data.name); } if ((Object)(object)val5 == (Object)null && !string.IsNullOrEmpty(data.clonePrefabName)) { val5 = Instant.GetItemPrefab(data.clonePrefabName); if ((Object)(object)val5 != (Object)null) { WMRecipeCust.WLog.LogInfo((object)("Last ditch effort to catch " + data.name + " worked, restoring clone")); flag = false; WMRecipeCust.ClonedI.Remove(data.name); data.name = data.clonePrefabName; } } if ((Object)(object)val5 == (Object)null) { WMRecipeCust.WLog.LogWarning((object)("Item is null " + data.name)); return; } if ((Object)(object)val5.GetComponent() == (Object)null) { WMRecipeCust.WLog.LogWarning((object)("Item ItemDrop " + data.name + " is not found!")); return; } if (string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(data.clonePrefabName)) { WMRecipeCust.WLog.LogWarning((object)"Item cloned name is empty!"); return; } int num = Instant.m_items.Count - 1; Vector3 localScale3 = default(Vector3); Vector3 localScale2 = default(Vector3); Vector3 localScale = default(Vector3); MonsterAI val12 = default(MonsterAI); AnimalAI val13 = default(AnimalAI); MonsterAI val16 = default(MonsterAI); AnimalAI val17 = default(AnimalAI); MonsterAI val20 = default(MonsterAI); AnimalAI val21 = default(AnimalAI); MonsterAI val24 = default(MonsterAI); AnimalAI val25 = default(AnimalAI); Feast val26 = default(Feast); MonsterAI val29 = default(MonsterAI); AnimalAI val30 = default(AnimalAI); MonsterAI val33 = default(MonsterAI); AnimalAI val34 = default(AnimalAI); Feast val35 = default(Feast); while (num >= 0) { if (!((Object)(object)Instant.m_items[num] == (Object)(object)val5)) { GameObject obj3 = Instant.m_items[num]; if (!(((obj3 != null) ? ((Object)obj3).name : null) == ((Object)val5).name)) { num--; continue; } } ItemData itemData = Instant.m_items[num].GetComponent().m_itemData; if (!string.IsNullOrEmpty(data.clonePrefabName) && !flag) { if (WMRecipeCust.BlacklistClone.Contains(data.clonePrefabName)) { WMRecipeCust.Dbgl("Can not clone " + data.clonePrefabName + " "); break; } if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Item being set is " + name + " a CLONE of " + data.clonePrefabName); } WMRecipeCust.ClonedI.Add(name); Transform transform = WMRecipeCust.Root.transform; GameObject val6 = Object.Instantiate(val5, transform, false); ItemDrop component2 = val6.GetComponent(); val6.GetComponent(); ((Object)component2).name = name; ((Object)val6).name = name; component2.m_itemData.m_shared.m_name = (DataHelpers.ECheck(data.m_name) ? itemData.m_shared.m_name : data.m_name); int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)val6).name); ObjectDB.instance.m_items.Add(val6); ObjectDB.instance.m_itemByHash.Add(stableHashCode, val6); WMRecipeCust.WLog.LogDebug((object)("hash " + stableHashCode)); ZNetScene instance = ZNetScene.instance; if (Object.op_Implicit((Object)(object)instance) && ZnetNow) { string name2 = ((Object)val6).name; if (instance.m_namedPrefabs.ContainsKey(stableHashCode)) { WMRecipeCust.WLog.LogWarning((object)("Prefab " + name2 + " already in ZNetScene")); } else { if ((Object)(object)val6.GetComponent() != (Object)null) { instance.m_prefabs.Add(val6); } else { instance.m_nonNetViewPrefabs.Add(val6); } instance.m_namedPrefabs.Add(stableHashCode, val6); if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Added prefab " + name2); } } instance.m_namedPrefabs[stableHashCode].gameObject.SetActive(false); } val5 = Instant.GetItemPrefab(name); itemData = val5.GetComponent().m_itemData; itemData.m_dropPrefab = val5; data.name = name; val5.SetActive(true); } if (flag || flag2) { val5.SetActive(true); } if (!string.IsNullOrEmpty(data.material) || (data.materials != null && data.materials.Length != 0)) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Item " + data.name + " searching for " + data.material); } try { Material value2; if (data.materials != null && data.materials.Length != 0) { try { if (WMRecipeCust.showLogs.Value) { Debug.Log((object)"Updating materials"); } Material[] array = (Material[])(object)new Material[data.materials.Length]; for (uint num2 = 0u; num2 < data.materials.Length; num2++) { WMRecipeCust.originalMaterials.TryGetValue(data.materials[num2], out array[num2]); } if (WMRecipeCust.showLogs.Value) { Debug.Log((object)"Applying materials"); } foreach (Renderer renderer in PrefabAssistant.GetRenderers(val5)) { PrefabAssistant.UpdateMaterialReferences(renderer, array); } } catch (Exception ex) { WMRecipeCust.WLog.LogError((object)ex); } } else if (Enumerable.Contains(data.material, ',')) { renderfinder = val5.GetComponentsInChildren(); string[] array2 = data.material.Split(new char[1] { ',' }); Material m = WMRecipeCust.originalMaterials[array2[0]]; Material m2 = WMRecipeCust.originalMaterials[array2[1]]; Renderer[] array3 = renderfinder; foreach (Renderer val7 in array3) { if (val7.receiveShadows && array2[0] != "none") { PrefabAssistant.UpdateMaterialReference(val7, m); } else if (!val7.receiveShadows) { PrefabAssistant.UpdateMaterialReference(val7, m2); } } } else if (WMRecipeCust.originalMaterials.TryGetValue(data.material, out value2)) { foreach (Renderer renderer2 in PrefabAssistant.GetRenderers(val5)) { PrefabAssistant.UpdateMaterialReference(renderer2, value2); } } else { WMRecipeCust.WLog.LogWarning((object)(data.material + " was not found")); } } catch { WMRecipeCust.WLog.LogWarning((object)"Material was not found or was not set correctly"); } } ItemDrop val8 = (Reload.lastItemSet = Instant.GetItemPrefab(data.name).GetComponent()); bool flag3 = false; if (!DataHelpers.ECheck(data.customIcon)) { string text = Path.Combine(WMRecipeCust.assetPathIcons, data.customIcon); if (File.Exists(text)) { if (File.ReadAllBytes(text) != null) { try { Sprite val9 = SpriteTools.LoadNewSprite(text, 100f, (SpriteMeshType)1); val8.m_itemData.m_shared.m_icons[0] = val9; flag3 = true; } catch { WMRecipeCust.WLog.LogInfo((object)"customIcon failed"); } } else { WMRecipeCust.WLog.LogInfo((object)("No Img with the name " + data.customIcon + " in Icon Folder - ")); } } else { WMRecipeCust.WLog.LogInfo((object)("No Img with the name " + data.customIcon + " in Icon Folder - ")); } } if (!DataHelpers.ECheck(data.material) && !flag3 && data.snapshotOnMaterialChange.GetValueOrDefault(true)) { try { Quaternion? itemRotation = null; if (data.snapshotRotation != null) { float[] array4 = data.snapshotRotation.Split(new char[1] { ',' }).Select(float.Parse).ToArray(); itemRotation = Quaternion.Euler(array4[0], array4[1], array4[2]); } Functions.SnapshotItem(val8, 1.3f, null, itemRotation); } catch { WMRecipeCust.WLog.LogInfo((object)"Icon cloned failed"); } } if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Item Data being set for " + data.name + " "); } if (data.Damage != null) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item has damage values "); } itemData.m_shared.m_damages = WeaponDamage.ParseDamageTypes(data.Damage); } if (data.Damage_Per_Level != null) { itemData.m_shared.m_damagesPerLevel = WeaponDamage.ParseDamageTypes(data.Damage_Per_Level); } itemData.m_shared.m_name = data.m_name ?? itemData.m_shared.m_name; itemData.m_shared.m_description = data.m_description ?? itemData.m_shared.m_description; itemData.m_shared.m_weight = data.m_weight; itemData.m_shared.m_scaleWeightByQuality = data.scale_weight_by_quality ?? itemData.m_shared.m_scaleWeightByQuality; if (data.sizeMultiplier != null) { List list = data.sizeMultiplier.Split(new char[1] { '|' }).ToList(); int count = list.Count; List list2 = new List(); foreach (string item3 in list) { item3.Replace(",", "."); if (float.TryParse(item3, NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out var result)) { list2.Add(result); } } switch (count) { case 1: if (list2[0] != 1f) { ((Vector3)(ref localScale3))..ctor(list2[0], list2[0], list2[0]); val5.transform.GetChild(0).localScale = localScale3; } break; case 2: ((Vector3)(ref localScale2))..ctor(list2[0], list2[1], 1f); val5.transform.GetChild(0).localScale = localScale2; break; default: ((Vector3)(ref localScale))..ctor(list2[0], list2[1], list2[2]); val5.transform.GetChild(0).localScale = localScale; break; } } if (data.Primary_Attack != null) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item attacks "); } itemData.m_shared.m_attack.m_attackType = (AttackType)(((??)data.Primary_Attack.AttackType) ?? itemData.m_shared.m_attack.m_attackType); itemData.m_shared.m_attack.m_attackAnimation = data.Primary_Attack.Attack_Animation ?? itemData.m_shared.m_attack.m_attackAnimation; itemData.m_shared.m_attack.m_attackRandomAnimations = data.Primary_Attack.Attack_Random_Animation ?? itemData.m_shared.m_attack.m_attackRandomAnimations; itemData.m_shared.m_attack.m_attackChainLevels = data.Primary_Attack.Chain_Attacks ?? itemData.m_shared.m_attack.m_attackChainLevels; itemData.m_shared.m_attack.m_hitTerrain = data.Primary_Attack.Hit_Terrain ?? itemData.m_shared.m_attack.m_hitTerrain; itemData.m_shared.m_attack.m_hitFriendly = data.Primary_Attack.Hit_Friendly ?? itemData.m_shared.m_attack.m_hitFriendly; itemData.m_shared.m_attack.m_isHomeItem = data.Primary_Attack.is_HomeItem ?? itemData.m_shared.m_attack.m_isHomeItem; if (!WMRecipeCust.AttackSpeed.ContainsKey(name)) { WMRecipeCust.AttackSpeed.Add(name, new Dictionary()); WMRecipeCust.AttackSpeed[name].Add(key: false, 1f); WMRecipeCust.AttackSpeed[name].Add(key: true, 1f); } if (data.Primary_Attack.Custom_AttackSpeed.HasValue) { WMRecipeCust.AttackSpeed[name][false] = data.Primary_Attack.Custom_AttackSpeed.Value; } itemData.m_shared.m_attack.m_attackStamina = data.Primary_Attack.m_attackStamina ?? itemData.m_shared.m_attack.m_attackStamina; itemData.m_shared.m_attack.m_attackAdrenaline = data.Primary_Attack.m_attackAdrenaline ?? itemData.m_shared.m_attack.m_attackAdrenaline; itemData.m_shared.m_attack.m_attackUseAdrenaline = data.Primary_Attack.m_attackUseAdrenaline ?? itemData.m_shared.m_attack.m_attackUseAdrenaline; itemData.m_shared.m_attack.m_attackEitr = data.Primary_Attack.m_eitrCost ?? itemData.m_shared.m_attack.m_attackEitr; itemData.m_shared.m_attack.m_attackHealth = data.Primary_Attack.AttackHealthCost ?? itemData.m_shared.m_attack.m_attackHealth; itemData.m_shared.m_attack.m_attackHealthPercentage = data.Primary_Attack.m_attackHealthPercentage ?? itemData.m_shared.m_attack.m_attackHealthPercentage; itemData.m_shared.m_attack.m_attackHealthLowBlockUse = data.Primary_Attack.attack_Health_Low_BlockUsage ?? itemData.m_shared.m_attack.m_attackHealthLowBlockUse; itemData.m_shared.m_attack.m_attackStartNoise = data.Primary_Attack.Attack_Start_Noise ?? itemData.m_shared.m_attack.m_attackStartNoise; itemData.m_shared.m_attack.m_attackHitNoise = data.Primary_Attack.Attack_Hit_Noise ?? itemData.m_shared.m_attack.m_attackHitNoise; itemData.m_shared.m_attack.m_damageMultiplierPerMissingHP = data.Primary_Attack.Dmg_Multiplier_Per_Missing_Health ?? itemData.m_shared.m_attack.m_damageMultiplierPerMissingHP; itemData.m_shared.m_attack.m_damageMultiplierByTotalHealthMissing = data.Primary_Attack.Damage_Multiplier_By_Health_Deficit_Percent ?? itemData.m_shared.m_attack.m_damageMultiplierByTotalHealthMissing; itemData.m_shared.m_attack.m_staminaReturnPerMissingHP = data.Primary_Attack.Stamina_Return_Per_Missing_HP ?? itemData.m_shared.m_attack.m_staminaReturnPerMissingHP; itemData.m_shared.m_attack.m_selfDamage = data.Primary_Attack.SelfDamage ?? itemData.m_shared.m_attack.m_selfDamage; itemData.m_shared.m_attack.m_attackKillsSelf = data.Primary_Attack.Attack_Kills_Self ?? itemData.m_shared.m_attack.m_attackKillsSelf; itemData.m_shared.m_attack.m_speedFactor = data.Primary_Attack.SpeedFactor ?? itemData.m_shared.m_attack.m_speedFactor; itemData.m_shared.m_attack.m_damageMultiplier = data.Primary_Attack.DmgMultiplier ?? itemData.m_shared.m_attack.m_damageMultiplier; itemData.m_shared.m_attack.m_forceMultiplier = data.Primary_Attack.ForceMultiplier ?? itemData.m_shared.m_attack.m_forceMultiplier; itemData.m_shared.m_attack.m_staggerMultiplier = data.Primary_Attack.StaggerMultiplier ?? itemData.m_shared.m_attack.m_staggerMultiplier; itemData.m_shared.m_attack.m_recoilPushback = data.Primary_Attack.RecoilMultiplier ?? itemData.m_shared.m_attack.m_recoilPushback; itemData.m_shared.m_attack.m_attackRange = data.Primary_Attack.AttackRange ?? itemData.m_shared.m_attack.m_attackRange; itemData.m_shared.m_attack.m_attackHeight = data.Primary_Attack.AttackHeight ?? itemData.m_shared.m_attack.m_attackHeight; if (!string.IsNullOrEmpty(data.Primary_Attack.Spawn_On_Trigger)) { string spawn_On_Trigger = data.Primary_Attack.Spawn_On_Trigger; GameObject spawnOnTrigger = itemData.m_shared.m_attack.m_spawnOnTrigger; if (spawn_On_Trigger != ((spawnOnTrigger != null) ? ((Object)spawnOnTrigger).name : null)) { if (data.Primary_Attack.Spawn_On_Trigger == "delete" || data.Primary_Attack.Spawn_On_Trigger == "-") { itemData.m_shared.m_attack.m_spawnOnTrigger = null; } GameObject val10 = null; GameObject[] array5 = AllObjects; foreach (GameObject val11 in array5) { if (((Object)val11).name == data.Primary_Attack.Spawn_On_Trigger) { if ((Object)(object)val10 == (Object)null) { val10 = val11; } else if (val11.TryGetComponent(ref val12) || val11.TryGetComponent(ref val13)) { val10 = val11; } } } itemData.m_shared.m_attack.m_spawnOnTrigger = val10 ?? itemData.m_shared.m_attack.m_spawnOnTrigger; } } itemData.m_shared.m_attack.m_cantUseInDungeon = data.Primary_Attack.cant_Use_InDungeon ?? itemData.m_shared.m_attack.m_cantUseInDungeon; itemData.m_shared.m_attack.m_requiresReload = data.Primary_Attack.Requires_Reload ?? itemData.m_shared.m_attack.m_requiresReload; itemData.m_shared.m_attack.m_reloadAnimation = data.Primary_Attack.Reload_Animation ?? itemData.m_shared.m_attack.m_reloadAnimation; itemData.m_shared.m_attack.m_reloadTime = data.Primary_Attack.ReloadTime ?? itemData.m_shared.m_attack.m_reloadTime; if (itemData.m_shared.m_attack.m_requiresReload) { string name3 = itemData.m_shared.m_name; name3 += "P"; if (WMRecipeCust.crossbowReloadingTime.ContainsKey(name3)) { WMRecipeCust.crossbowReloadingTime[name3] = data.Primary_Attack.ReloadTimeMultiplier.GetValueOrDefault(1f); } else { WMRecipeCust.crossbowReloadingTime.Add(name3, data.Primary_Attack.ReloadTimeMultiplier.GetValueOrDefault(1f)); } } itemData.m_shared.m_attack.m_reloadStaminaDrain = data.Primary_Attack.Reload_Stamina_Drain ?? itemData.m_shared.m_attack.m_reloadStaminaDrain; itemData.m_shared.m_attack.m_reloadEitrDrain = data.Primary_Attack.Reload_Eitr_Drain ?? itemData.m_shared.m_attack.m_reloadEitrDrain; itemData.m_shared.m_attack.m_bowDraw = data.Primary_Attack.Bow_Draw ?? itemData.m_shared.m_attack.m_bowDraw; itemData.m_shared.m_attack.m_drawDurationMin = data.Primary_Attack.Bow_Duration_Min ?? itemData.m_shared.m_attack.m_drawDurationMin; itemData.m_shared.m_attack.m_drawStaminaDrain = data.Primary_Attack.Bow_Stamina_Drain ?? itemData.m_shared.m_attack.m_drawStaminaDrain; itemData.m_shared.m_attack.m_drawAnimationState = data.Primary_Attack.Bow_Animation_State ?? itemData.m_shared.m_attack.m_drawAnimationState; itemData.m_shared.m_attack.m_attackAngle = data.Primary_Attack.Attack_Angle ?? itemData.m_shared.m_attack.m_attackAngle; itemData.m_shared.m_attack.m_attackRayWidth = data.Primary_Attack.Attack_Ray_Width ?? itemData.m_shared.m_attack.m_attackRayWidth; itemData.m_shared.m_attack.m_lowerDamagePerHit = data.Primary_Attack.Lower_Dmg_Per_Hit ?? itemData.m_shared.m_attack.m_lowerDamagePerHit; itemData.m_shared.m_attack.m_hitThroughWalls = data.Primary_Attack.Hit_Through_Walls ?? itemData.m_shared.m_attack.m_hitThroughWalls; itemData.m_shared.m_attack.m_multiHit = data.Primary_Attack.Multi_Hit ?? itemData.m_shared.m_attack.m_multiHit; itemData.m_shared.m_attack.m_pickaxeSpecial = data.Primary_Attack.Pickaxe_Special ?? itemData.m_shared.m_attack.m_pickaxeSpecial; itemData.m_shared.m_attack.m_lastChainDamageMultiplier = data.Primary_Attack.Last_Chain_Dmg_Multiplier ?? itemData.m_shared.m_attack.m_lastChainDamageMultiplier; itemData.m_shared.m_attack.m_resetChainIfHit = (DestructibleType)(((??)data.Primary_Attack.Reset_Chain_If_hit) ?? itemData.m_shared.m_attack.m_resetChainIfHit); if (!string.IsNullOrEmpty(data.Primary_Attack.SpawnOnHit)) { string spawnOnHit = data.Primary_Attack.SpawnOnHit; GameObject spawnOnHit2 = itemData.m_shared.m_attack.m_spawnOnHit; if (spawnOnHit != ((spawnOnHit2 != null) ? ((Object)spawnOnHit2).name : null)) { if (data.Primary_Attack.SpawnOnHit == "delete" || data.Primary_Attack.SpawnOnHit == "-") { itemData.m_shared.m_attack.m_spawnOnHit = null; } else { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " SpawnOnHit m_attack added "); } GameObject val14 = null; try { GameObject[] array5 = AllObjects; foreach (GameObject val15 in array5) { if (((Object)val15).name == data.Primary_Attack.SpawnOnHit) { if ((Object)(object)val14 == (Object)null) { val14 = val15; } else if (val15.TryGetComponent(ref val16) || val15.TryGetComponent(ref val17)) { val14 = val15; } } } } catch (Exception ex2) { WMRecipeCust.WLog.LogInfo((object)("Error catch " + ex2)); } itemData.m_shared.m_attack.m_spawnOnHit = val14 ?? itemData.m_shared.m_attack.m_spawnOnHit; } } } itemData.m_shared.m_attack.m_spawnOnHitChance = data.Primary_Attack.SpawnOnHit_Chance ?? itemData.m_shared.m_attack.m_spawnOnHitChance; itemData.m_shared.m_attack.m_raiseSkillAmount = data.Primary_Attack.Raise_Skill_Amount ?? itemData.m_shared.m_attack.m_raiseSkillAmount; itemData.m_shared.m_attack.m_skillHitType = (DestructibleType)(((??)data.Primary_Attack.Skill_Hit_Type) ?? itemData.m_shared.m_attack.m_skillHitType); itemData.m_shared.m_attack.m_specialHitSkill = (SkillType)(((??)data.Primary_Attack.Special_Hit_Skill) ?? itemData.m_shared.m_attack.m_specialHitSkill); itemData.m_shared.m_attack.m_specialHitType = (DestructibleType)(((??)data.Primary_Attack.Special_Hit_Type) ?? itemData.m_shared.m_attack.m_specialHitType); itemData.m_shared.m_attack.m_projectileVel = data.Primary_Attack.Projectile_Vel ?? itemData.m_shared.m_attack.m_projectileVel; itemData.m_shared.m_attack.m_projectileAccuracy = data.Primary_Attack.Projectile_Accuracy ?? data.Primary_Attack.Projectile_Accuraccy ?? itemData.m_shared.m_attack.m_projectileAccuracy; itemData.m_shared.m_attack.m_projectileAccuracyMin = data.Primary_Attack.Projectile_Accuracy_Min ?? itemData.m_shared.m_attack.m_projectileAccuracyMin; itemData.m_shared.m_attack.m_projectiles = data.Primary_Attack.Projectiles ?? itemData.m_shared.m_attack.m_projectiles; itemData.m_shared.m_attack.m_skillAccuracy = data.Primary_Attack.Skill_Accuracy ?? itemData.m_shared.m_attack.m_skillAccuracy; itemData.m_shared.m_attack.m_launchAngle = data.Primary_Attack.Launch_Angle ?? itemData.m_shared.m_attack.m_launchAngle; itemData.m_shared.m_attack.m_projectileBursts = data.Primary_Attack.Projectile_Burst ?? itemData.m_shared.m_attack.m_projectileBursts; itemData.m_shared.m_attack.m_burstInterval = data.Primary_Attack.Burst_Interval ?? itemData.m_shared.m_attack.m_burstInterval; itemData.m_shared.m_attack.m_destroyPreviousProjectile = data.Primary_Attack.Destroy_Previous_Projectile ?? itemData.m_shared.m_attack.m_destroyPreviousProjectile; itemData.m_shared.m_attack.m_perBurstResourceUsage = data.Primary_Attack.PerBurst_Resource_usage ?? itemData.m_shared.m_attack.m_perBurstResourceUsage; itemData.m_shared.m_attack.m_loopingAttack = data.Primary_Attack.Looping_Attack ?? itemData.m_shared.m_attack.m_loopingAttack; itemData.m_shared.m_attack.m_consumeItem = data.Primary_Attack.Consume_Item ?? itemData.m_shared.m_attack.m_consumeItem; if (data.Primary_Attack.AEffects != null) { if (data.Primary_Attack.AEffects.Hit_Effects != null) { itemData.m_shared.m_attack.m_hitEffect = FindEffect(itemData.m_shared.m_attack.m_hitEffect, data.Primary_Attack.AEffects.Hit_Effects); } if (data.Primary_Attack.AEffects.Hit_Terrain_Effects != null) { itemData.m_shared.m_attack.m_hitTerrainEffect = FindEffect(itemData.m_shared.m_attack.m_hitTerrainEffect, data.Primary_Attack.AEffects.Hit_Terrain_Effects); } if (data.Primary_Attack.AEffects.Start_Effect != null) { itemData.m_shared.m_attack.m_startEffect = FindEffect(itemData.m_shared.m_attack.m_startEffect, data.Primary_Attack.AEffects.Start_Effect); } if (data.Primary_Attack.AEffects.Trigger_Effect != null) { itemData.m_shared.m_attack.m_triggerEffect = FindEffect(itemData.m_shared.m_attack.m_triggerEffect, data.Primary_Attack.AEffects.Trigger_Effect); } if (data.Primary_Attack.AEffects.Trail_Effect != null) { itemData.m_shared.m_attack.m_trailStartEffect = FindEffect(itemData.m_shared.m_attack.m_trailStartEffect, data.Primary_Attack.AEffects.Trail_Effect); } if (data.Primary_Attack.AEffects.Burst_Effect != null) { itemData.m_shared.m_attack.m_burstEffect = FindEffect(itemData.m_shared.m_attack.m_burstEffect, data.Primary_Attack.AEffects.Burst_Effect); } } if (data.Primary_Attack.AEffectsPLUS != null) { if (data.Primary_Attack.AEffectsPLUS.Hit_Effects.Length != 0) { itemData.m_shared.m_attack.m_hitEffect = FindEffect(itemData.m_shared.m_attack.m_hitEffect, data.Primary_Attack.AEffectsPLUS.Hit_Effects); } if (data.Primary_Attack.AEffectsPLUS.Hit_Terrain_Effects.Length != 0) { itemData.m_shared.m_attack.m_hitTerrainEffect = FindEffect(itemData.m_shared.m_attack.m_hitTerrainEffect, data.Primary_Attack.AEffectsPLUS.Hit_Terrain_Effects); } if (data.Primary_Attack.AEffectsPLUS.Start_Effect.Length != 0) { itemData.m_shared.m_attack.m_startEffect = FindEffect(itemData.m_shared.m_attack.m_startEffect, data.Primary_Attack.AEffectsPLUS.Start_Effect); } if (data.Primary_Attack.AEffectsPLUS.Trigger_Effect.Length != 0) { itemData.m_shared.m_attack.m_triggerEffect = FindEffect(itemData.m_shared.m_attack.m_triggerEffect, data.Primary_Attack.AEffectsPLUS.Trigger_Effect); } if (data.Primary_Attack.AEffectsPLUS.Trail_Effect.Length != 0) { itemData.m_shared.m_attack.m_trailStartEffect = FindEffect(itemData.m_shared.m_attack.m_trailStartEffect, data.Primary_Attack.AEffectsPLUS.Trail_Effect); } if (data.Primary_Attack.AEffectsPLUS.Burst_Effect.Length != 0) { itemData.m_shared.m_attack.m_burstEffect = FindEffect(itemData.m_shared.m_attack.m_burstEffect, data.Primary_Attack.AEffectsPLUS.Burst_Effect); } } itemData.m_shared.m_secondaryAttack.m_attackType = (AttackType)(((??)data.Secondary_Attack.AttackType) ?? itemData.m_shared.m_secondaryAttack.m_attackType); itemData.m_shared.m_secondaryAttack.m_attackAnimation = data.Secondary_Attack.Attack_Animation ?? itemData.m_shared.m_secondaryAttack.m_attackAnimation; itemData.m_shared.m_secondaryAttack.m_attackRandomAnimations = data.Secondary_Attack.Attack_Random_Animation ?? itemData.m_shared.m_secondaryAttack.m_attackRandomAnimations; itemData.m_shared.m_secondaryAttack.m_attackChainLevels = data.Secondary_Attack.Chain_Attacks ?? itemData.m_shared.m_secondaryAttack.m_attackChainLevels; itemData.m_shared.m_secondaryAttack.m_hitTerrain = data.Secondary_Attack.Hit_Terrain ?? itemData.m_shared.m_secondaryAttack.m_hitTerrain; itemData.m_shared.m_secondaryAttack.m_hitFriendly = data.Secondary_Attack.Hit_Friendly ?? itemData.m_shared.m_secondaryAttack.m_hitFriendly; itemData.m_shared.m_secondaryAttack.m_isHomeItem = data.Secondary_Attack.is_HomeItem ?? itemData.m_shared.m_secondaryAttack.m_isHomeItem; if (data.Secondary_Attack.Custom_AttackSpeed.HasValue) { WMRecipeCust.AttackSpeed[name][true] = data.Secondary_Attack.Custom_AttackSpeed.Value; } itemData.m_shared.m_secondaryAttack.m_attackStamina = data.Secondary_Attack.m_attackStamina ?? itemData.m_shared.m_secondaryAttack.m_attackStamina; itemData.m_shared.m_secondaryAttack.m_attackAdrenaline = data.Secondary_Attack.m_attackAdrenaline ?? itemData.m_shared.m_secondaryAttack.m_attackAdrenaline; itemData.m_shared.m_secondaryAttack.m_attackUseAdrenaline = data.Secondary_Attack.m_attackUseAdrenaline ?? itemData.m_shared.m_secondaryAttack.m_attackUseAdrenaline; itemData.m_shared.m_secondaryAttack.m_attackEitr = data.Secondary_Attack.m_eitrCost ?? itemData.m_shared.m_secondaryAttack.m_attackEitr; itemData.m_shared.m_secondaryAttack.m_attackHealth = data.Secondary_Attack.AttackHealthCost ?? itemData.m_shared.m_secondaryAttack.m_attackHealth; itemData.m_shared.m_secondaryAttack.m_attackHealthPercentage = data.Secondary_Attack.m_attackHealthPercentage ?? itemData.m_shared.m_secondaryAttack.m_attackHealthPercentage; itemData.m_shared.m_secondaryAttack.m_attackHealthLowBlockUse = data.Secondary_Attack.attack_Health_Low_BlockUsage ?? itemData.m_shared.m_secondaryAttack.m_attackHealthLowBlockUse; itemData.m_shared.m_secondaryAttack.m_attackStartNoise = data.Secondary_Attack.Attack_Start_Noise ?? itemData.m_shared.m_secondaryAttack.m_attackStartNoise; itemData.m_shared.m_secondaryAttack.m_attackHitNoise = data.Secondary_Attack.Attack_Hit_Noise ?? itemData.m_shared.m_secondaryAttack.m_attackHitNoise; itemData.m_shared.m_secondaryAttack.m_damageMultiplierPerMissingHP = data.Secondary_Attack.Dmg_Multiplier_Per_Missing_Health ?? itemData.m_shared.m_secondaryAttack.m_damageMultiplierPerMissingHP; itemData.m_shared.m_secondaryAttack.m_damageMultiplierByTotalHealthMissing = data.Secondary_Attack.Damage_Multiplier_By_Health_Deficit_Percent ?? itemData.m_shared.m_secondaryAttack.m_damageMultiplierByTotalHealthMissing; itemData.m_shared.m_secondaryAttack.m_staminaReturnPerMissingHP = data.Secondary_Attack.Stamina_Return_Per_Missing_HP ?? itemData.m_shared.m_secondaryAttack.m_staminaReturnPerMissingHP; itemData.m_shared.m_secondaryAttack.m_selfDamage = data.Secondary_Attack.SelfDamage ?? itemData.m_shared.m_secondaryAttack.m_selfDamage; itemData.m_shared.m_secondaryAttack.m_attackKillsSelf = data.Secondary_Attack.Attack_Kills_Self ?? itemData.m_shared.m_secondaryAttack.m_attackKillsSelf; itemData.m_shared.m_secondaryAttack.m_speedFactor = data.Secondary_Attack.SpeedFactor ?? itemData.m_shared.m_secondaryAttack.m_speedFactor; itemData.m_shared.m_secondaryAttack.m_damageMultiplier = data.Secondary_Attack.DmgMultiplier ?? itemData.m_shared.m_secondaryAttack.m_damageMultiplier; itemData.m_shared.m_secondaryAttack.m_forceMultiplier = data.Secondary_Attack.ForceMultiplier ?? itemData.m_shared.m_secondaryAttack.m_forceMultiplier; itemData.m_shared.m_secondaryAttack.m_staggerMultiplier = data.Secondary_Attack.StaggerMultiplier ?? itemData.m_shared.m_secondaryAttack.m_staggerMultiplier; itemData.m_shared.m_secondaryAttack.m_recoilPushback = data.Secondary_Attack.RecoilMultiplier ?? itemData.m_shared.m_secondaryAttack.m_recoilPushback; itemData.m_shared.m_secondaryAttack.m_attackRange = data.Secondary_Attack.AttackRange ?? itemData.m_shared.m_secondaryAttack.m_attackRange; itemData.m_shared.m_secondaryAttack.m_attackHeight = data.Secondary_Attack.AttackHeight ?? itemData.m_shared.m_secondaryAttack.m_attackHeight; if (!string.IsNullOrEmpty(data.Secondary_Attack.Spawn_On_Trigger)) { string spawn_On_Trigger2 = data.Secondary_Attack.Spawn_On_Trigger; GameObject spawnOnTrigger2 = itemData.m_shared.m_secondaryAttack.m_spawnOnTrigger; if (spawn_On_Trigger2 != ((spawnOnTrigger2 != null) ? ((Object)spawnOnTrigger2).name : null)) { if (data.Secondary_Attack.Spawn_On_Trigger == "delete" || data.Secondary_Attack.Spawn_On_Trigger == "-") { itemData.m_shared.m_secondaryAttack.m_spawnOnTrigger = null; } GameObject val18 = null; GameObject[] array5 = AllObjects; foreach (GameObject val19 in array5) { if (((Object)val19).name == data.Secondary_Attack.Spawn_On_Trigger) { if ((Object)(object)val18 == (Object)null) { val18 = val19; } else if (val19.TryGetComponent(ref val20) || val19.TryGetComponent(ref val21)) { val18 = val19; } } } itemData.m_shared.m_secondaryAttack.m_spawnOnTrigger = val18 ?? itemData.m_shared.m_secondaryAttack.m_spawnOnTrigger; } } itemData.m_shared.m_secondaryAttack.m_cantUseInDungeon = data.Secondary_Attack.cant_Use_InDungeon ?? itemData.m_shared.m_secondaryAttack.m_cantUseInDungeon; itemData.m_shared.m_secondaryAttack.m_requiresReload = data.Secondary_Attack.Requires_Reload ?? itemData.m_shared.m_secondaryAttack.m_requiresReload; itemData.m_shared.m_secondaryAttack.m_reloadAnimation = data.Secondary_Attack.Reload_Animation ?? itemData.m_shared.m_secondaryAttack.m_reloadAnimation; itemData.m_shared.m_secondaryAttack.m_reloadTime = data.Secondary_Attack.ReloadTime ?? itemData.m_shared.m_secondaryAttack.m_reloadTime; itemData.m_shared.m_secondaryAttack.m_reloadStaminaDrain = data.Secondary_Attack.Reload_Stamina_Drain ?? itemData.m_shared.m_secondaryAttack.m_reloadStaminaDrain; itemData.m_shared.m_secondaryAttack.m_reloadEitrDrain = data.Secondary_Attack.Reload_Eitr_Drain ?? itemData.m_shared.m_secondaryAttack.m_reloadEitrDrain; itemData.m_shared.m_secondaryAttack.m_bowDraw = data.Secondary_Attack.Bow_Draw ?? itemData.m_shared.m_secondaryAttack.m_bowDraw; itemData.m_shared.m_secondaryAttack.m_drawDurationMin = data.Secondary_Attack.Bow_Duration_Min ?? itemData.m_shared.m_secondaryAttack.m_drawDurationMin; itemData.m_shared.m_secondaryAttack.m_drawStaminaDrain = data.Secondary_Attack.Bow_Stamina_Drain ?? itemData.m_shared.m_secondaryAttack.m_drawStaminaDrain; itemData.m_shared.m_secondaryAttack.m_drawAnimationState = data.Secondary_Attack.Bow_Animation_State ?? itemData.m_shared.m_secondaryAttack.m_drawAnimationState; itemData.m_shared.m_secondaryAttack.m_attackAngle = data.Secondary_Attack.Attack_Angle ?? itemData.m_shared.m_secondaryAttack.m_attackAngle; itemData.m_shared.m_secondaryAttack.m_attackRayWidth = data.Secondary_Attack.Attack_Ray_Width ?? itemData.m_shared.m_secondaryAttack.m_attackRayWidth; itemData.m_shared.m_secondaryAttack.m_lowerDamagePerHit = data.Secondary_Attack.Lower_Dmg_Per_Hit ?? itemData.m_shared.m_secondaryAttack.m_lowerDamagePerHit; itemData.m_shared.m_secondaryAttack.m_hitThroughWalls = data.Secondary_Attack.Hit_Through_Walls ?? itemData.m_shared.m_secondaryAttack.m_hitThroughWalls; itemData.m_shared.m_secondaryAttack.m_multiHit = data.Secondary_Attack.Multi_Hit ?? itemData.m_shared.m_secondaryAttack.m_multiHit; itemData.m_shared.m_secondaryAttack.m_pickaxeSpecial = data.Secondary_Attack.Pickaxe_Special ?? itemData.m_shared.m_secondaryAttack.m_pickaxeSpecial; itemData.m_shared.m_secondaryAttack.m_lastChainDamageMultiplier = data.Secondary_Attack.Last_Chain_Dmg_Multiplier ?? itemData.m_shared.m_secondaryAttack.m_lastChainDamageMultiplier; itemData.m_shared.m_secondaryAttack.m_resetChainIfHit = (DestructibleType)(((??)data.Secondary_Attack.Reset_Chain_If_hit) ?? itemData.m_shared.m_secondaryAttack.m_resetChainIfHit); if (!string.IsNullOrEmpty(data.Secondary_Attack.SpawnOnHit)) { string spawnOnHit3 = data.Secondary_Attack.SpawnOnHit; GameObject spawnOnHit4 = itemData.m_shared.m_secondaryAttack.m_spawnOnHit; if (spawnOnHit3 != ((spawnOnHit4 != null) ? ((Object)spawnOnHit4).name : null)) { if (data.Secondary_Attack.SpawnOnHit == "delete" || data.Secondary_Attack.SpawnOnHit == "-") { itemData.m_shared.m_secondaryAttack.m_spawnOnHit = null; } else { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " SpawnOnHit m_secondaryAttack added "); } GameObject val22 = null; try { GameObject[] array5 = AllObjects; foreach (GameObject val23 in array5) { if (((Object)val23).name == data.Secondary_Attack.SpawnOnHit) { if ((Object)(object)val22 == (Object)null) { val22 = val23; } else if (val23.TryGetComponent(ref val24) || val23.TryGetComponent(ref val25)) { val22 = val23; } } } } catch (Exception ex3) { WMRecipeCust.WLog.LogInfo((object)("Error catch " + ex3)); } itemData.m_shared.m_secondaryAttack.m_spawnOnHit = val22 ?? itemData.m_shared.m_secondaryAttack.m_spawnOnHit; } } } itemData.m_shared.m_secondaryAttack.m_spawnOnHitChance = data.Secondary_Attack.SpawnOnHit_Chance ?? itemData.m_shared.m_secondaryAttack.m_spawnOnHitChance; itemData.m_shared.m_secondaryAttack.m_raiseSkillAmount = data.Secondary_Attack.Raise_Skill_Amount ?? itemData.m_shared.m_secondaryAttack.m_raiseSkillAmount; itemData.m_shared.m_secondaryAttack.m_skillHitType = (DestructibleType)(((??)data.Secondary_Attack.Skill_Hit_Type) ?? itemData.m_shared.m_secondaryAttack.m_skillHitType); itemData.m_shared.m_secondaryAttack.m_specialHitSkill = (SkillType)(((??)data.Secondary_Attack.Special_Hit_Skill) ?? itemData.m_shared.m_secondaryAttack.m_specialHitSkill); itemData.m_shared.m_secondaryAttack.m_specialHitType = (DestructibleType)(((??)data.Secondary_Attack.Special_Hit_Type) ?? itemData.m_shared.m_secondaryAttack.m_specialHitType); itemData.m_shared.m_secondaryAttack.m_projectileVel = data.Secondary_Attack.Projectile_Vel ?? itemData.m_shared.m_secondaryAttack.m_projectileVel; itemData.m_shared.m_secondaryAttack.m_projectileAccuracy = data.Secondary_Attack.Projectile_Accuracy ?? data.Secondary_Attack.Projectile_Accuraccy ?? itemData.m_shared.m_secondaryAttack.m_projectileAccuracy; itemData.m_shared.m_secondaryAttack.m_projectileAccuracyMin = data.Secondary_Attack.Projectile_Accuracy_Min ?? itemData.m_shared.m_secondaryAttack.m_projectileAccuracyMin; itemData.m_shared.m_secondaryAttack.m_projectiles = data.Secondary_Attack.Projectiles ?? itemData.m_shared.m_secondaryAttack.m_projectiles; itemData.m_shared.m_secondaryAttack.m_skillAccuracy = data.Secondary_Attack.Skill_Accuracy ?? itemData.m_shared.m_secondaryAttack.m_skillAccuracy; itemData.m_shared.m_secondaryAttack.m_launchAngle = data.Secondary_Attack.Launch_Angle ?? itemData.m_shared.m_secondaryAttack.m_launchAngle; itemData.m_shared.m_secondaryAttack.m_projectileBursts = data.Secondary_Attack.Projectile_Burst ?? itemData.m_shared.m_secondaryAttack.m_projectileBursts; itemData.m_shared.m_secondaryAttack.m_burstInterval = data.Secondary_Attack.Burst_Interval ?? itemData.m_shared.m_secondaryAttack.m_burstInterval; itemData.m_shared.m_secondaryAttack.m_destroyPreviousProjectile = data.Secondary_Attack.Destroy_Previous_Projectile ?? itemData.m_shared.m_secondaryAttack.m_destroyPreviousProjectile; itemData.m_shared.m_secondaryAttack.m_perBurstResourceUsage = data.Secondary_Attack.PerBurst_Resource_usage ?? itemData.m_shared.m_secondaryAttack.m_perBurstResourceUsage; itemData.m_shared.m_secondaryAttack.m_loopingAttack = data.Secondary_Attack.Looping_Attack ?? itemData.m_shared.m_secondaryAttack.m_loopingAttack; itemData.m_shared.m_secondaryAttack.m_consumeItem = data.Secondary_Attack.Consume_Item ?? itemData.m_shared.m_secondaryAttack.m_consumeItem; if (data.Secondary_Attack.AEffects != null) { if (data.Secondary_Attack.AEffects.Hit_Effects != null) { itemData.m_shared.m_secondaryAttack.m_hitEffect = FindEffect(itemData.m_shared.m_secondaryAttack.m_hitEffect, data.Secondary_Attack.AEffects.Hit_Effects); } if (data.Secondary_Attack.AEffects.Hit_Terrain_Effects != null) { itemData.m_shared.m_secondaryAttack.m_hitTerrainEffect = FindEffect(itemData.m_shared.m_secondaryAttack.m_hitTerrainEffect, data.Secondary_Attack.AEffects.Hit_Terrain_Effects); } if (data.Secondary_Attack.AEffects.Start_Effect != null) { itemData.m_shared.m_secondaryAttack.m_startEffect = FindEffect(itemData.m_shared.m_secondaryAttack.m_startEffect, data.Secondary_Attack.AEffects.Start_Effect); } if (data.Secondary_Attack.AEffects.Trigger_Effect != null) { itemData.m_shared.m_secondaryAttack.m_triggerEffect = FindEffect(itemData.m_shared.m_secondaryAttack.m_triggerEffect, data.Secondary_Attack.AEffects.Trigger_Effect); } if (data.Secondary_Attack.AEffects.Trail_Effect != null) { itemData.m_shared.m_secondaryAttack.m_trailStartEffect = FindEffect(itemData.m_shared.m_secondaryAttack.m_trailStartEffect, data.Secondary_Attack.AEffects.Trail_Effect); } if (data.Secondary_Attack.AEffects.Burst_Effect != null) { itemData.m_shared.m_secondaryAttack.m_burstEffect = FindEffect(itemData.m_shared.m_secondaryAttack.m_burstEffect, data.Secondary_Attack.AEffects.Burst_Effect); } } if (data.Secondary_Attack.AEffectsPLUS != null) { if (data.Secondary_Attack.AEffectsPLUS.Hit_Effects.Length != 0) { itemData.m_shared.m_secondaryAttack.m_hitEffect = FindEffect(itemData.m_shared.m_secondaryAttack.m_hitEffect, data.Secondary_Attack.AEffectsPLUS.Hit_Effects); } if (data.Secondary_Attack.AEffectsPLUS.Hit_Terrain_Effects.Length != 0) { itemData.m_shared.m_secondaryAttack.m_hitTerrainEffect = FindEffect(itemData.m_shared.m_secondaryAttack.m_hitTerrainEffect, data.Secondary_Attack.AEffectsPLUS.Hit_Terrain_Effects); } if (data.Secondary_Attack.AEffectsPLUS.Start_Effect.Length != 0) { itemData.m_shared.m_secondaryAttack.m_startEffect = FindEffect(itemData.m_shared.m_secondaryAttack.m_startEffect, data.Secondary_Attack.AEffectsPLUS.Start_Effect); } if (data.Secondary_Attack.AEffectsPLUS.Trigger_Effect.Length != 0) { itemData.m_shared.m_secondaryAttack.m_triggerEffect = FindEffect(itemData.m_shared.m_secondaryAttack.m_triggerEffect, data.Secondary_Attack.AEffectsPLUS.Trigger_Effect); } if (data.Secondary_Attack.AEffectsPLUS.Trail_Effect.Length != 0) { itemData.m_shared.m_secondaryAttack.m_trailStartEffect = FindEffect(itemData.m_shared.m_secondaryAttack.m_trailStartEffect, data.Secondary_Attack.AEffectsPLUS.Trail_Effect); } if (data.Secondary_Attack.AEffectsPLUS.Burst_Effect.Length != 0) { itemData.m_shared.m_secondaryAttack.m_burstEffect = FindEffect(itemData.m_shared.m_secondaryAttack.m_burstEffect, data.Secondary_Attack.AEffectsPLUS.Burst_Effect); } } } if (data.Armor != null) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item armor "); } itemData.m_shared.m_armor = data.Armor.armor ?? itemData.m_shared.m_armor; itemData.m_shared.m_armorPerLevel = data.Armor.armorPerLevel ?? itemData.m_shared.m_armorPerLevel; } if (data.FoodStats != null) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item food "); } itemData.m_shared.m_food = data.FoodStats.m_foodHealth ?? itemData.m_shared.m_food; itemData.m_shared.m_foodStamina = data.FoodStats.m_foodStamina ?? itemData.m_shared.m_foodStamina; itemData.m_shared.m_foodRegen = data.FoodStats.m_foodRegen ?? itemData.m_shared.m_foodRegen; itemData.m_shared.m_foodBurnTime = data.FoodStats.m_foodBurnTime ?? itemData.m_shared.m_foodBurnTime; itemData.m_shared.m_foodEitr = data.FoodStats.m_FoodEitr ?? itemData.m_shared.m_foodEitr; itemData.m_shared.m_foodEatAnimTime = data.FoodStats.eatAnimationTime ?? itemData.m_shared.m_foodEatAnimTime; itemData.m_shared.m_isDrink = data.FoodStats.isDrink ?? itemData.m_shared.m_isDrink; if (val5.TryGetComponent(ref val26)) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" Feast Found, Complicated Setting, Setting Feast _Material at same time"); } val26.m_eatStacks = data.FoodStats.feastStacks ?? val26.m_eatStacks; int prefabHash = ZNetScene.instance.GetPrefabHash(val5); ItemData itemData2 = ZNetScene.instance.GetPrefab(prefabHash).GetComponent().m_itemData; itemData2.m_shared.m_food = data.FoodStats.m_foodHealth ?? itemData.m_shared.m_food; itemData2.m_shared.m_foodStamina = data.FoodStats.m_foodStamina ?? itemData.m_shared.m_foodStamina; itemData2.m_shared.m_foodRegen = data.FoodStats.m_foodRegen ?? itemData.m_shared.m_foodRegen; itemData2.m_shared.m_foodBurnTime = data.FoodStats.m_foodBurnTime ?? itemData.m_shared.m_foodBurnTime; itemData2.m_shared.m_foodEitr = data.FoodStats.m_FoodEitr ?? itemData.m_shared.m_foodEitr; SharedData shared = Instant.GetItemPrefab(((Object)val5).name + "_Material").GetComponent().m_itemData.m_shared; itemData2.m_shared.m_name = data.m_name; shared.m_description = data.m_description; shared.m_maxStackSize = data.m_maxStackSize ?? shared.m_maxStackSize; shared.m_weight = data.m_weight; shared.m_appendToolTip = val5.GetComponent(); shared.m_food = 0f; shared.m_foodStamina = 0f; shared.m_foodRegen = 0f; shared.m_foodBurnTime = 0f; shared.m_foodEitr = 0f; shared.m_itemType = (ItemType)1; if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" Finished Feast _Material"); } break; } } if (data.Moddifiers != null) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item movement "); } itemData.m_shared.m_movementModifier = data.Moddifiers.m_movementModifier ?? itemData.m_shared.m_movementModifier; itemData.m_shared.m_eitrRegenModifier = data.Moddifiers.m_EitrRegen ?? itemData.m_shared.m_eitrRegenModifier; itemData.m_shared.m_homeItemsStaminaModifier = data.Moddifiers.m_homeItemsStaminaModifier ?? itemData.m_shared.m_homeItemsStaminaModifier; itemData.m_shared.m_heatResistanceModifier = data.Moddifiers.m_heatResistanceModifier ?? itemData.m_shared.m_heatResistanceModifier; itemData.m_shared.m_jumpStaminaModifier = data.Moddifiers.m_jumpStaminaModifier ?? itemData.m_shared.m_jumpStaminaModifier; itemData.m_shared.m_attackStaminaModifier = data.Moddifiers.m_attackStaminaModifier ?? itemData.m_shared.m_attackStaminaModifier; itemData.m_shared.m_blockStaminaModifier = data.Moddifiers.m_blockStaminaModifier ?? itemData.m_shared.m_blockStaminaModifier; itemData.m_shared.m_dodgeStaminaModifier = data.Moddifiers.m_dodgeStaminaModifier ?? itemData.m_shared.m_dodgeStaminaModifier; itemData.m_shared.m_swimStaminaModifier = data.Moddifiers.m_swimStaminaModifier ?? itemData.m_shared.m_swimStaminaModifier; itemData.m_shared.m_sneakStaminaModifier = data.Moddifiers.m_sneakStaminaModifier ?? itemData.m_shared.m_sneakStaminaModifier; itemData.m_shared.m_runStaminaModifier = data.Moddifiers.m_runStaminaModifier ?? itemData.m_shared.m_runStaminaModifier; } if (data.SE_Equip != null) { if (data.SE_Equip.EffectName == "delete" || data.SE_Equip.EffectName == "-") { itemData.m_shared.m_equipStatusEffect = null; if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item equip effects removed"); } } else { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item equip effects "); } itemData.m_shared.m_equipStatusEffect = Instant.GetStatusEffect(StringExtensionMethods.GetStableHashCode(data.SE_Equip.EffectName)) ?? itemData.m_shared.m_equipStatusEffect; } } if (data.SE_SET_Equip != null) { if (data.SE_SET_Equip.EffectName == "delete" || data.SE_SET_Equip.EffectName == "-") { itemData.m_shared.m_setName = null; itemData.m_shared.m_setSize = 0; itemData.m_shared.m_setStatusEffect = null; if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item seteffects removed"); } } else { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item seteffects "); } itemData.m_shared.m_setName = data.SE_SET_Equip.SetName ?? itemData.m_shared.m_setName; itemData.m_shared.m_setSize = data.SE_SET_Equip.Size ?? itemData.m_shared.m_setSize; itemData.m_shared.m_setStatusEffect = Instant.GetStatusEffect(StringExtensionMethods.GetStableHashCode(data.SE_SET_Equip.EffectName)) ?? itemData.m_shared.m_setStatusEffect; } } if (data.ShieldStats != null) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item block "); } itemData.m_shared.m_blockPower = data.ShieldStats.m_blockPower ?? itemData.m_shared.m_blockPower; itemData.m_shared.m_blockPowerPerLevel = data.ShieldStats.m_blockPowerPerLevel ?? itemData.m_shared.m_blockPowerPerLevel; itemData.m_shared.m_timedBlockBonus = data.ShieldStats.m_timedBlockBonus ?? itemData.m_shared.m_timedBlockBonus; itemData.m_shared.m_deflectionForce = data.ShieldStats.m_deflectionForce ?? itemData.m_shared.m_deflectionForce; itemData.m_shared.m_deflectionForcePerLevel = data.ShieldStats.m_deflectionForcePerLevel ?? itemData.m_shared.m_deflectionForcePerLevel; if (data.ShieldStats.m_perfectBlockStatusEffect != null) { itemData.m_shared.m_perfectBlockStatusEffect = ((data.ShieldStats.m_perfectBlockStatusEffect == "delete") ? null : (Instant.GetStatusEffect(StringExtensionMethods.GetStableHashCode(data.ShieldStats.m_perfectBlockStatusEffect)) ?? itemData.m_shared.m_perfectBlockStatusEffect)); } itemData.m_shared.m_buildBlockCharges = data.ShieldStats.m_buildBlockCharges ?? itemData.m_shared.m_buildBlockCharges; itemData.m_shared.m_maxBlockCharges = data.ShieldStats.m_maxBlockCharges ?? itemData.m_shared.m_maxBlockCharges; itemData.m_shared.m_blockChargeDecayTime = data.ShieldStats.m_blockChargeDecayTime ?? itemData.m_shared.m_blockChargeDecayTime; } if (data.AdrenalineStats != null) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item Adrenaline "); } itemData.m_shared.m_maxAdrenaline = data.AdrenalineStats.maxAdrenaline ?? itemData.m_shared.m_maxAdrenaline; if ((Object)(object)itemData.m_shared.m_fullAdrenalineSE != (Object)null) { itemData.m_shared.m_fullAdrenalineSE = ((data.AdrenalineStats.fullAdrenalineSE == "delete") ? null : (Instant.GetStatusEffect(StringExtensionMethods.GetStableHashCode(data.AdrenalineStats.fullAdrenalineSE)) ?? itemData.m_shared.m_fullAdrenalineSE)); } itemData.m_shared.m_blockAdrenaline = data.AdrenalineStats.blockAdrenaline ?? itemData.m_shared.m_blockAdrenaline; itemData.m_shared.m_perfectBlockAdrenaline = data.AdrenalineStats.perfectBlockAdrenaline ?? itemData.m_shared.m_perfectBlockAdrenaline; } itemData.m_shared.m_maxStackSize = data.m_maxStackSize ?? itemData.m_shared.m_maxStackSize; itemData.m_shared.m_canBeReparied = data.m_canBeReparied ?? itemData.m_shared.m_canBeReparied; itemData.m_shared.m_destroyBroken = data.m_destroyBroken ?? itemData.m_shared.m_destroyBroken; itemData.m_shared.m_dodgeable = data.m_dodgeable ?? itemData.m_shared.m_dodgeable; itemData.m_shared.m_blockable = data.blockable ?? itemData.m_shared.m_blockable; itemData.m_shared.m_questItem = data.m_questItem ?? itemData.m_shared.m_questItem; itemData.m_shared.m_teleportable = data.m_teleportable ?? itemData.m_shared.m_teleportable; itemData.m_shared.m_backstabBonus = data.m_backstabbonus ?? itemData.m_shared.m_backstabBonus; itemData.m_shared.m_attackForce = data.m_knockback ?? itemData.m_shared.m_attackForce; if (data.Attack_status_effect != null) { if (data.Attack_status_effect == "delete") { itemData.m_shared.m_attackStatusEffect = null; } else { itemData.m_shared.m_attackStatusEffect = Instant.GetStatusEffect(StringExtensionMethods.GetStableHashCode(data.Attack_status_effect)) ?? itemData.m_shared.m_attackStatusEffect; } } itemData.m_shared.m_attackStatusEffectChance = data.Attack_status_effect_chance ?? itemData.m_shared.m_attackStatusEffectChance; bool flag4 = false; if (!string.IsNullOrEmpty(data.Primary_Attack?.Attack_status_effect)) { flag4 = true; } if (!string.IsNullOrEmpty(data.Secondary_Attack?.Attack_status_effect)) { flag4 = true; } if (flag4) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item Attack_status_effect "); } WMRecipeCust.SEWeaponChoice.Add(data.name, new Tuple(data.Primary_Attack.Attack_status_effect ?? "", data.Primary_Attack.Attack_status_effect_chance.GetValueOrDefault(), data.Secondary_Attack.Attack_status_effect ?? "", data.Secondary_Attack.Attack_status_effect_chance.GetValueOrDefault())); } if (!string.IsNullOrEmpty(data.spawn_on_hit)) { string spawn_on_hit = data.spawn_on_hit; GameObject spawnOnHit5 = itemData.m_shared.m_spawnOnHit; if (spawn_on_hit != ((spawnOnHit5 != null) ? ((Object)spawnOnHit5).name : null)) { if (data.spawn_on_hit == "delete") { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " SpawnOnHit deleted "); } itemData.m_shared.m_spawnOnHit = null; } else { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " SpawnOnHit Main added "); } GameObject val27 = null; try { GameObject[] array5 = AllObjects; foreach (GameObject val28 in array5) { if (((Object)val28).name == data.spawn_on_hit) { if ((Object)(object)val27 == (Object)null) { val27 = val28; } else if (val28.TryGetComponent(ref val29) || val28.TryGetComponent(ref val30)) { val27 = val28; } } } } catch (Exception ex4) { WMRecipeCust.WLog.LogInfo((object)("Error catch " + ex4)); } itemData.m_shared.m_spawnOnHit = val27 ?? itemData.m_shared.m_spawnOnHit; } } } if (!string.IsNullOrEmpty(data.spawn_on_terrain_hit)) { string spawn_on_terrain_hit = data.spawn_on_terrain_hit; GameObject spawnOnHitTerrain = itemData.m_shared.m_spawnOnHitTerrain; if (spawn_on_terrain_hit != ((spawnOnHitTerrain != null) ? ((Object)spawnOnHitTerrain).name : null)) { if (data.spawn_on_terrain_hit == "delete") { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " spawn_on_terrain_hit deleted "); } itemData.m_shared.m_spawnOnHitTerrain = null; } else { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " SpawnOnHitTerrain added "); } GameObject val31 = null; GameObject[] array5 = AllObjects; foreach (GameObject val32 in array5) { if (((Object)val32).name == data.spawn_on_terrain_hit) { if ((Object)(object)val31 == (Object)null) { val31 = val32; } else if (val32.TryGetComponent(ref val33) || val32.TryGetComponent(ref val34)) { val31 = val32; } } } itemData.m_shared.m_spawnOnHitTerrain = val31 ?? itemData.m_shared.m_spawnOnHitTerrain; } } } itemData.m_shared.m_useDurability = data.m_useDurability ?? itemData.m_shared.m_useDurability; itemData.m_shared.m_useDurabilityDrain = data.m_useDurabilityDrain ?? itemData.m_shared.m_useDurabilityDrain; itemData.m_shared.m_durabilityDrain = data.m_durabilityDrain ?? itemData.m_shared.m_durabilityDrain; itemData.m_shared.m_maxDurability = data.m_maxDurability ?? itemData.m_shared.m_maxDurability; itemData.m_shared.m_durabilityPerLevel = data.m_durabilityPerLevel ?? itemData.m_shared.m_durabilityPerLevel; itemData.m_shared.m_equipDuration = data.m_equipDuration ?? itemData.m_shared.m_equipDuration; itemData.m_shared.m_skillType = (SkillType)(((??)data.m_skillType) ?? itemData.m_shared.m_skillType); itemData.m_shared.m_animationState = (AnimationState)(((??)data.m_animationState) ?? itemData.m_shared.m_animationState); itemData.m_shared.m_itemType = (ItemType)(((??)data.m_itemType) ?? itemData.m_shared.m_itemType); itemData.m_shared.m_attachOverride = (ItemType)(((??)data.Attach_Override) ?? itemData.m_shared.m_attachOverride); itemData.m_shared.m_toolTier = data.m_toolTier ?? itemData.m_shared.m_toolTier; itemData.m_shared.m_maxQuality = data.m_maxQuality ?? itemData.m_shared.m_maxQuality; itemData.m_shared.m_value = data.m_value ?? itemData.m_shared.m_value; if (data.GEffects != null) { if (data.GEffects.Hit_Effects != null) { itemData.m_shared.m_hitEffect = FindEffect(itemData.m_shared.m_hitEffect, data.GEffects.Hit_Effects, "m_hitEffect"); } if (data.GEffects.Hit_Terrain_Effects != null) { itemData.m_shared.m_hitTerrainEffect = FindEffect(itemData.m_shared.m_hitTerrainEffect, data.GEffects.Hit_Terrain_Effects, "m_hitTerrainEffect"); } if (data.GEffects.Start_Effect != null) { itemData.m_shared.m_startEffect = FindEffect(itemData.m_shared.m_startEffect, data.GEffects.Start_Effect, "m_startEffect"); } if (data.GEffects.Hold_Start_Effects != null) { itemData.m_shared.m_holdStartEffect = FindEffect(itemData.m_shared.m_holdStartEffect, data.GEffects.Hold_Start_Effects, "m_holdStartEffect"); } if (data.GEffects.Trigger_Effect != null) { itemData.m_shared.m_triggerEffect = FindEffect(itemData.m_shared.m_triggerEffect, data.GEffects.Trigger_Effect, "m_triggerEffect"); } if (data.GEffects.Trail_Effect != null) { itemData.m_shared.m_trailStartEffect = FindEffect(itemData.m_shared.m_trailStartEffect, data.GEffects.Trail_Effect, "m_trailStartEffect"); } } if (data.GEffectsPLUS != null) { if (data.GEffectsPLUS.Hit_Effects.Length != 0) { itemData.m_shared.m_hitEffect = FindEffect(itemData.m_shared.m_hitEffect, data.GEffectsPLUS.Hit_Effects, "m_hitEffect"); } if (data.GEffectsPLUS.Hit_Terrain_Effects.Length != 0) { itemData.m_shared.m_hitTerrainEffect = FindEffect(itemData.m_shared.m_hitTerrainEffect, data.GEffectsPLUS.Hit_Terrain_Effects, "m_hitTerrainEffect"); } if (data.GEffectsPLUS.Start_Effect.Length != 0) { itemData.m_shared.m_startEffect = FindEffect(itemData.m_shared.m_startEffect, data.GEffectsPLUS.Start_Effect, "m_startEffect"); } if (data.GEffectsPLUS.Hold_Start_Effects.Length != 0) { itemData.m_shared.m_holdStartEffect = FindEffect(itemData.m_shared.m_holdStartEffect, data.GEffectsPLUS.Hold_Start_Effects, "m_holdStartEffect"); } if (data.GEffectsPLUS.Trigger_Effect.Length != 0) { itemData.m_shared.m_triggerEffect = FindEffect(itemData.m_shared.m_triggerEffect, data.GEffectsPLUS.Trigger_Effect, "m_triggerEffect"); } if (data.GEffectsPLUS.Trail_Effect.Length != 0) { itemData.m_shared.m_trailStartEffect = FindEffect(itemData.m_shared.m_trailStartEffect, data.GEffectsPLUS.Trail_Effect, "m_trailStartEffect"); } } if (!DataHelpers.ECheck(data.damageModifiers)) { itemData.m_shared.m_damageModifiers.Clear(); if (data.damageModifiers[0] == "-" || data.damageModifiers[0] == "delete" || data.damageModifiers[0] == " -") { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" clearing dmg Modifiers"); } } else { foreach (string damageModifier in data.damageModifiers) { string[] array6 = damageModifier.Split(new char[1] { ':' }); ArmorHelpers.NewDamageTypes result2; int num3 = (Enum.TryParse(array6[0], out result2) ? ((int)result2) : ((int)Enum.Parse(typeof(DamageType), array6[0]))); itemData.m_shared.m_damageModifiers.Add(new DamageModPair { m_type = (DamageType)num3, m_modifier = (DamageModifier)Enum.Parse(typeof(DamageModifier), array6[1]) }); } } } if (itemData.m_shared.m_value > 0) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item value " + itemData.m_shared.m_value); } string text2 = " Valuable"; itemData.m_shared.m_description = data.m_description + text2; } if (data.ConsumableStatusEffect != null) { if (data.ConsumableStatusEffect == "delete") { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item ConsumeEffect removed "); } itemData.m_shared.m_consumeStatusEffect = null; } else { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item ConsumableStatusEffect added "); } itemData.m_shared.m_consumeStatusEffect = Instant.GetStatusEffect(StringExtensionMethods.GetStableHashCode(data.ConsumableStatusEffect)) ?? itemData.m_shared.m_consumeStatusEffect; } } if (data.AppendToolTip == null || val5.TryGetComponent(ref val35)) { break; } if (data.AppendToolTip == "delete") { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item AppendToolTip removed "); } itemData.m_shared.m_appendToolTip = null; } else { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" " + data.name + " Item AppendToolTip added "); } itemData.m_shared.m_appendToolTip = Instant.GetItemPrefab(data.AppendToolTip).GetComponent() ?? itemData.m_shared.m_appendToolTip; } break; } } private static GameObject GetEffectPrefab(string name) { if (string.IsNullOrEmpty(name)) { return null; } if (WMRecipeCust.originalVFX.TryGetValue(name, out var value)) { return value; } if (WMRecipeCust.originalSFX.TryGetValue(name, out var value2)) { return value2; } if (WMRecipeCust.originalFX.TryGetValue(name, out var value3)) { return value3; } if (WMRecipeCust.extraEffects.TryGetValue(name, out var value4)) { return value4; } return null; } private static EffectList FindEffect(EffectList current, EffectVerse[] userlist, string name = "") { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_007b: 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_00a0: 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_00c4: 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_00e8: 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_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Expected O, but got Unknown if (userlist == null || userlist.Length == 0 || userlist[0] == null) { return current; } EffectList val = new EffectList(); List list = new List(); foreach (EffectVerse effectVerse in userlist) { if (effectVerse != null && !string.IsNullOrEmpty(effectVerse.name)) { GameObject effectPrefab = GetEffectPrefab(effectVerse.name); if ((Object)(object)effectPrefab != (Object)null) { EffectData item = new EffectData { m_prefab = effectPrefab, m_enabled = effectVerse.m_enabled.GetValueOrDefault(true), m_variant = effectVerse.m_variant.GetValueOrDefault(-1), m_attach = effectVerse.m_attach.GetValueOrDefault(), m_follow = effectVerse.m_follow.GetValueOrDefault(), m_inheritParentRotation = effectVerse.m_inheritParentRotation.GetValueOrDefault(), m_inheritParentScale = effectVerse.m_inheritParentScale.GetValueOrDefault(), m_multiplyParentVisualScale = effectVerse.m_multiplyParentVisualScale.GetValueOrDefault(), m_randomRotation = effectVerse.m_randomRotation.GetValueOrDefault(), m_scale = effectVerse.m_scale.GetValueOrDefault(), m_childTransform = (effectVerse.m_childTransform ?? "") }; list.Add(item); } else { WMRecipeCust.WLog.LogError((object)("Didn't find effect " + effectVerse.name + " This will cause an error when the effect is used - please remove")); } } } val.m_effectPrefabs = list.ToArray(); return val; } private static EffectList FindEffect(EffectList current, string[] userlist, string name = "") { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Expected O, but got Unknown try { if (userlist == null || userlist.Length == 0 || userlist[0] == null) { return new EffectList(); } if (current == null) { current = new EffectList(); } List list = new List(); List list2 = userlist.ToList(); if (current.m_effectPrefabs != null) { EffectData[] effectPrefabs = current.m_effectPrefabs; foreach (EffectData val in effectPrefabs) { if ((Object)(object)val.m_prefab != (Object)null && list2.Contains(((Object)val.m_prefab).name)) { val.m_enabled = true; list.Add(val); list2.Remove(((Object)val.m_prefab).name); } } } foreach (string item in list2) { GameObject effectPrefab = GetEffectPrefab(item); if ((Object)(object)effectPrefab != (Object)null) { list.Add(new EffectData { m_prefab = effectPrefab, m_enabled = true, m_childTransform = "", m_follow = true }); } else { WMRecipeCust.WLog.LogError((object)("Didn't find effect " + item + " This will cause an error when the effect is used - please remove")); } } current.m_effectPrefabs = list.ToArray(); return current; } catch (Exception ex) { WMRecipeCust.WLog.LogWarning((object)("Effect " + name + " had problems " + ex.Message)); return current; } } internal static void SetCreature(CreatureData data, GameObject[] arrayCreature) { int num = 0; GameObject val = null; GameObject val2 = null; bool flag = false; bool flag2 = false; foreach (string item in WMRecipeCust.ClonedC) { if (item == data.name) { flag = true; } } foreach (string item2 in WMRecipeCust.ClonedCR) { if (item2 == data.name) { flag2 = true; } } Humanoid val4 = default(Humanoid); AnimalAI val5 = default(AnimalAI); MonsterAI val6 = default(MonsterAI); Humanoid val7 = default(Humanoid); AnimalAI val8 = default(AnimalAI); MonsterAI val9 = default(MonsterAI); Humanoid val11 = default(Humanoid); Humanoid val12 = default(Humanoid); foreach (GameObject val3 in arrayCreature) { if (data.clone_creature != null && !flag && ((Object)val3).name == data.clone_creature && (val3.TryGetComponent(ref val4) || val3.TryGetComponent(ref val5) || val3.TryGetComponent(ref val6))) { val2 = Object.Instantiate(val3, WMRecipeCust.Root.transform, false); ((Object)val2).name = data.name; ((Object)val2.GetComponent()).name = data.name; Humanoid component = val2.GetComponent(); ZNetScene instance = ZNetScene.instance; if (Object.op_Implicit((Object)(object)instance)) { string name = ((Object)val2).name; int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)val2).name); if (instance.m_namedPrefabs.ContainsKey(stableHashCode)) { WMRecipeCust.WLog.LogWarning((object)("Prefab " + name + " already in ZNetScene")); } else { if ((Object)(object)val2.GetComponent() != (Object)null) { instance.m_prefabs.Add(val2); } else { instance.m_nonNetViewPrefabs.Add(val2); } instance.m_namedPrefabs.Add(stableHashCode, val2); if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Added cloned Creature " + name); } } } ((Character)component).m_name = data.mob_display_name; WMRecipeCust.ClonedC.Add(data.name); WMRecipeCust.ClonedCC.Add(data.name, val2); } if (((Object)val3).name == data.name && (val3.TryGetComponent(ref val7) || val3.TryGetComponent(ref val8) || val3.TryGetComponent(ref val9)) && data.creature_replacer != null && !flag2) { foreach (GameObject val10 in arrayCreature) { if (!(((Object)val10).name == data.creature_replacer) || !val10.TryGetComponent(ref val11)) { continue; } val3.SetActive(false); _ = val3.gameObject; val = Object.Instantiate(val10, WMRecipeCust.Root.transform, false); ((Object)val).name = data.name; val3.GetComponent(); val.GetComponent(); ((Character)val.GetComponent()).m_name = data.mob_display_name; ZNetScene instance2 = ZNetScene.instance; if (Object.op_Implicit((Object)(object)instance2)) { string name2 = ((Object)val).name; int stableHashCode2 = StringExtensionMethods.GetStableHashCode(((Object)val).name); if (instance2.m_namedPrefabs.ContainsKey(stableHashCode2)) { WMRecipeCust.Dbgl("Prefab " + name2 + " already in ZNetScene"); instance2.m_namedPrefabs.Remove(stableHashCode2); instance2.m_prefabs.Remove(val3); instance2.m_prefabs.Add(val); instance2.m_namedPrefabs.Add(stableHashCode2, val); WMRecipeCust.Dbgl("Removed old " + name2 + " and replaced prefab with " + ((Object)val10).name); } } WMRecipeCust.ClonedCR.Add(data.name); } } if (((Object)val3).name == data.name && val3.TryGetComponent(ref val12)) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Updating " + data.name + " info"); } ((Character)val12).m_name = data.mob_display_name; } num++; } } internal static void SetPickables(PickableData data, Pickable[] array, ObjectDB Instant) { //IL_06c4: Unknown result type (might be due to invalid IL or missing references) //IL_0696: Unknown result type (might be due to invalid IL or missing references) //IL_0666: Unknown result type (might be due to invalid IL or missing references) //IL_0561: Unknown result type (might be due to invalid IL or missing references) //IL_057d: Unknown result type (might be due to invalid IL or missing references) bool flag = false; foreach (string item2 in WMRecipeCust.ClonedPI) { if (item2 == data.name) { flag = true; } } string name = data.name; if (!string.IsNullOrEmpty(data.cloneOfWhatPickable) && !flag) { data.name = data.cloneOfWhatPickable; } Pickable val = null; foreach (Pickable val2 in array) { if (!((Object)val2).name.Contains("Clone") && ((Object)val2).name == data.name) { val = val2; break; } } if ((Object)(object)val == (Object)null) { WMRecipeCust.WLog.LogWarning((object)("Pickable is null " + data.name)); return; } if (!string.IsNullOrEmpty(data.cloneOfWhatPickable) && !flag) { if (WMRecipeCust.BlacklistClone.Contains(data.cloneOfWhatPickable)) { WMRecipeCust.Dbgl("Can not clone " + data.cloneOfWhatPickable + " "); return; } if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Pickable being set " + name + " is CLONE of " + data.cloneOfWhatPickable); } Transform transform = WMRecipeCust.Root.transform; GameObject val3 = Object.Instantiate(((Component)val).gameObject, transform, false); Pickable component = val3.GetComponent(); WMRecipeCust.ClonedPI.Add(name); ((Object)val3).name = name; ((Object)component).name = name; data.name = name; if (!WMRecipeCust.ClonedPrefabsMap.ContainsKey(name)) { WMRecipeCust.ClonedPrefabsMap.Add(name, data.cloneOfWhatPickable); } int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)val3).name); ZNetScene instance = ZNetScene.instance; if (Object.op_Implicit((Object)(object)instance)) { string name2 = ((Object)val3).name; if (instance.m_namedPrefabs.ContainsKey(stableHashCode)) { WMRecipeCust.Dbgl("Prefab " + name2 + " already in ZNetScene"); } else { if ((Object)(object)val3.GetComponent() != (Object)null) { instance.m_prefabs.Add(val3); } else { instance.m_nonNetViewPrefabs.Add(val3); } instance.m_namedPrefabs.Add(stableHashCode, val3); if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Added prefab " + name2); } } } val = component; } else if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Pickable being set " + name); } if (!string.IsNullOrEmpty(data.material)) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Material name searching for " + data.material + " for pickable " + data.name); } try { renderfinder = ((Component)val).GetComponentsInChildren(); renderfinder2 = ((Component)val).GetComponentsInChildren(true); if (data.material.Contains("same_mat") || data.material.Contains("no_wear")) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("No Wear set for " + data.name); } Renderer[] array2 = renderfinder; foreach (Renderer val4 in array2) { if (val4.receiveShadows) { _ = val4.sharedMaterial; break; } } } else { Material m = WMRecipeCust.originalMaterials[data.material]; Renderer[] array2 = renderfinder2; foreach (Renderer val5 in array2) { if (val5.receiveShadows) { PrefabAssistant.UpdateMaterialReference(val5, m); } } } } catch { WMRecipeCust.WLog.LogWarning((object)"Material was not found or was not set correctly"); } } val.m_itemPrefab = Instant.GetItemPrefab(data.itemPrefab) ?? val.m_itemPrefab; if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl(" ItemPrefab set to " + ((Object)val.m_itemPrefab).name); } val.m_amount = data.amount ?? val.m_amount; if (!string.IsNullOrEmpty(data.overrideName)) { val.m_overrideName = data.overrideName ?? val.m_overrideName; } val.m_respawnTimeMinutes = data.respawnTimer ?? val.m_respawnTimeMinutes; val.m_spawnOffset = data.spawnOffset ?? val.m_spawnOffset; if (data.extraDrops != null) { DropTable extraDrops = val.m_extraDrops; extraDrops.m_dropMin = data.extraDrops.dropMin ?? extraDrops.m_dropMin; extraDrops.m_dropMax = data.extraDrops.dropMax ?? extraDrops.m_dropMax; extraDrops.m_dropChance = data.extraDrops.dropChance ?? extraDrops.m_dropChance; extraDrops.m_oneOfEach = data.extraDrops.dropOneOfEach ?? extraDrops.m_oneOfEach; extraDrops.m_drops.Clear(); foreach (string drop in data.extraDrops.drops) { DropData item = default(DropData); item.m_item = Instant.GetItemPrefab(drop); extraDrops.m_drops.Add(item); } } if (data.size != null) { List list = data.size.Split(new char[1] { '|' }).ToList(); int count = list.Count; List list2 = new List(); foreach (string item3 in list) { item3.Replace(",", "."); if (float.TryParse(item3, NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out var result)) { list2.Add(result); } } switch (count) { case 1: if (list2[0] != 1f) { Vector3 localScale3 = default(Vector3); ((Vector3)(ref localScale3))..ctor(list2[0], list2[0], list2[0]); ((Component)val).gameObject.transform.localScale = localScale3; } break; case 2: { Vector3 localScale2 = default(Vector3); ((Vector3)(ref localScale2))..ctor(list2[0], list2[1], 1f); ((Component)val).transform.localScale = localScale2; break; } default: { Vector3 localScale = default(Vector3); ((Vector3)(ref localScale))..ctor(list2[0], list2[1], list2[2]); ((Component)val).transform.localScale = localScale; break; } } } Destructible val6 = default(Destructible); if (((Component)val).TryGetComponent(ref val6)) { val6.m_health = data.ifHasHealth ?? val6.m_health; } if (!string.IsNullOrEmpty(data.hiddenChildWhenPicked)) { Transform val7 = ((Component)val).gameObject.transform.FindChild(data.hiddenChildWhenPicked); if ((Object)(object)val7 != (Object)null) { val.m_hideWhenPicked = ((Component)val7).gameObject; } } } internal static void SetTreeBase(TreeBaseData data, TreeBase[] array) { //IL_04b5: Unknown result type (might be due to invalid IL or missing references) //IL_0488: Unknown result type (might be due to invalid IL or missing references) //IL_0459: Unknown result type (might be due to invalid IL or missing references) bool flag = false; foreach (string item in WMRecipeCust.ClonedPTB) { if (item == data.name) { flag = true; } } string name = data.name; if (!string.IsNullOrEmpty(data.cloneOfWhatTree) && !flag) { data.name = data.cloneOfWhatTree; } TreeBase val = null; foreach (TreeBase val2 in array) { if (!((Object)val2).name.Contains("Clone") && ((Object)val2).name == data.name) { val = val2; break; } } if ((Object)(object)val == (Object)null) { WMRecipeCust.WLog.LogWarning((object)("Tree is null " + data.name)); return; } if (!string.IsNullOrEmpty(data.cloneOfWhatTree) && !flag) { if (WMRecipeCust.BlacklistClone.Contains(data.cloneOfWhatTree)) { WMRecipeCust.Dbgl("Can not clone " + data.cloneOfWhatTree + " "); return; } if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Tree being set " + name + " is CLONE of " + data.cloneOfWhatTree); } Transform transform = WMRecipeCust.Root.transform; GameObject val3 = Object.Instantiate(((Component)val).gameObject, transform, false); TreeBase component = val3.GetComponent(); WMRecipeCust.ClonedPTB.Add(name); ((Object)val3).name = name; ((Object)component).name = name; data.name = name; if (!WMRecipeCust.ClonedPrefabsMap.ContainsKey(name)) { WMRecipeCust.ClonedPrefabsMap.Add(name, data.cloneOfWhatTree); } int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)val3).name); ZNetScene instance = ZNetScene.instance; if (Object.op_Implicit((Object)(object)instance)) { string name2 = ((Object)val3).name; if (instance.m_namedPrefabs.ContainsKey(stableHashCode)) { WMRecipeCust.Dbgl("Prefab " + name2 + " already in ZNetScene"); } else { if ((Object)(object)val3.GetComponent() != (Object)null) { instance.m_prefabs.Add(val3); } else { instance.m_nonNetViewPrefabs.Add(val3); } instance.m_namedPrefabs.Add(stableHashCode, val3); WMRecipeCust.Dbgl("Added prefab " + name2); } } val = component; } if (!string.IsNullOrEmpty(data.material)) { if (WMRecipeCust.showLogs.Value) { WMRecipeCust.Dbgl("Material name searching for " + data.material + " for pickable " + data.name); } try { renderfinder = ((Component)val).GetComponentsInChildren(); renderfinder2 = ((Component)val).GetComponentsInChildren(true); if (data.material.Contains("same_mat") || data.material.Contains("no_wear")) { WMRecipeCust.Dbgl("No Wear set for " + data.name); Renderer[] array2 = renderfinder; foreach (Renderer val4 in array2) { if (val4.receiveShadows) { _ = val4.sharedMaterial; break; } } } else { Material m = WMRecipeCust.originalMaterials[data.material]; Renderer[] array2 = renderfinder2; foreach (Renderer val5 in array2) { if (val5.receiveShadows) { PrefabAssistant.UpdateMaterialReference(val5, m); } } } } catch { WMRecipeCust.WLog.LogWarning((object)"Material was not found or was not set correctly"); } } val.m_health = data.treeHealth; val.m_minToolTier = data.minToolTier ?? val.m_minToolTier; if (data.size == null) { return; } List list = data.size.Split(new char[1] { '|' }).ToList(); int count = list.Count; List list2 = new List(); foreach (string item2 in list) { item2.Replace(",", "."); if (float.TryParse(item2, NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out var result)) { list2.Add(result); } } switch (count) { case 1: if (list2[0] != 1f) { Vector3 localScale3 = default(Vector3); ((Vector3)(ref localScale3))..ctor(list2[0], list2[0], list2[0]); ((Component)val).gameObject.transform.localScale = localScale3; } break; case 2: { Vector3 localScale2 = default(Vector3); ((Vector3)(ref localScale2))..ctor(list2[0], list2[1], 1f); ((Component)val).transform.localScale = localScale2; break; } default: { Vector3 localScale = default(Vector3); ((Vector3)(ref localScale))..ctor(list2[0], list2[1], list2[2]); ((Component)val).transform.localScale = localScale; break; } } } } internal class WeaponDamage { [NullableContext(1)] public static DamageTypes ParseDamageTypes(WDamages dmg) { //IL_0002: 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) DamageTypes result = default(DamageTypes); result.m_blunt = dmg.Blunt; result.m_chop = dmg.Chop; result.m_damage = dmg.Damage; result.m_fire = dmg.Fire; result.m_frost = dmg.Frost; result.m_lightning = dmg.Lightning; result.m_pickaxe = dmg.Pickaxe; result.m_pierce = dmg.Pierce; result.m_poison = dmg.Poison; result.m_slash = dmg.Slash; result.m_spirit = dmg.Spirit; return result; } } } namespace wackydatabase.PatchClasses { [HarmonyPatch(typeof(Player), "QueueReloadAction")] internal static class AddStaminaReloadCheck { [NullableContext(1)] public static bool Prefix(Player __instance) { if (!__instance.IsReloadActionQueued() && ((Character)__instance).IsPlayer()) { ItemData currentWeapon = ((Humanoid)__instance).GetCurrentWeapon(); if (currentWeapon != null && currentWeapon.m_shared.m_attack.m_requiresReload && currentWeapon.m_shared.m_attack.m_reloadStaminaDrain > 0f) { if (((Character)__instance).HaveStamina(currentWeapon.m_shared.m_attack.m_reloadStaminaDrain)) { return true; } Hud.instance.StaminaBarEmptyFlash(); return false; } } return true; } } [HarmonyPatch(typeof(Attack), "ModifyDamage")] internal static class ModifyDamageWM { [NullableContext(1)] public static void Postfix(ref HitData hitData, Attack __instance) { if (!((Character)__instance.m_character).IsPlayer() || (__instance.m_character.m_rightItem == null && __instance.m_character.m_leftItem == null)) { return; } ItemData weapon = __instance.m_weapon; object obj; if (weapon == null) { obj = null; } else { GameObject dropPrefab = weapon.m_dropPrefab; obj = ((dropPrefab != null) ? ((Object)dropPrefab).name : null); } if (obj == null || !WMRecipeCust.SEWeaponChoice.TryGetValue(((Object)__instance.m_weapon.m_dropPrefab).name, out var value)) { return; } if (__instance.m_character.m_currentAttackIsSecondary) { if (value.Item3 != "" && value.Item4 != 0f && Random.Range(0f, 1f) < value.Item4) { hitData.m_statusEffectHash = StringExtensionMethods.GetStableHashCode(value.Item3); } } else if (value.Item1 != "" && value.Item2 != 0f && Random.Range(0f, 1f) < value.Item2) { hitData.m_statusEffectHash = StringExtensionMethods.GetStableHashCode(value.Item1); } } } [NullableContext(1)] [Nullable(0)] [HarmonyPatch(typeof(Attack), "DoMeleeAttack")] internal static class Attack_DoMeleeAttack_LastChainDamageMultiplier_Patch { private static readonly FieldInfo LastChainDamageMultiplierField = AccessTools.Field(typeof(Attack), "m_lastChainDamageMultiplier"); private static readonly MethodInfo ModifyMethod = AccessTools.Method(typeof(DamageTypes), "Modify", new Type[1] { typeof(float) }, (Type[])null); private static IEnumerable Transpiler(IEnumerable instructions) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown List list = new List(instructions); bool flag = false; for (int i = 1; i < list.Count; i++) { if (!flag && CodeInstructionExtensions.Calls(list[i], ModifyMethod) && IsConstantTwo(list[i - 1])) { CodeInstruction value = new CodeInstruction(OpCodes.Ldarg_0, (object)null) { labels = list[i - 1].labels, blocks = list[i - 1].blocks }; list[i - 1] = value; list.Insert(i, new CodeInstruction(OpCodes.Ldfld, (object)LastChainDamageMultiplierField)); flag = true; WMRecipeCust.Dbgl("Patched Attack.DoMeleeAttack last chain damage multiplier"); break; } } if (!flag) { WMRecipeCust.WLog.LogWarning((object)"Failed to patch Attack.DoMeleeAttack last chain damage multiplier"); } return list; } private static bool IsConstantTwo(CodeInstruction instruction) { if (instruction.opcode == OpCodes.Ldc_R4 && instruction.operand is float num) { return Mathf.Approximately(num, 2f); } if (instruction.opcode == OpCodes.Ldc_I4_2) { return true; } return false; } } [Nullable(0)] [HarmonyPatch(typeof(Player), "GetAvailableRecipes")] [NullableContext(1)] internal static class Player_GetAvailableRecipes_Patch { [HarmonyPrefix] public static void Prefix(Player __instance, [Nullable(new byte[] { 2, 1, 1, 1 })] ref Dictionary> __state) { if (__state == null) { __state = new Dictionary>(); } Dictionary dictionary = new Dictionary(); if (InventoryGui.instance.InCraftTab()) { dictionary = WMRecipeCust.RequiredUpgradeItemsString.ToDictionary([NullableContext(0)] (KeyValuePair entry) => entry.Key, [NullableContext(0)] (KeyValuePair entry) => entry.Value); } else { if (!InventoryGui.instance.InUpradeTab()) { return; } dictionary = WMRecipeCust.RequiredCraftItemsString.ToDictionary([NullableContext(0)] (KeyValuePair entry) => entry.Key, [NullableContext(0)] (KeyValuePair entry) => entry.Value); } foreach (Recipe key in dictionary.Keys) { key.m_enabled = false; } __state[Assembly.GetExecutingAssembly()] = dictionary; } [HarmonyFinalizer] public static void Finalizer(Dictionary> __state) { if (!__state.TryGetValue(Assembly.GetExecutingAssembly(), out var value)) { return; } foreach (KeyValuePair item in value) { item.Key.m_enabled = item.Value; } } } [HarmonyPatch(typeof(Requirement))] internal static class PieceUpgradeReq { [HarmonyPatch("GetAmount")] [HarmonyPrefix] [NullableContext(1)] internal static bool Patch_RequirementGetAmountWM(Requirement __instance, int qualityLevel, ref int __result) { if (WMRecipeCust.requirementQuality.TryGetValue(__instance, out var value)) { __result = ((value.quality == qualityLevel) ? __instance.m_amountPerLevel : 0); return false; } return true; } } [Nullable(0)] [NullableContext(1)] [HarmonyPatch(typeof(ItemData))] internal static class ItemDataPatch { [HarmonyPriority(100)] [HarmonyPrefix] [HarmonyPatch("GetWeaponLoadingTime")] public static void GetWeaponLoadingTimePrefixWM(ItemData __instance, out float __state) { if (__instance.m_shared.m_attack.m_requiresReload) { string text = __instance.m_shared.m_name ?? "none"; __state = __instance.m_shared.m_attack.m_reloadTime; float value2; if (WMRecipeCust.crossbowReloadingTime.TryGetValue(text + "P", out var value)) { if (value == 1f) { __state = -1f; return; } Attack attack = __instance.m_shared.m_attack; attack.m_reloadTime *= value; } else if (WMRecipeCust.crossbowReloadingTime.TryGetValue(text + "S", out value2)) { if (value2 == 1f) { __state = -1f; return; } Attack secondaryAttack = __instance.m_shared.m_secondaryAttack; secondaryAttack.m_reloadTime *= value2; } } else { __state = -1f; } } [HarmonyPatch("GetWeaponLoadingTime")] [HarmonyPriority(700)] [HarmonyPostfix] public static void GetWeaponLoadingTimePostfixWM(ItemData __instance, ref float __state) { if (__instance.m_shared.m_attack.m_requiresReload && __state != -1f) { __instance.m_shared.m_attack.m_reloadTime = __state; } } } [HarmonyPatch(typeof(Player), "TryPlacePiece")] internal static class Player_MessageforWackyDBTry { private static Vector3 tempvalue; [NullableContext(1)] private static bool Prefix(ref Player __instance, ref Piece piece) { //IL_0064: 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_0087: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)piece == (Object)null) { return true; } foreach (string item in WMRecipeCust.pieceWithLvl) { string[] array = item.Split(new char[1] { '.' }); string text = array[0]; int num = int.Parse(array[1]); if (!(((Object)piece).name == text) || __instance.m_noPlacementCost) { continue; } _ = ((Component)__instance).transform.position; tempvalue = ((Component)__instance).transform.position; if (CraftingStation.HaveBuildStationInRange(piece.m_craftingStation.m_name, tempvalue).GetLevel(true) + 1 <= num) { string worktablename = ((Object)piece.m_craftingStation).name; string name = DataHelpers.GetPieces().Find([NullableContext(1)] (GameObject g) => Utils.GetPrefabName(g) == worktablename).GetComponent() .m_name; ((Character)__instance).Message((MessageType)2, "Need a Level " + num + " " + name + " for placement", 0, (Sprite)null); return false; } } return true; } } [HarmonyPriority(0)] [HarmonyPatch(typeof(Recipe), "GetRequiredStationLevel")] internal static class RecipeStationPatchWackydb { [NullableContext(1)] private static void Postfix(ref int __result, Recipe __instance) { if (!((Object)(object)__instance == (Object)null) && !((Object)(object)__instance.m_item == (Object)null) && WMRecipeCust.RecipeMaxStationLvl.TryGetValue(((Object)__instance.m_item).name, out var value) && value != -1) { __result = Math.Min(__result, value); } } } [HarmonyPatch(typeof(StatusEffect), "Stop")] internal static class StatusEffectChainCheck { [NullableContext(1)] private static void Postfix(StatusEffect __instance) { Character character = __instance.m_character; Player val = (Player)(object)((character is Player) ? character : null); if (val != null && (Object)(object)val == (Object)(object)Player.m_localPlayer && __instance.m_ttl > 0f && __instance.m_time > __instance.m_ttl && WMRecipeCust.EndingStatusEffect.TryGetValue(((Object)__instance).name, out var value)) { ((Character)val).m_seman.AddStatusEffect(StringExtensionMethods.GetStableHashCode(value), false, 0, 0f); } } } [NullableContext(1)] [Nullable(0)] public class QuoteSurroundingEventEmitter : ChainedEventEmitter { private int _itemIndex; public QuoteSurroundingEventEmitter(IEventEmitter nextEmitter) : base(nextEmitter) { } public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { if (eventInfo.Source.StaticType == typeof(object) && _itemIndex++ % 2 == 1) { eventInfo.Style = ScalarStyle.SingleQuoted; } base.Emit(eventInfo, emitter); } } [HarmonyPatch(typeof(Terminal), "InitTerminal")] public static class Console_Patch { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static ConsoleEvent <>9__0_0; public static ConsoleEvent <>9__0_1; public static ConsoleEvent <>9__0_2; public static ConsoleEvent <>9__0_3; public static ConsoleEvent <>9__0_4; public static ConsoleEvent <>9__0_5; public static ConsoleEvent <>9__0_6; public static ConsoleEvent <>9__0_7; public static ConsoleOptionsFetcher <>9__0_8; public static ConsoleEvent <>9__0_9; public static ConsoleOptionsFetcher <>9__0_10; public static ConsoleEvent <>9__0_11; public static ConsoleOptionsFetcher <>9__0_12; public static ConsoleEvent <>9__0_13; public static ConsoleOptionsFetcher <>9__0_14; public static ConsoleEvent <>9__0_15; public static ConsoleOptionsFetcher <>9__0_16; public static ConsoleEvent <>9__0_17; public static ConsoleOptionsFetcher <>9__0_18; public static ConsoleEvent <>9__0_19; public static ConsoleEvent <>9__0_20; public static ConsoleEvent <>9__0_21; public static ConsoleEvent <>9__0_22; public static ConsoleEvent <>9__0_23; public static ConsoleEvent <>9__0_24; public static ConsoleEvent <>9__0_25; public static ConsoleEvent <>9__0_26; public static ConsoleEvent <>9__0_27; public static ConsoleEvent <>9__0_28; public static ConsoleEvent <>9__0_29; public static ConsoleEvent <>9__0_30; public static ConsoleEvent <>9__0_31; public static ConsoleEvent <>9__0_32; public static ConsoleOptionsFetcher <>9__0_33; public static ConsoleEvent <>9__0_34; public static ConsoleOptionsFetcher <>9__0_35; public static ConsoleEvent <>9__0_36; public static ConsoleEvent <>9__0_37; public static ConsoleOptionsFetcher <>9__0_38; public static ConsoleEvent <>9__0_39; internal void b__0_0(ConsoleEventArgs args) { WMRecipeCust.WLog.LogWarning((object)" deleting Cache"); WMRecipeCust.DeleteCache(); MaterialDataManager.Instance.materials.Clear(); TextureDataManager.textureCache.Clear(); Terminal context = args.Context; if (context != null) { context.AddString("deleting Cache"); } } internal void b__0_1(ConsoleEventArgs args) { foreach (GameObject item in WMRecipeCust.SnapshotPiecestoDo) { Functions.SnapshotPiece(item); } } internal void b__0_2(ConsoleEventArgs args) { string text = "wackydb_reload -reloads on client or server\r\nwackydb_save_recipe [RecipeName](recipe output)\r\nwackydb_save_piece [PieceName](piece output) \r\nwackydb_save_item [ItemName](item Output)\r\nwackydb_save_creature [CreatureName](Creature Output)\r\nwackydb_save_pickable [PickableName](Pickable Output)\r\nwackydb_save_material [MaterialName] Save Material Info - Usually has _mat\r\nwackydb_se [SEEffectName] Save SEeffect\r\nwackydb_help\r\nwackydb_clone [item/recipe/piece/creatures/material/se/pickables] [Prefab to clone] [Unique name for the clone] \r\n4th paramater for recipes - you can already have item WackySword loaded in game, but now want a recipe. WackySword Uses SwordIron - wackydb_clone recipe WackySword RWackySword SwordIron - otherwise manually edit\r\nwackydb_clone_recipeitem [Prefab to clone] [Unique name for the clone](Recipe name will be Rname) (clones item and recipe at same time)\r\nwackydb_vfx (outputs vfx gameobjects available)\r\nwackydb_fx (outputs fx gameobjects available)\r\nwackydb_sfx (outputs Sfx gameobjects available)\r\nwackydb_material (outputs Materials available)\r\nwackydb_sendtheload -experimental\r\nwackydb_get_piecehammers -Get All Hammer in Game\r\nwackydb_all_se -Save All SE Effects to Bulk Folder\r\nwackydb_all_items -Save ALL Items to Bulk Folder\r\nwackydb_all_recipes -Save all Recipes to Bulk Folder\r\nwackydb_all_pieces [Hammer][Optional-Category]-Save all Pieces to Bulk Folder: default hammer, optionally by category\r\nwackydb_all_creatures -Save All Creatures\r\nwackydb_all_pickables -Save All Pickables and Tree Bases\r\nwackydb_describe [ObjectName] Describe an Objects Visual Data\r\nwackydb_clearcache Clears cache\r\nwackydb_snapshot Reloads snapshot after wackydb_reload\r\n"; Terminal context = args.Context; if (context != null) { context.AddString(text); } } internal void b__0_3(ConsoleEventArgs args) { string text = "wackydb_reload\r\nwackydb_save_recipe [RecipeName](recipe output)\r\nwackydb_save_piece [PieceName](piece output) \r\nwackydb_save_item [ItemName](item Output)\r\nwackydb_save_creature [CreatureName](Creature Output)\r\nwackydb_save_pickable [PickableName](Pickable Output)\r\nwackydb_save_material [MaterialName] Save Material Info - Usually has _mat\r\nwackydb_se [SEEffectName] Save SEeffect\r\nwackydb_help\r\nwackydb_clone [item/recipe/piece/creatures/material/se/pickables] [Prefab to clone] [Unique name for the clone] \r\n4th paramater for recipes - you can already have item WackySword loaded in game, but now want a recipe. WackySword Uses SwordIron - wackydb_clone recipe WackySword RWackySword SwordIron - otherwise manually edit\r\nwackydb_clone_recipeitem [Prefab to clone] [Unique name for the clone](Recipe name will be Rname) (clones item and recipe at same time)\r\nwackydb_vfx (outputs vfx gameobjects available)\r\nwackydb_fx (outputs fx gameobjects available)\r\nwackydb_sfx (outputs Sfx gameobjects available)\r\nwackydb_material (outputs Materials available)\r\nwackydb_sendtheload -experimental\r\nwackydb_get_piecehammers -Get All Hammer in Game\r\nwackydb_all_se -Save All SE Effects to Bulk Folder\r\nwackydb_all_items -Save ALL Items to Bulk Folder\r\nwackydb_all_recipes -Save all Recipes to Bulk Folder\r\nwackydb_all_pieces [Hammer][Optional-Category]-Save all Pieces to Bulk Folder: default hammer, optionally by category\r\nwackydb_all_creatures -Save All Creatures\r\nwackydb_all_pickables -Save All Pickables and Tree Bases\r\nwackydb_describe [ObjectName] Describe an Objects Visual Data\r\nwackydb_clearcache Clears cache\r\nwackydb_snapshot Reloads snapshot after wackydb_reload\r\n"; Terminal context = args.Context; if (context != null) { context.AddString(text); } } internal void b__0_4(ConsoleEventArgs args) { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown if (Object.op_Implicit((Object)(object)ObjectDB.instance) && WMRecipeCust.issettoSinglePlayer) { ReadFiles readFiles = new ReadFiles(); ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(readFiles.GetDataFromFiles(slowmode: true)); WMRecipeCust.readFiles = readFiles; Reload reload = (WMRecipeCust.CurrentReload = new Reload()); if (WMRecipeCust.HasLobbied) { ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(reload.LoadAllRecipeData(reload: true, slowmode: true, forcepush: true)); WMRecipeCust.Dbgl("Admin: Forcing Push after reload"); Terminal context = args.Context; if (context != null) { context.AddString("Admin: Forcing Push after reload"); } } else { ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(reload.LoadAllRecipeData(reload: true, slowmode: true)); } } else if (WMRecipeCust.Admin) { ZPackage val = new ZPackage(); val.Write("true"); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "WackyDBAdminReload", new object[1] { val }); WMRecipeCust.Dbgl("Admin: Attempting to tell Server to reload"); Terminal context2 = args.Context; if (context2 != null) { context2.AddString("Admin: Attempting to tell Server to reload"); } } else { Terminal context3 = args.Context; if (context3 != null) { context3.AddString("WackyDatabase did NOT reload recipes/items/pieces from files"); } WMRecipeCust.Dbgl("WackyDatabase did NOT reload recipes/items/pieces from files"); } } internal void b__0_5(ConsoleEventArgs args) { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && WMRecipeCust.issettoSinglePlayer) { ReadFiles readFiles = new ReadFiles(); ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(readFiles.GetDataFromFiles()); WMRecipeCust.readFiles = readFiles; Reload reload = (WMRecipeCust.CurrentReload = new Reload()); ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(reload.LoadAllRecipeData(reload: true)); Terminal context = args.Context; if (context != null) { context.AddString("WackyDatabase reloaded recipes/items/pieces from files"); } } } internal void b__0_6(ConsoleEventArgs args) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown if (!WMRecipeCust.Admin) { return; } if (WMRecipeCust.issettoSinglePlayer) { Terminal context = args.Context; if (context != null) { context.AddString("You are in singleplayer, no clients to send the load to."); } return; } ZPackage val = new ZPackage(); val.Write("true"); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "WackyDBAdminBigData", new object[1] { val }); WMRecipeCust.Dbgl("Admin: Attempting to tell Server to Send the Motherload"); Terminal context2 = args.Context; if (context2 != null) { context2.AddString("Admin: Attempting to tell Server to Send the Motherload"); } } internal void b__0_7(ConsoleEventArgs args) { string text = args[1]; WItemData itemDataByName = new GetDataYML().GetItemDataByName(text, ObjectDB.instance); if (itemDataByName != null) { WMRecipeCust.CheckModFolder(); ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathItems, "Item_" + itemDataByName.name + ".yml"), serializer.Serialize(itemDataByName)); Terminal context = args.Context; if (context != null) { context.AddString("saved item data to Item_" + text + ".yml"); } } } internal List b__0_8() { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { return ZNetScene.instance.GetPrefabNames(); } return new List(); } internal void b__0_9(ConsoleEventArgs args) { string text = args[1]; PieceData pieceRecipeByName = new GetDataYML().GetPieceRecipeByName(text, ObjectDB.instance); if (pieceRecipeByName != null) { WMRecipeCust.CheckModFolder(); ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathPieces, "Piece_" + pieceRecipeByName.name + ".yml"), serializer.Serialize(pieceRecipeByName)); Terminal context = args.Context; if (context != null) { context.AddString("saved data to Piece_" + text + ".yml"); } } } internal List b__0_10() { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { return ZNetScene.instance.GetPrefabNames(); } return new List(); } internal void b__0_11(ConsoleEventArgs args) { string text = args[1]; RecipeData recipeDataByName = new GetDataYML().GetRecipeDataByName(text, ObjectDB.instance); if (recipeDataByName != null) { WMRecipeCust.CheckModFolder(); ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathRecipes, "Recipe_" + recipeDataByName.name + ".yml"), serializer.Serialize(recipeDataByName)); Terminal context = args.Context; if (context != null) { context.AddString("saved data to Recipe_" + text + ".yml"); } } } internal List b__0_12() { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { return ZNetScene.instance.GetPrefabNames(); } return new List(); } internal void b__0_13(ConsoleEventArgs args) { string text = args[1]; CreatureData creature = new GetDataYML().GetCreature(text); if (creature != null) { WMRecipeCust.CheckModFolder(); ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathCreatures, "Creature_" + creature.name + ".yml"), serializer.Serialize(creature)); Terminal context = args.Context; if (context != null) { context.AddString("saved data to Creature_" + text + ".yml"); } } } internal List b__0_14() { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { return ZNetScene.instance.GetPrefabNames(); } return new List(); } internal void b__0_15(ConsoleEventArgs args) { string text = args[1]; GetDataYML getDataYML = new GetDataYML(); Pickable[] array = Resources.FindObjectsOfTypeAll(); PickableData pickable = getDataYML.GetPickable(text, array); TreeBase[] array2 = Resources.FindObjectsOfTypeAll(); TreeBaseData treeBase = getDataYML.GetTreeBase(text, array2); string text2 = "Pickable"; if (pickable == null) { text2 = "Treebase_"; if (treeBase == null) { return; } } WMRecipeCust.CheckModFolder(); ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); if (text2 == "Pickable") { File.WriteAllText(Path.Combine(WMRecipeCust.assetPathPickables, "Pickable_" + pickable.name + ".yml"), serializer.Serialize(pickable)); } else { File.WriteAllText(Path.Combine(WMRecipeCust.assetPathPickables, text2 + treeBase.name + ".yml"), serializer.Serialize(treeBase)); } Terminal context = args.Context; if (context != null) { context.AddString("Saved data to Folder Pickables " + text2 + "_" + text + ".yml"); } } internal List b__0_16() { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { return ZNetScene.instance.GetPrefabNames(); } return new List(); } internal void b__0_17(ConsoleEventArgs args) { WMRecipeCust.CheckModFolder(); if (args.Length - 1 < 1) { Terminal context = args.Context; if (context != null) { context.AddString("Not enough arguments"); } return; } ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); GetDataYML getDataYML = new GetDataYML(); string text = args[1]; WItemData itemDataByName = getDataYML.GetItemDataByName(text, ObjectDB.instance); if (itemDataByName == null) { return; } File.WriteAllText(Path.Combine(WMRecipeCust.assetPathItems, "Item_" + itemDataByName.name + ".yml"), serializer.Serialize(itemDataByName)); string text2 = ""; RecipeData recipeDataByName = getDataYML.GetRecipeDataByName(text, ObjectDB.instance); if (recipeDataByName != null) { File.WriteAllText(Path.Combine(WMRecipeCust.assetPathRecipes, "Recipe_" + recipeDataByName.name + ".yml"), serializer.Serialize(recipeDataByName)); text2 = "Item saved as Item_" + itemDataByName.name + ".yml, Recipe saved as Recipe_" + recipeDataByName.name + ".yml"; } else { recipeDataByName = getDataYML.GetRecipeDataByName("Club", ObjectDB.instance); if (recipeDataByName == null) { return; } recipeDataByName.name = "R" + text; recipeDataByName.clonePrefabName = text; text2 = "Item saved as Item_" + itemDataByName.name + ".yml, Recipe saved as a clone from 'Club' Recipe_" + recipeDataByName.name + ".yml"; File.WriteAllText(Path.Combine(WMRecipeCust.assetPathRecipes, "Recipe_" + recipeDataByName.name + ".yml"), serializer.Serialize(recipeDataByName)); } Terminal context2 = args.Context; if (context2 != null) { context2.AddString(text2 ?? ""); } } internal List b__0_18() { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { return ZNetScene.instance.GetPrefabNames(); } return new List(); } internal void b__0_19(ConsoleEventArgs args) { string allMaterialsFile = Functions.GetAllMaterialsFile(); WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathconfig, "Materials.txt"), allMaterialsFile); Terminal context = args.Context; if (context != null) { context.AddString("saved data to Materials.txt"); } WMRecipeCust.WLog.LogInfo((object)"saved data to Materials.txt"); } internal void b__0_20(ConsoleEventArgs args) { string text = ""; PieceTable[] maybePieceStations = WMRecipeCust.MaybePieceStations; foreach (PieceTable val in maybePieceStations) { text = text + ((object)val).ToString() + " \r\n"; } File.WriteAllText(Path.Combine(WMRecipeCust.assetPathconfig, "Hammers.txt"), text); Terminal context = args.Context; if (context != null) { context.AddString("saved data to Hammers.txt"); } WMRecipeCust.WLog.LogInfo((object)"saved data to Hammers.txt"); } internal void b__0_21(ConsoleEventArgs args) { string allVFXFile = Functions.GetAllVFXFile(); WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathconfig, "vfx.txt"), allVFXFile); Terminal context = args.Context; if (context != null) { context.AddString("saved data to VFX.txt"); } WMRecipeCust.WLog.LogInfo((object)"saved data to VFX.txt"); } internal void b__0_22(ConsoleEventArgs args) { string allSFXFile = Functions.GetAllSFXFile(); WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathconfig, "sfx.txt"), allSFXFile); Terminal context = args.Context; if (context != null) { context.AddString("saved data to sfx.txt"); } WMRecipeCust.WLog.LogInfo((object)"saved data to sfx.txt"); } internal void b__0_23(ConsoleEventArgs args) { string allFXFile = Functions.GetAllFXFile(); WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathconfig, "FX.txt"), allFXFile); Terminal context = args.Context; if (context != null) { context.AddString("saved data to FX.txt"); } WMRecipeCust.WLog.LogInfo((object)"saved data to FX.txt"); } internal void b__0_24(ConsoleEventArgs args) { ObjectDB instance = ObjectDB.instance; int num = instance.m_StatusEffects.Count(); GetDataYML getDataYML = new GetDataYML(); int num2 = 0; if (!Directory.Exists(WMRecipeCust.assetPathBulkYML)) { WMRecipeCust.Dbgl("Creating wackyDatabase-BulkYML Folder in Config"); Directory.CreateDirectory(WMRecipeCust.assetPathBulkYML); } if (!Directory.Exists(WMRecipeCust.assetPathBulkYMLEffects)) { Directory.CreateDirectory(WMRecipeCust.assetPathBulkYMLEffects); } ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); while (num2 != num) { StatusData statusEByNum = getDataYML.GetStatusEByNum(num2, instance); num2++; if (statusEByNum != null) { string contents = serializer.Serialize(statusEByNum); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathBulkYMLEffects, "SE_" + statusEByNum.Name + ".yml"), contents); } } Terminal context = args.Context; if (context != null) { context.AddString("saved all Status Effects to wackyDatabase-BulkYML Effects"); } WMRecipeCust.WLog.LogInfo((object)"saved all Status Effects to wackyDatabase-BulkYML Effects"); } internal void b__0_25(ConsoleEventArgs args) { if (!Directory.Exists(WMRecipeCust.assetPathBulkYML)) { WMRecipeCust.Dbgl("Creating wackyDatabase-BulkYML Folder in Config"); Directory.CreateDirectory(WMRecipeCust.assetPathBulkYML); } if (!Directory.Exists(WMRecipeCust.assetPathBulkYMLItems)) { Directory.CreateDirectory(WMRecipeCust.assetPathBulkYMLItems); } ObjectDB instance = ObjectDB.instance; int num = instance.m_items.Count(); GetDataYML getDataYML = new GetDataYML(); int num2 = 0; ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); while (num2 != num) { WItemData itemDataByCount = getDataYML.GetItemDataByCount(num2, instance); num2++; if (itemDataByCount != null) { string contents = serializer.Serialize(itemDataByCount); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathBulkYMLItems, "Item_" + itemDataByCount.name + ".yml"), contents); } } Terminal context = args.Context; if (context != null) { context.AddString("saved all Items in WackyBulk Items"); } WMRecipeCust.WLog.LogInfo((object)"saved all Items in WackyBulk Items"); } internal void b__0_26(ConsoleEventArgs args) { if (!Directory.Exists(WMRecipeCust.assetPathBulkYML)) { WMRecipeCust.Dbgl("Creating wackyDatabase-BulkYML Folder in Config"); Directory.CreateDirectory(WMRecipeCust.assetPathBulkYML); } if (!Directory.Exists(WMRecipeCust.assetPathBulkYMLCreatures)) { Directory.CreateDirectory(WMRecipeCust.assetPathBulkYMLCreatures); } new GetDataYML().GetAllCreature(); Terminal context = args.Context; if (context != null) { context.AddString("saved all Creatures in WackyBulk "); } WMRecipeCust.WLog.LogInfo((object)"saved all Creatures in WackyBulk "); } internal void b__0_27(ConsoleEventArgs args) { if (!Directory.Exists(WMRecipeCust.assetPathBulkYML)) { WMRecipeCust.Dbgl("Creating wackyDatabase-BulkYML Folder in Config"); Directory.CreateDirectory(WMRecipeCust.assetPathBulkYML); } if (!Directory.Exists(WMRecipeCust.assetPathBulkYMLRecipes)) { Directory.CreateDirectory(WMRecipeCust.assetPathBulkYMLRecipes); } ObjectDB instance = ObjectDB.instance; int num = instance.m_recipes.Count(); GetDataYML getDataYML = new GetDataYML(); int num2 = 0; ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); while (num2 != num) { RecipeData recipeDataByNum = getDataYML.GetRecipeDataByNum(num2, instance); num2++; if (recipeDataByNum != null) { string contents = serializer.Serialize(recipeDataByNum); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathBulkYMLRecipes, "Recipe_" + recipeDataByNum.name + ".yml"), contents); } } Terminal context = args.Context; if (context != null) { context.AddString("saved all Recipes in WackyBulk Recipes Folder"); } WMRecipeCust.WLog.LogInfo((object)"saved all Recipes in WackyBulk Recipes Folder"); } internal void b__0_28(ConsoleEventArgs args) { if (!Directory.Exists(WMRecipeCust.assetPathBulkYML)) { WMRecipeCust.Dbgl("Creating wackyDatabase-BulkYML Folder in Config"); Directory.CreateDirectory(WMRecipeCust.assetPathBulkYML); } if (!Directory.Exists(WMRecipeCust.assetPathBulkYMLPickables)) { Directory.CreateDirectory(WMRecipeCust.assetPathBulkYMLPickables); } new GetDataYML().GetAllPickables(); Terminal context = args.Context; if (context != null) { context.AddString("saved all Pickables/TreeBases in WackyBulk Pickables Folder"); } WMRecipeCust.WLog.LogInfo((object)"saved all Pickables/TreeBases in WackyBulk Pickables Folder"); } internal void b__0_29(ConsoleEventArgs args) { //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_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) if (args.Length - 1 < 1) { Terminal context = args.Context; if (context != null) { context.AddString("Enter a piece hammer default hammer is Hammer"); } return; } string text = null; string text2 = args[1]; if (text2.ToLower() == "hammer") { text2 = "Hammer"; } if (text2.ToLower() == "hoe") { text2 = "Hoe"; } if (args.Length - 1 == 2) { text = args[2]; } if (!Directory.Exists(WMRecipeCust.assetPathBulkYML)) { WMRecipeCust.Dbgl("Creating wackyDatabase-BulkYML Folder in Config"); Directory.CreateDirectory(WMRecipeCust.assetPathBulkYML); } if (!Directory.Exists(WMRecipeCust.assetPathBulkYMLPieces)) { Directory.CreateDirectory(WMRecipeCust.assetPathBulkYMLPieces); } ObjectDB instance = ObjectDB.instance; ItemDrop val = null; try { val = instance.GetItemPrefab(text2).GetComponent(); } catch { WMRecipeCust.WLog.LogWarning((object)(text2 + " not found")); return; } int num = val.m_itemData.m_shared.m_buildPieces.m_pieces.Count(); WMRecipeCust.WLog.LogWarning((object)$"Count is {num} for m__pieces"); if (text != null) { List list = null; try { PieceCategory val2 = (PieceCategory)Enum.Parse(typeof(PieceCategory), text); WMRecipeCust.WLog.LogWarning((object)"Piece Hammer CAt"); num = val.m_itemData.m_shared.m_buildPieces.GetAvailablePiecesInCategory(val2); val.m_itemData.m_shared.m_buildPieces.m_selectedCategory = val2; list = val.m_itemData.m_shared.m_buildPieces.GetPiecesInSelectedCategory(); } catch { WMRecipeCust.WLog.LogWarning((object)(text + " category was not parsed correclty")); text = null; } if (list != null) { GetDataYML getDataYML = new GetDataYML(); ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); foreach (Piece item in list) { PieceData piece = getDataYML.GetPiece(val, text2, ((Component)item).gameObject, instance); if (piece != null) { string contents = serializer.Serialize(piece); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathBulkYMLPieces, "Piece_" + piece.name + ".yml"), contents); } } Terminal context2 = args.Context; if (context2 != null) { context2.AddString("saved all Pieces from hammer " + text2 + " with category " + text + " in WackyBulk Pieces"); } WMRecipeCust.WLog.LogInfo((object)("saved all Pieces from hammer " + text2 + " with category " + text + " in WackyBulk Pieces")); } else { Terminal context3 = args.Context; if (context3 != null) { context3.AddString("Failure for category saving of pieces " + text2 + " in WackyBulk"); } WMRecipeCust.WLog.LogWarning((object)("Failure for category saving of pieces " + text2 + " in WackyBulk")); } return; } GetDataYML getDataYML2 = new GetDataYML(); int num2 = 0; ISerializer serializer2 = new SerializerBuilder().WithNewLine("\n").Build(); while (num2 != num) { PieceData pieceRecipeByNum = getDataYML2.GetPieceRecipeByNum(num2, text2, val, instance); num2++; if (pieceRecipeByNum != null) { string contents2 = serializer2.Serialize(pieceRecipeByNum); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathBulkYMLPieces, "Piece_" + pieceRecipeByNum.name + ".yml"), contents2); } } Terminal context4 = args.Context; if (context4 != null) { context4.AddString("saved all Pieces from hammer " + text2 + " in WackyBulk"); } WMRecipeCust.WLog.LogInfo((object)("saved all Pieces from hammer " + text2 + " in WackyBulk")); } internal void b__0_30(ConsoleEventArgs args) { string text = args[1]; ObjectDB instance = ObjectDB.instance; GetDataYML getDataYML = new GetDataYML(); ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); StatusData statusEByName = getDataYML.GetStatusEByName(text, instance); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathEffects, "SE_" + statusEByName.Name + ".yml"), serializer.Serialize(statusEByName)); Terminal context = args.Context; if (context != null) { context.AddString("saved SE effect " + text + " to SE_" + text + ".yml in Effects folder"); } WMRecipeCust.WLog.LogInfo((object)("saved SE effect " + text + " to SE_" + text + ".yml in Effects folder")); } internal void b__0_31(ConsoleEventArgs args) { ObjectDB instance = ObjectDB.instance; GetDataYML getDataYML = new GetDataYML(); ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); StatusData statusEByName = getDataYML.GetStatusEByName("SetEffect_TrollArmor", instance); statusEByName.Name = "SetEffect_New" + new Random().Next(1, 1000); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathEffects, "SE_" + statusEByName.Name + ".yml"), serializer.Serialize(statusEByName)); Terminal context = args.Context; if (context != null) { context.AddString("Created a clone from SetEffect_TrollArmor, saved as a file SE_" + statusEByName.Name + ".yml in Effects folder, PLEASE ReNAME"); } WMRecipeCust.WLog.LogInfo((object)("Created a clone from SetEffect_TrollArmor, saved as a file SE_" + statusEByName.Name + ".yml in Effects folder, PLEASE ReNAME")); } internal void b__0_32(ConsoleEventArgs args) { //IL_061a: Unknown result type (might be due to invalid IL or missing references) //IL_061f: Unknown result type (might be due to invalid IL or missing references) //IL_0631: Unknown result type (might be due to invalid IL or missing references) //IL_064c: Expected I4, but got Unknown //IL_0663: Unknown result type (might be due to invalid IL or missing references) //IL_06b2: Unknown result type (might be due to invalid IL or missing references) //IL_06bc: Expected O, but got Unknown if (args.Length - 1 < 3) { Terminal context = args.Context; if (context != null) { context.AddString("Not enough arguments"); } return; } string text = args[1]; string text2 = args[2]; string text3 = args[3]; string text4 = args[3]; if (text3 == "SwordTest") { Terminal context2 = args.Context; if (context2 != null) { context2.AddString("" + text3 + " is already a ingame name. -Bad "); } return; } ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); GetDataYML getDataYML = new GetDataYML(); if (text == "recipe" || text == "Recipe") { WMRecipeCust.CheckModFolder(); if (args.Length - 1 < 4) { RecipeData recipeDataByName = getDataYML.GetRecipeDataByName(text2, ObjectDB.instance); if (recipeDataByName == null) { return; } recipeDataByName.name = text3; recipeDataByName.clonePrefabName = text2; File.WriteAllText(Path.Combine(WMRecipeCust.assetPathRecipes, "Recipe_" + recipeDataByName.name + ".yml"), serializer.Serialize(recipeDataByName)); text4 = "Recipe" + recipeDataByName.name; } else { string text5 = args[4]; RecipeData recipeDataByName2 = getDataYML.GetRecipeDataByName(text5, ObjectDB.instance); if (recipeDataByName2 == null) { return; } recipeDataByName2.name = text3; recipeDataByName2.clonePrefabName = text2; File.WriteAllText(Path.Combine(WMRecipeCust.assetPathRecipes, "Recipe_" + recipeDataByName2.name + ".yml"), serializer.Serialize(recipeDataByName2)); text4 = "Cloned Item " + recipeDataByName2.name + " Clone Recipe from " + text5; } } if (text == "item" || text == "Item") { WItemData itemDataByName = getDataYML.GetItemDataByName(text2, ObjectDB.instance); if (itemDataByName == null) { return; } itemDataByName.name = text3; itemDataByName.clonePrefabName = text2; itemDataByName.m_name = text3; WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathItems, "Item_" + itemDataByName.name + ".yml"), serializer.Serialize(itemDataByName)); text4 = "Item_" + itemDataByName.name; } if (text == "piece" || text == "Piece") { PieceData pieceRecipeByName = getDataYML.GetPieceRecipeByName(text2, ObjectDB.instance); if (pieceRecipeByName == null) { return; } pieceRecipeByName.name = text3; pieceRecipeByName.clonePrefabName = text2; WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathPieces, "Piece_" + pieceRecipeByName.name + ".yml"), serializer.Serialize(pieceRecipeByName)); text4 = "Piece_" + pieceRecipeByName.name; } switch (text) { case "pickable": case "Pickable": case "Pickables": case "pickables": { Pickable[] array = Resources.FindObjectsOfTypeAll(); PickableData pickable = getDataYML.GetPickable(text2, array); if (pickable == null) { return; } pickable.name = text3; pickable.cloneOfWhatPickable = text2; WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathPickables, "Pickable_" + pickable.name + ".yml"), serializer.Serialize(pickable)); text4 = "Pickable_" + pickable.name; break; } } if (text == "treebase" || text == "Treebase") { TreeBase[] array2 = Resources.FindObjectsOfTypeAll(); TreeBaseData treeBase = getDataYML.GetTreeBase(text2, array2); if (treeBase == null) { return; } treeBase.name = text3; treeBase.cloneOfWhatTree = text2; WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathPieces, "Treebase_" + treeBase.name + ".yml"), serializer.Serialize(treeBase)); text4 = "Treebase_" + treeBase.name; } switch (text) { case "creature": case "Creature": case "mob": { CreatureData creature = getDataYML.GetCreature(text2); if (creature == null) { return; } creature.name = text3; creature.clone_creature = text2; WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathCreatures, "Creature_" + creature.name + ".yml"), serializer.Serialize(creature)); text4 = "Creature_" + creature.name; break; } } switch (text) { case "se": case "SE": case "Se": try { ObjectDB instance = ObjectDB.instance; StatusData statusEByName = new GetDataYML().GetStatusEByName(text2, instance); if (statusEByName == null) { WMRecipeCust.WLog.LogInfo((object)(statusEByName.Name + " Was not found")); } statusEByName.Name = text3; statusEByName.ClonedSE = text2; File.WriteAllText(Path.Combine(WMRecipeCust.assetPathEffects, "SE_" + statusEByName.Name + ".yml"), serializer.Serialize(statusEByName)); Terminal context3 = args.Context; if (context3 != null) { context3.AddString("Created a clone from " + text2 + " , saved as a file SE_" + statusEByName.Name + ".yml in Effects folder"); } WMRecipeCust.WLog.LogInfo((object)("Created a clone from " + text2 + " , saved as a file SE_" + statusEByName.Name + ".yml in Effects folder")); } catch { WMRecipeCust.WLog.LogWarning((object)"wackydb_clone SE is unhappy, feed it better cookies"); text4 = "not saved"; } break; } switch (text) { case "material": case "Material": case "mat": { string text6 = text2; if (!WMRecipeCust.originalMaterials.ContainsKey(text6)) { break; } Material val = WMRecipeCust.originalMaterials[text6]; YamlLoader yamlLoader = new YamlLoader(); MaterialInstance materialInstance = new MaterialInstance { original = text6, name = text3, overwrite = false }; int propertyCount = val.shader.GetPropertyCount(); for (int i = 0; i < propertyCount; i++) { ShaderPropertyType propertyType = val.shader.GetPropertyType(i); string propertyName = val.shader.GetPropertyName(i); switch ((int)propertyType) { case 0: materialInstance.changes.colors.Add(propertyName, val.GetColor(propertyName)); break; case 1: case 2: case 3: materialInstance.changes.floats.Add(propertyName, val.GetFloat(propertyName)); break; case 4: { Texture texture = val.GetTexture(propertyName); try { if ((Object)(object)texture != (Object)null) { materialInstance.changes.textures.Add(propertyName, (Texture2D)texture); TextureDataManager.SaveTexture(((Object)texture).name, texture); } } catch (Exception ex) { Debug.LogError((object)("[WackysDatabase]: Unable to write texture for property: " + propertyName + " - " + ex.Message)); } break; } } } yamlLoader.Write(Path.Combine(WMRecipeCust.assetPathMaterials, text3 + ".yml"), materialInstance); Terminal context4 = args.Context; if (context4 != null) { context4.AddString("Saved in the Material folder, as " + text3 + ".yml"); } break; } } Terminal context5 = args.Context; if (context5 != null) { context5.AddString("saved cloned data to " + text4 + ".yml"); } } internal List b__0_33() { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { return ZNetScene.instance.GetPrefabNames(); } return new List(); } internal void b__0_34(ConsoleEventArgs args) { WMRecipeCust.CheckModFolder(); if (args.Length - 1 < 2) { Terminal context = args.Context; if (context != null) { context.AddString("Not enough arguments"); } return; } ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); GetDataYML getDataYML = new GetDataYML(); string text = args[1]; string text2 = args[2]; string text3 = args[2]; WItemData itemDataByName = getDataYML.GetItemDataByName(text, ObjectDB.instance); if (itemDataByName == null) { return; } itemDataByName.name = text2; itemDataByName.clonePrefabName = text; itemDataByName.m_name = text2; File.WriteAllText(Path.Combine(WMRecipeCust.assetPathItems, "Item_" + itemDataByName.name + ".yml"), serializer.Serialize(itemDataByName)); RecipeData recipeDataByName = getDataYML.GetRecipeDataByName(text, ObjectDB.instance); if (recipeDataByName != null) { recipeDataByName.name = "R" + text2; recipeDataByName.clonePrefabName = itemDataByName.name; File.WriteAllText(Path.Combine(WMRecipeCust.assetPathRecipes, "Recipe_" + recipeDataByName.name + ".yml"), serializer.Serialize(recipeDataByName)); text3 = "Cloned Item saved as Item_" + itemDataByName.name + ".yml, cloned Recipe saved as Recipe_" + recipeDataByName.name + ".yml which is from the Orginal Recipe " + text; Terminal context2 = args.Context; if (context2 != null) { context2.AddString(text3 ?? ""); } } } internal List b__0_35() { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { return ZNetScene.instance.GetPrefabNames(); } return new List(); } internal void b__0_36(ConsoleEventArgs args) { if (WMRecipeCust.issettoSinglePlayer || WMRecipeCust.kickcount >= 3) { return; } string text = ""; try { text = args[1]; } catch { WMRecipeCust.WLog.LogWarning((object)"Congrats on finding the backdoor... You have 3 chances to guess the password or you will be called out that your a dirty cheater in chat and probably being kicked by Azu or an admin"); return; } WMRecipeCust.WLog.LogWarning((object)$"guess {WMRecipeCust.kickcount + 1}"); string text2 = Functions.ComputeSha256Hash(text); string text3 = "f289b4717485d90d9dee6ce2a9992e4fcfa4317a9439c148053d52c637b0691b"; if (text2 == text3) { WMRecipeCust.WLog.LogWarning((object)"Congrats you cheater, Enjoy nothin"); return; } WMRecipeCust.kickcount++; if (WMRecipeCust.kickcount >= 3) { string name = ((Object)Player.m_localPlayer).name; ((Terminal)Chat.m_instance).AddString("[WackysDatabase]", "Cheater Cheater, pants on fire. " + name + " tried to get admin access and failed. Laugh at this person or kick them.", (Type)1, false); WMRecipeCust.WLog.LogWarning((object)"Cheater Cheater, pants on fire"); } } internal void b__0_37(ConsoleEventArgs args) { if (args.Length - 1 < 1) { Terminal context = args.Context; if (context != null) { context.AddString("Not enough arguments "); } return; } string text = args[1]; WMRecipeCust.WLog.LogInfo((object)text); try { VisualController.Export(PrefabAssistant.Describe(text)); } catch { WMRecipeCust.WLog.LogWarning((object)"Error, Didnt save"); Terminal context2 = args.Context; if (context2 != null) { context2.AddString("Error, Didnt save"); } } Terminal context3 = args.Context; if (context3 != null) { context3.AddString("Saved in config folder Describe_" + text + ".yml"); } } internal List b__0_38() { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { return ZNetScene.instance.GetPrefabNames(); } return new List(); } internal void b__0_39(ConsoleEventArgs args) { if (args.Length - 1 < 1) { Terminal context = args.Context; if (context != null) { context.AddString("Not enough arguments"); } return; } string text = args[1]; string text2 = PrefabAssistant.SaveMaterial(text); if (text2 != null) { Terminal context2 = args.Context; if (context2 != null) { context2.AddString("Saved in the Material folder, as " + text2 + ".yml"); } } else { Terminal context3 = args.Context; if (context3 != null) { context3.AddString("Material '" + text + "' not found."); } } } } private static void Postfix() { //IL_004e: 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_0045: Expected O, but got Unknown //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_00d8: 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_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Expected O, but got Unknown //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Expected O, but got Unknown //IL_0148: 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_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Expected O, but got Unknown //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Expected O, but got Unknown //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Expected O, but got Unknown //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Expected O, but got Unknown //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_020b: Expected O, but got Unknown //IL_0232: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_023d: Expected O, but got Unknown //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_0261: Expected O, but got Unknown //IL_0288: Unknown result type (might be due to invalid IL or missing references) //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_0293: Expected O, but got Unknown //IL_02ba: 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_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Expected O, but got Unknown //IL_02de: 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_02e9: Expected O, but got Unknown //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_0302: Unknown result type (might be due to invalid IL or missing references) //IL_0307: Unknown result type (might be due to invalid IL or missing references) //IL_030d: Expected O, but got Unknown //IL_0334: Unknown result type (might be due to invalid IL or missing references) //IL_0339: Unknown result type (might be due to invalid IL or missing references) //IL_033f: Expected O, but got Unknown //IL_0366: 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_035d: Unknown result type (might be due to invalid IL or missing references) //IL_0363: Expected O, but got Unknown //IL_038a: Unknown result type (might be due to invalid IL or missing references) //IL_038f: Unknown result type (might be due to invalid IL or missing references) //IL_0395: Expected O, but got Unknown //IL_03bc: Unknown result type (might be due to invalid IL or missing references) //IL_03ae: Unknown result type (might be due to invalid IL or missing references) //IL_03b3: Unknown result type (might be due to invalid IL or missing references) //IL_03b9: Expected O, but got Unknown //IL_03f4: Unknown result type (might be due to invalid IL or missing references) //IL_03e0: Unknown result type (might be due to invalid IL or missing references) //IL_03e5: Unknown result type (might be due to invalid IL or missing references) //IL_03eb: Expected O, but got Unknown //IL_042c: Unknown result type (might be due to invalid IL or missing references) //IL_0418: 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_0423: Expected O, but got Unknown //IL_0464: Unknown result type (might be due to invalid IL or missing references) //IL_0450: Unknown result type (might be due to invalid IL or missing references) //IL_0455: Unknown result type (might be due to invalid IL or missing references) //IL_045b: Expected O, but got Unknown //IL_049c: Unknown result type (might be due to invalid IL or missing references) //IL_0488: Unknown result type (might be due to invalid IL or missing references) //IL_048d: Unknown result type (might be due to invalid IL or missing references) //IL_0493: Expected O, but got Unknown //IL_04d4: Unknown result type (might be due to invalid IL or missing references) //IL_04c0: Unknown result type (might be due to invalid IL or missing references) //IL_04c5: Unknown result type (might be due to invalid IL or missing references) //IL_04cb: Expected O, but got Unknown //IL_050c: Unknown result type (might be due to invalid IL or missing references) //IL_04f8: Unknown result type (might be due to invalid IL or missing references) //IL_04fd: Unknown result type (might be due to invalid IL or missing references) //IL_0503: Expected O, but got Unknown //IL_0544: Unknown result type (might be due to invalid IL or missing references) //IL_0530: Unknown result type (might be due to invalid IL or missing references) //IL_0535: Unknown result type (might be due to invalid IL or missing references) //IL_053b: Expected O, but got Unknown //IL_057c: Unknown result type (might be due to invalid IL or missing references) //IL_0568: Unknown result type (might be due to invalid IL or missing references) //IL_056d: Unknown result type (might be due to invalid IL or missing references) //IL_0573: Expected O, but got Unknown //IL_05b4: Unknown result type (might be due to invalid IL or missing references) //IL_05a0: Unknown result type (might be due to invalid IL or missing references) //IL_05a5: Unknown result type (might be due to invalid IL or missing references) //IL_05ab: Expected O, but got Unknown //IL_05ec: Unknown result type (might be due to invalid IL or missing references) //IL_05d8: Unknown result type (might be due to invalid IL or missing references) //IL_05dd: Unknown result type (might be due to invalid IL or missing references) //IL_05e3: Expected O, but got Unknown //IL_0624: Unknown result type (might be due to invalid IL or missing references) //IL_0610: Unknown result type (might be due to invalid IL or missing references) //IL_0615: Unknown result type (might be due to invalid IL or missing references) //IL_061b: Expected O, but got Unknown //IL_065c: Unknown result type (might be due to invalid IL or missing references) //IL_0648: Unknown result type (might be due to invalid IL or missing references) //IL_064d: Unknown result type (might be due to invalid IL or missing references) //IL_0653: Expected O, but got Unknown //IL_0694: Unknown result type (might be due to invalid IL or missing references) //IL_0680: Unknown result type (might be due to invalid IL or missing references) //IL_0685: Unknown result type (might be due to invalid IL or missing references) //IL_068b: Expected O, but got Unknown //IL_06b8: Unknown result type (might be due to invalid IL or missing references) //IL_06bd: Unknown result type (might be due to invalid IL or missing references) //IL_06c3: Expected O, but got Unknown //IL_06ea: Unknown result type (might be due to invalid IL or missing references) //IL_06dc: Unknown result type (might be due to invalid IL or missing references) //IL_06e1: Unknown result type (might be due to invalid IL or missing references) //IL_06e7: Expected O, but got Unknown //IL_070e: Unknown result type (might be due to invalid IL or missing references) //IL_0713: Unknown result type (might be due to invalid IL or missing references) //IL_0719: Expected O, but got Unknown //IL_0740: Unknown result type (might be due to invalid IL or missing references) //IL_0732: Unknown result type (might be due to invalid IL or missing references) //IL_0737: Unknown result type (might be due to invalid IL or missing references) //IL_073d: Expected O, but got Unknown //IL_0778: Unknown result type (might be due to invalid IL or missing references) //IL_0764: Unknown result type (might be due to invalid IL or missing references) //IL_0769: Unknown result type (might be due to invalid IL or missing references) //IL_076f: Expected O, but got Unknown //IL_079c: Unknown result type (might be due to invalid IL or missing references) //IL_07a1: Unknown result type (might be due to invalid IL or missing references) //IL_07a7: Expected O, but got Unknown //IL_07ce: Unknown result type (might be due to invalid IL or missing references) //IL_07c0: Unknown result type (might be due to invalid IL or missing references) //IL_07c5: Unknown result type (might be due to invalid IL or missing references) //IL_07cb: Expected O, but got Unknown //IL_0806: Unknown result type (might be due to invalid IL or missing references) //IL_07f2: Unknown result type (might be due to invalid IL or missing references) //IL_07f7: Unknown result type (might be due to invalid IL or missing references) //IL_07fd: Expected O, but got Unknown WMRecipeCust.WLog.LogDebug((object)"Patching Updated Console Commands"); if (!WMRecipeCust.modEnabled.Value) { return; } object obj = <>c.<>9__0_0; if (obj == null) { ConsoleEvent val = delegate(ConsoleEventArgs args) { WMRecipeCust.WLog.LogWarning((object)" deleting Cache"); WMRecipeCust.DeleteCache(); MaterialDataManager.Instance.materials.Clear(); TextureDataManager.textureCache.Clear(); Terminal context45 = args.Context; if (context45 != null) { context45.AddString("deleting Cache"); } }; <>c.<>9__0_0 = val; obj = (object)val; } new ConsoleCommand("wackydb_clearcache", "ClearCache", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj2 = <>c.<>9__0_1; if (obj2 == null) { ConsoleEvent val2 = delegate { foreach (GameObject item in WMRecipeCust.SnapshotPiecestoDo) { Functions.SnapshotPiece(item); } }; <>c.<>9__0_1 = val2; obj2 = (object)val2; } new ConsoleCommand("wackydb_snapshot", "snapshot", (ConsoleEvent)obj2, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); Scene activeScene = SceneManager.GetActiveScene(); if (((Scene)(ref activeScene)).name != "main") { return; } object obj3 = <>c.<>9__0_2; if (obj3 == null) { ConsoleEvent val3 = delegate(ConsoleEventArgs args) { string text29 = "wackydb_reload -reloads on client or server\r\nwackydb_save_recipe [RecipeName](recipe output)\r\nwackydb_save_piece [PieceName](piece output) \r\nwackydb_save_item [ItemName](item Output)\r\nwackydb_save_creature [CreatureName](Creature Output)\r\nwackydb_save_pickable [PickableName](Pickable Output)\r\nwackydb_save_material [MaterialName] Save Material Info - Usually has _mat\r\nwackydb_se [SEEffectName] Save SEeffect\r\nwackydb_help\r\nwackydb_clone [item/recipe/piece/creatures/material/se/pickables] [Prefab to clone] [Unique name for the clone] \r\n4th paramater for recipes - you can already have item WackySword loaded in game, but now want a recipe. WackySword Uses SwordIron - wackydb_clone recipe WackySword RWackySword SwordIron - otherwise manually edit\r\nwackydb_clone_recipeitem [Prefab to clone] [Unique name for the clone](Recipe name will be Rname) (clones item and recipe at same time)\r\nwackydb_vfx (outputs vfx gameobjects available)\r\nwackydb_fx (outputs fx gameobjects available)\r\nwackydb_sfx (outputs Sfx gameobjects available)\r\nwackydb_material (outputs Materials available)\r\nwackydb_sendtheload -experimental\r\nwackydb_get_piecehammers -Get All Hammer in Game\r\nwackydb_all_se -Save All SE Effects to Bulk Folder\r\nwackydb_all_items -Save ALL Items to Bulk Folder\r\nwackydb_all_recipes -Save all Recipes to Bulk Folder\r\nwackydb_all_pieces [Hammer][Optional-Category]-Save all Pieces to Bulk Folder: default hammer, optionally by category\r\nwackydb_all_creatures -Save All Creatures\r\nwackydb_all_pickables -Save All Pickables and Tree Bases\r\nwackydb_describe [ObjectName] Describe an Objects Visual Data\r\nwackydb_clearcache Clears cache\r\nwackydb_snapshot Reloads snapshot after wackydb_reload\r\n"; Terminal context44 = args.Context; if (context44 != null) { context44.AddString(text29); } }; <>c.<>9__0_2 = val3; obj3 = (object)val3; } new ConsoleCommand("wackydb", "Display Help ", (ConsoleEvent)obj3, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj4 = <>c.<>9__0_3; if (obj4 == null) { ConsoleEvent val4 = delegate(ConsoleEventArgs args) { string text28 = "wackydb_reload\r\nwackydb_save_recipe [RecipeName](recipe output)\r\nwackydb_save_piece [PieceName](piece output) \r\nwackydb_save_item [ItemName](item Output)\r\nwackydb_save_creature [CreatureName](Creature Output)\r\nwackydb_save_pickable [PickableName](Pickable Output)\r\nwackydb_save_material [MaterialName] Save Material Info - Usually has _mat\r\nwackydb_se [SEEffectName] Save SEeffect\r\nwackydb_help\r\nwackydb_clone [item/recipe/piece/creatures/material/se/pickables] [Prefab to clone] [Unique name for the clone] \r\n4th paramater for recipes - you can already have item WackySword loaded in game, but now want a recipe. WackySword Uses SwordIron - wackydb_clone recipe WackySword RWackySword SwordIron - otherwise manually edit\r\nwackydb_clone_recipeitem [Prefab to clone] [Unique name for the clone](Recipe name will be Rname) (clones item and recipe at same time)\r\nwackydb_vfx (outputs vfx gameobjects available)\r\nwackydb_fx (outputs fx gameobjects available)\r\nwackydb_sfx (outputs Sfx gameobjects available)\r\nwackydb_material (outputs Materials available)\r\nwackydb_sendtheload -experimental\r\nwackydb_get_piecehammers -Get All Hammer in Game\r\nwackydb_all_se -Save All SE Effects to Bulk Folder\r\nwackydb_all_items -Save ALL Items to Bulk Folder\r\nwackydb_all_recipes -Save all Recipes to Bulk Folder\r\nwackydb_all_pieces [Hammer][Optional-Category]-Save all Pieces to Bulk Folder: default hammer, optionally by category\r\nwackydb_all_creatures -Save All Creatures\r\nwackydb_all_pickables -Save All Pickables and Tree Bases\r\nwackydb_describe [ObjectName] Describe an Objects Visual Data\r\nwackydb_clearcache Clears cache\r\nwackydb_snapshot Reloads snapshot after wackydb_reload\r\n"; Terminal context43 = args.Context; if (context43 != null) { context43.AddString(text28); } }; <>c.<>9__0_3 = val4; obj4 = (object)val4; } new ConsoleCommand("wackydb_help", "Display Help ", (ConsoleEvent)obj4, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj5 = <>c.<>9__0_4; if (obj5 == null) { ConsoleEvent val5 = delegate(ConsoleEventArgs args) { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown if (Object.op_Implicit((Object)(object)ObjectDB.instance) && WMRecipeCust.issettoSinglePlayer) { ReadFiles readFiles2 = new ReadFiles(); ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(readFiles2.GetDataFromFiles(slowmode: true)); WMRecipeCust.readFiles = readFiles2; Reload reload2 = (WMRecipeCust.CurrentReload = new Reload()); if (WMRecipeCust.HasLobbied) { ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(reload2.LoadAllRecipeData(reload: true, slowmode: true, forcepush: true)); WMRecipeCust.Dbgl("Admin: Forcing Push after reload"); Terminal context40 = args.Context; if (context40 != null) { context40.AddString("Admin: Forcing Push after reload"); } } else { ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(reload2.LoadAllRecipeData(reload: true, slowmode: true)); } } else if (WMRecipeCust.Admin) { ZPackage val46 = new ZPackage(); val46.Write("true"); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "WackyDBAdminReload", new object[1] { val46 }); WMRecipeCust.Dbgl("Admin: Attempting to tell Server to reload"); Terminal context41 = args.Context; if (context41 != null) { context41.AddString("Admin: Attempting to tell Server to reload"); } } else { Terminal context42 = args.Context; if (context42 != null) { context42.AddString("WackyDatabase did NOT reload recipes/items/pieces from files"); } WMRecipeCust.Dbgl("WackyDatabase did NOT reload recipes/items/pieces from files"); } }; <>c.<>9__0_4 = val5; obj5 = (object)val5; } new ConsoleCommand("wackydb_reload", "reload the whole config files", (ConsoleEvent)obj5, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj6 = <>c.<>9__0_5; if (obj6 == null) { ConsoleEvent val6 = delegate(ConsoleEventArgs args) { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && WMRecipeCust.issettoSinglePlayer) { ReadFiles readFiles = new ReadFiles(); ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(readFiles.GetDataFromFiles()); WMRecipeCust.readFiles = readFiles; Reload reload = (WMRecipeCust.CurrentReload = new Reload()); ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(reload.LoadAllRecipeData(reload: true)); Terminal context39 = args.Context; if (context39 != null) { context39.AddString("WackyDatabase reloaded recipes/items/pieces from files"); } } }; <>c.<>9__0_5 = val6; obj6 = (object)val6; } new ConsoleCommand("wackydb_reload_fast", "reload the whole config files fast", (ConsoleEvent)obj6, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj7 = <>c.<>9__0_6; if (obj7 == null) { ConsoleEvent val7 = delegate(ConsoleEventArgs args) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown if (WMRecipeCust.Admin) { if (WMRecipeCust.issettoSinglePlayer) { Terminal context37 = args.Context; if (context37 != null) { context37.AddString("You are in singleplayer, no clients to send the load to."); } } else { ZPackage val45 = new ZPackage(); val45.Write("true"); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "WackyDBAdminBigData", new object[1] { val45 }); WMRecipeCust.Dbgl("Admin: Attempting to tell Server to Send the Motherload"); Terminal context38 = args.Context; if (context38 != null) { context38.AddString("Admin: Attempting to tell Server to Send the Motherload"); } } } }; <>c.<>9__0_6 = val7; obj7 = (object)val7; } new ConsoleCommand("wackydb_sendtheload", "Sends images/icons/obj to clients, highly experimental", (ConsoleEvent)obj7, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj8 = <>c.<>9__0_7; if (obj8 == null) { ConsoleEvent val8 = delegate(ConsoleEventArgs args) { string text27 = args[1]; WItemData itemDataByName4 = new GetDataYML().GetItemDataByName(text27, ObjectDB.instance); if (itemDataByName4 != null) { WMRecipeCust.CheckModFolder(); ISerializer serializer15 = new SerializerBuilder().WithNewLine("\n").Build(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathItems, "Item_" + itemDataByName4.name + ".yml"), serializer15.Serialize(itemDataByName4)); Terminal context36 = args.Context; if (context36 != null) { context36.AddString("saved item data to Item_" + text27 + ".yml"); } } }; <>c.<>9__0_7 = val8; obj8 = (object)val8; } object obj9 = <>c.<>9__0_8; if (obj9 == null) { ConsoleOptionsFetcher val9 = () => Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefabNames() : new List(); <>c.<>9__0_8 = val9; obj9 = (object)val9; } new ConsoleCommand("wackydb_save_item", "Save an Item ", (ConsoleEvent)obj8, false, false, false, false, false, (ConsoleOptionsFetcher)obj9, false, false, false); object obj10 = <>c.<>9__0_9; if (obj10 == null) { ConsoleEvent val10 = delegate(ConsoleEventArgs args) { string text26 = args[1]; PieceData pieceRecipeByName2 = new GetDataYML().GetPieceRecipeByName(text26, ObjectDB.instance); if (pieceRecipeByName2 != null) { WMRecipeCust.CheckModFolder(); ISerializer serializer14 = new SerializerBuilder().WithNewLine("\n").Build(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathPieces, "Piece_" + pieceRecipeByName2.name + ".yml"), serializer14.Serialize(pieceRecipeByName2)); Terminal context35 = args.Context; if (context35 != null) { context35.AddString("saved data to Piece_" + text26 + ".yml"); } } }; <>c.<>9__0_9 = val10; obj10 = (object)val10; } object obj11 = <>c.<>9__0_10; if (obj11 == null) { ConsoleOptionsFetcher val11 = () => Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefabNames() : new List(); <>c.<>9__0_10 = val11; obj11 = (object)val11; } new ConsoleCommand("wackydb_save_piece", "Save a piece ", (ConsoleEvent)obj10, false, false, false, false, false, (ConsoleOptionsFetcher)obj11, false, false, false); object obj12 = <>c.<>9__0_11; if (obj12 == null) { ConsoleEvent val12 = delegate(ConsoleEventArgs args) { string text25 = args[1]; RecipeData recipeDataByName5 = new GetDataYML().GetRecipeDataByName(text25, ObjectDB.instance); if (recipeDataByName5 != null) { WMRecipeCust.CheckModFolder(); ISerializer serializer13 = new SerializerBuilder().WithNewLine("\n").Build(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathRecipes, "Recipe_" + recipeDataByName5.name + ".yml"), serializer13.Serialize(recipeDataByName5)); Terminal context34 = args.Context; if (context34 != null) { context34.AddString("saved data to Recipe_" + text25 + ".yml"); } } }; <>c.<>9__0_11 = val12; obj12 = (object)val12; } object obj13 = <>c.<>9__0_12; if (obj13 == null) { ConsoleOptionsFetcher val13 = () => Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefabNames() : new List(); <>c.<>9__0_12 = val13; obj13 = (object)val13; } new ConsoleCommand("wackydb_save_recipe", "Save a recipe ", (ConsoleEvent)obj12, false, false, false, false, false, (ConsoleOptionsFetcher)obj13, false, false, false); object obj14 = <>c.<>9__0_13; if (obj14 == null) { ConsoleEvent val14 = delegate(ConsoleEventArgs args) { string text24 = args[1]; CreatureData creature2 = new GetDataYML().GetCreature(text24); if (creature2 != null) { WMRecipeCust.CheckModFolder(); ISerializer serializer12 = new SerializerBuilder().WithNewLine("\n").Build(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathCreatures, "Creature_" + creature2.name + ".yml"), serializer12.Serialize(creature2)); Terminal context33 = args.Context; if (context33 != null) { context33.AddString("saved data to Creature_" + text24 + ".yml"); } } }; <>c.<>9__0_13 = val14; obj14 = (object)val14; } object obj15 = <>c.<>9__0_14; if (obj15 == null) { ConsoleOptionsFetcher val15 = () => Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefabNames() : new List(); <>c.<>9__0_14 = val15; obj15 = (object)val15; } new ConsoleCommand("wackydb_save_creature", "Save a Creature ", (ConsoleEvent)obj14, false, false, false, false, false, (ConsoleOptionsFetcher)obj15, false, false, false); object obj16 = <>c.<>9__0_15; if (obj16 == null) { ConsoleEvent val16 = delegate(ConsoleEventArgs args) { string text22 = args[1]; GetDataYML getDataYML11 = new GetDataYML(); Pickable[] array3 = Resources.FindObjectsOfTypeAll(); PickableData pickable2 = getDataYML11.GetPickable(text22, array3); TreeBase[] array4 = Resources.FindObjectsOfTypeAll(); TreeBaseData treeBase2 = getDataYML11.GetTreeBase(text22, array4); string text23 = "Pickable"; if (pickable2 == null) { text23 = "Treebase_"; if (treeBase2 == null) { return; } } WMRecipeCust.CheckModFolder(); ISerializer serializer11 = new SerializerBuilder().WithNewLine("\n").Build(); if (text23 == "Pickable") { File.WriteAllText(Path.Combine(WMRecipeCust.assetPathPickables, "Pickable_" + pickable2.name + ".yml"), serializer11.Serialize(pickable2)); } else { File.WriteAllText(Path.Combine(WMRecipeCust.assetPathPickables, text23 + treeBase2.name + ".yml"), serializer11.Serialize(treeBase2)); } Terminal context32 = args.Context; if (context32 != null) { context32.AddString("Saved data to Folder Pickables " + text23 + "_" + text22 + ".yml"); } }; <>c.<>9__0_15 = val16; obj16 = (object)val16; } object obj17 = <>c.<>9__0_16; if (obj17 == null) { ConsoleOptionsFetcher val17 = () => Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefabNames() : new List(); <>c.<>9__0_16 = val17; obj17 = (object)val17; } new ConsoleCommand("wackydb_save_pickable", "Save a Pickable or Treebase ", (ConsoleEvent)obj16, false, false, false, false, false, (ConsoleOptionsFetcher)obj17, false, false, false); object obj18 = <>c.<>9__0_17; if (obj18 == null) { ConsoleEvent val18 = delegate(ConsoleEventArgs args) { WMRecipeCust.CheckModFolder(); if (args.Length - 1 < 1) { Terminal context30 = args.Context; if (context30 != null) { context30.AddString("Not enough arguments"); } } else { ISerializer serializer10 = new SerializerBuilder().WithNewLine("\n").Build(); GetDataYML getDataYML10 = new GetDataYML(); string text20 = args[1]; WItemData itemDataByName3 = getDataYML10.GetItemDataByName(text20, ObjectDB.instance); if (itemDataByName3 != null) { File.WriteAllText(Path.Combine(WMRecipeCust.assetPathItems, "Item_" + itemDataByName3.name + ".yml"), serializer10.Serialize(itemDataByName3)); string text21 = ""; RecipeData recipeDataByName4 = getDataYML10.GetRecipeDataByName(text20, ObjectDB.instance); if (recipeDataByName4 != null) { File.WriteAllText(Path.Combine(WMRecipeCust.assetPathRecipes, "Recipe_" + recipeDataByName4.name + ".yml"), serializer10.Serialize(recipeDataByName4)); text21 = "Item saved as Item_" + itemDataByName3.name + ".yml, Recipe saved as Recipe_" + recipeDataByName4.name + ".yml"; } else { recipeDataByName4 = getDataYML10.GetRecipeDataByName("Club", ObjectDB.instance); if (recipeDataByName4 == null) { return; } recipeDataByName4.name = "R" + text20; recipeDataByName4.clonePrefabName = text20; text21 = "Item saved as Item_" + itemDataByName3.name + ".yml, Recipe saved as a clone from 'Club' Recipe_" + recipeDataByName4.name + ".yml"; File.WriteAllText(Path.Combine(WMRecipeCust.assetPathRecipes, "Recipe_" + recipeDataByName4.name + ".yml"), serializer10.Serialize(recipeDataByName4)); } Terminal context31 = args.Context; if (context31 != null) { context31.AddString(text21 ?? ""); } } } }; <>c.<>9__0_17 = val18; obj18 = (object)val18; } object obj19 = <>c.<>9__0_18; if (obj19 == null) { ConsoleOptionsFetcher val19 = () => Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefabNames() : new List(); <>c.<>9__0_18 = val19; obj19 = (object)val19; } new ConsoleCommand("wackydb_save_recipeitem", "Save the recipe and item at the same time, this will create a recipe if not found", (ConsoleEvent)obj18, false, false, false, false, false, (ConsoleOptionsFetcher)obj19, false, false, false); object obj20 = <>c.<>9__0_19; if (obj20 == null) { ConsoleEvent val20 = delegate(ConsoleEventArgs args) { string allMaterialsFile = Functions.GetAllMaterialsFile(); WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathconfig, "Materials.txt"), allMaterialsFile); Terminal context29 = args.Context; if (context29 != null) { context29.AddString("saved data to Materials.txt"); } WMRecipeCust.WLog.LogInfo((object)"saved data to Materials.txt"); }; <>c.<>9__0_19 = val20; obj20 = (object)val20; } new ConsoleCommand("wackydb_material", "Create txt file of materials", (ConsoleEvent)obj20, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj21 = <>c.<>9__0_20; if (obj21 == null) { ConsoleEvent val21 = delegate(ConsoleEventArgs args) { string text19 = ""; PieceTable[] maybePieceStations = WMRecipeCust.MaybePieceStations; foreach (PieceTable val44 in maybePieceStations) { text19 = text19 + ((object)val44).ToString() + " \r\n"; } File.WriteAllText(Path.Combine(WMRecipeCust.assetPathconfig, "Hammers.txt"), text19); Terminal context28 = args.Context; if (context28 != null) { context28.AddString("saved data to Hammers.txt"); } WMRecipeCust.WLog.LogInfo((object)"saved data to Hammers.txt"); }; <>c.<>9__0_20 = val21; obj21 = (object)val21; } new ConsoleCommand("wackydb_get_piecehammers", "Create txt file of PieceHammers/PieceStations", (ConsoleEvent)obj21, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj22 = <>c.<>9__0_21; if (obj22 == null) { ConsoleEvent val22 = delegate(ConsoleEventArgs args) { string allVFXFile = Functions.GetAllVFXFile(); WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathconfig, "vfx.txt"), allVFXFile); Terminal context27 = args.Context; if (context27 != null) { context27.AddString("saved data to VFX.txt"); } WMRecipeCust.WLog.LogInfo((object)"saved data to VFX.txt"); }; <>c.<>9__0_21 = val22; obj22 = (object)val22; } new ConsoleCommand("wackydb_vfx", "Create txt file of VFX", (ConsoleEvent)obj22, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj23 = <>c.<>9__0_22; if (obj23 == null) { ConsoleEvent val23 = delegate(ConsoleEventArgs args) { string allSFXFile = Functions.GetAllSFXFile(); WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathconfig, "sfx.txt"), allSFXFile); Terminal context26 = args.Context; if (context26 != null) { context26.AddString("saved data to sfx.txt"); } WMRecipeCust.WLog.LogInfo((object)"saved data to sfx.txt"); }; <>c.<>9__0_22 = val23; obj23 = (object)val23; } new ConsoleCommand("wackydb_sfx", "Create txt file of SFX", (ConsoleEvent)obj23, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj24 = <>c.<>9__0_23; if (obj24 == null) { ConsoleEvent val24 = delegate(ConsoleEventArgs args) { string allFXFile = Functions.GetAllFXFile(); WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathconfig, "FX.txt"), allFXFile); Terminal context25 = args.Context; if (context25 != null) { context25.AddString("saved data to FX.txt"); } WMRecipeCust.WLog.LogInfo((object)"saved data to FX.txt"); }; <>c.<>9__0_23 = val24; obj24 = (object)val24; } new ConsoleCommand("wackydb_fx", "Create txt file of FX - iffy", (ConsoleEvent)obj24, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj25 = <>c.<>9__0_24; if (obj25 == null) { ConsoleEvent val25 = delegate(ConsoleEventArgs args) { ObjectDB instance7 = ObjectDB.instance; int num7 = instance7.m_StatusEffects.Count(); GetDataYML getDataYML9 = new GetDataYML(); int num8 = 0; if (!Directory.Exists(WMRecipeCust.assetPathBulkYML)) { WMRecipeCust.Dbgl("Creating wackyDatabase-BulkYML Folder in Config"); Directory.CreateDirectory(WMRecipeCust.assetPathBulkYML); } if (!Directory.Exists(WMRecipeCust.assetPathBulkYMLEffects)) { Directory.CreateDirectory(WMRecipeCust.assetPathBulkYMLEffects); } ISerializer serializer9 = new SerializerBuilder().WithNewLine("\n").Build(); while (num8 != num7) { StatusData statusEByNum = getDataYML9.GetStatusEByNum(num8, instance7); num8++; if (statusEByNum != null) { string contents5 = serializer9.Serialize(statusEByNum); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathBulkYMLEffects, "SE_" + statusEByNum.Name + ".yml"), contents5); } } Terminal context24 = args.Context; if (context24 != null) { context24.AddString("saved all Status Effects to wackyDatabase-BulkYML Effects"); } WMRecipeCust.WLog.LogInfo((object)"saved all Status Effects to wackyDatabase-BulkYML Effects"); }; <>c.<>9__0_24 = val25; obj25 = (object)val25; } new ConsoleCommand("wackydb_all_se", "Get all SE effects in game and create your own", (ConsoleEvent)obj25, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj26 = <>c.<>9__0_25; if (obj26 == null) { ConsoleEvent val26 = delegate(ConsoleEventArgs args) { if (!Directory.Exists(WMRecipeCust.assetPathBulkYML)) { WMRecipeCust.Dbgl("Creating wackyDatabase-BulkYML Folder in Config"); Directory.CreateDirectory(WMRecipeCust.assetPathBulkYML); } if (!Directory.Exists(WMRecipeCust.assetPathBulkYMLItems)) { Directory.CreateDirectory(WMRecipeCust.assetPathBulkYMLItems); } ObjectDB instance6 = ObjectDB.instance; int num5 = instance6.m_items.Count(); GetDataYML getDataYML8 = new GetDataYML(); int num6 = 0; ISerializer serializer8 = new SerializerBuilder().WithNewLine("\n").Build(); while (num6 != num5) { WItemData itemDataByCount = getDataYML8.GetItemDataByCount(num6, instance6); num6++; if (itemDataByCount != null) { string contents4 = serializer8.Serialize(itemDataByCount); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathBulkYMLItems, "Item_" + itemDataByCount.name + ".yml"), contents4); } } Terminal context23 = args.Context; if (context23 != null) { context23.AddString("saved all Items in WackyBulk Items"); } WMRecipeCust.WLog.LogInfo((object)"saved all Items in WackyBulk Items"); }; <>c.<>9__0_25 = val26; obj26 = (object)val26; } new ConsoleCommand("wackydb_all_items", "Get all Items in game", (ConsoleEvent)obj26, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj27 = <>c.<>9__0_26; if (obj27 == null) { ConsoleEvent val27 = delegate(ConsoleEventArgs args) { if (!Directory.Exists(WMRecipeCust.assetPathBulkYML)) { WMRecipeCust.Dbgl("Creating wackyDatabase-BulkYML Folder in Config"); Directory.CreateDirectory(WMRecipeCust.assetPathBulkYML); } if (!Directory.Exists(WMRecipeCust.assetPathBulkYMLCreatures)) { Directory.CreateDirectory(WMRecipeCust.assetPathBulkYMLCreatures); } new GetDataYML().GetAllCreature(); Terminal context22 = args.Context; if (context22 != null) { context22.AddString("saved all Creatures in WackyBulk "); } WMRecipeCust.WLog.LogInfo((object)"saved all Creatures in WackyBulk "); }; <>c.<>9__0_26 = val27; obj27 = (object)val27; } new ConsoleCommand("wackydb_all_creatures", "Get all Creatures in game", (ConsoleEvent)obj27, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj28 = <>c.<>9__0_27; if (obj28 == null) { ConsoleEvent val28 = delegate(ConsoleEventArgs args) { if (!Directory.Exists(WMRecipeCust.assetPathBulkYML)) { WMRecipeCust.Dbgl("Creating wackyDatabase-BulkYML Folder in Config"); Directory.CreateDirectory(WMRecipeCust.assetPathBulkYML); } if (!Directory.Exists(WMRecipeCust.assetPathBulkYMLRecipes)) { Directory.CreateDirectory(WMRecipeCust.assetPathBulkYMLRecipes); } ObjectDB instance5 = ObjectDB.instance; int num3 = instance5.m_recipes.Count(); GetDataYML getDataYML7 = new GetDataYML(); int num4 = 0; ISerializer serializer7 = new SerializerBuilder().WithNewLine("\n").Build(); while (num4 != num3) { RecipeData recipeDataByNum = getDataYML7.GetRecipeDataByNum(num4, instance5); num4++; if (recipeDataByNum != null) { string contents3 = serializer7.Serialize(recipeDataByNum); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathBulkYMLRecipes, "Recipe_" + recipeDataByNum.name + ".yml"), contents3); } } Terminal context21 = args.Context; if (context21 != null) { context21.AddString("saved all Recipes in WackyBulk Recipes Folder"); } WMRecipeCust.WLog.LogInfo((object)"saved all Recipes in WackyBulk Recipes Folder"); }; <>c.<>9__0_27 = val28; obj28 = (object)val28; } new ConsoleCommand("wackydb_all_recipes", "Get all Recipes in game", (ConsoleEvent)obj28, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj29 = <>c.<>9__0_28; if (obj29 == null) { ConsoleEvent val29 = delegate(ConsoleEventArgs args) { if (!Directory.Exists(WMRecipeCust.assetPathBulkYML)) { WMRecipeCust.Dbgl("Creating wackyDatabase-BulkYML Folder in Config"); Directory.CreateDirectory(WMRecipeCust.assetPathBulkYML); } if (!Directory.Exists(WMRecipeCust.assetPathBulkYMLPickables)) { Directory.CreateDirectory(WMRecipeCust.assetPathBulkYMLPickables); } new GetDataYML().GetAllPickables(); Terminal context20 = args.Context; if (context20 != null) { context20.AddString("saved all Pickables/TreeBases in WackyBulk Pickables Folder"); } WMRecipeCust.WLog.LogInfo((object)"saved all Pickables/TreeBases in WackyBulk Pickables Folder"); }; <>c.<>9__0_28 = val29; obj29 = (object)val29; } new ConsoleCommand("wackydb_all_pickables", "Get all Pickables/TreeBase in game", (ConsoleEvent)obj29, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj30 = <>c.<>9__0_29; if (obj30 == null) { ConsoleEvent val30 = delegate(ConsoleEventArgs args) { //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_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) if (args.Length - 1 < 1) { Terminal context16 = args.Context; if (context16 != null) { context16.AddString("Enter a piece hammer default hammer is Hammer"); } } else { string text17 = null; string text18 = args[1]; if (text18.ToLower() == "hammer") { text18 = "Hammer"; } if (text18.ToLower() == "hoe") { text18 = "Hoe"; } if (args.Length - 1 == 2) { text17 = args[2]; } if (!Directory.Exists(WMRecipeCust.assetPathBulkYML)) { WMRecipeCust.Dbgl("Creating wackyDatabase-BulkYML Folder in Config"); Directory.CreateDirectory(WMRecipeCust.assetPathBulkYML); } if (!Directory.Exists(WMRecipeCust.assetPathBulkYMLPieces)) { Directory.CreateDirectory(WMRecipeCust.assetPathBulkYMLPieces); } ObjectDB instance4 = ObjectDB.instance; ItemDrop val42 = null; try { val42 = instance4.GetItemPrefab(text18).GetComponent(); } catch { WMRecipeCust.WLog.LogWarning((object)(text18 + " not found")); return; } int num = val42.m_itemData.m_shared.m_buildPieces.m_pieces.Count(); WMRecipeCust.WLog.LogWarning((object)$"Count is {num} for m__pieces"); if (text17 != null) { List list = null; try { PieceCategory val43 = (PieceCategory)Enum.Parse(typeof(PieceCategory), text17); WMRecipeCust.WLog.LogWarning((object)"Piece Hammer CAt"); num = val42.m_itemData.m_shared.m_buildPieces.GetAvailablePiecesInCategory(val43); val42.m_itemData.m_shared.m_buildPieces.m_selectedCategory = val43; list = val42.m_itemData.m_shared.m_buildPieces.GetPiecesInSelectedCategory(); } catch { WMRecipeCust.WLog.LogWarning((object)(text17 + " category was not parsed correclty")); text17 = null; } if (list != null) { GetDataYML getDataYML5 = new GetDataYML(); ISerializer serializer5 = new SerializerBuilder().WithNewLine("\n").Build(); foreach (Piece item2 in list) { PieceData piece = getDataYML5.GetPiece(val42, text18, ((Component)item2).gameObject, instance4); if (piece != null) { string contents = serializer5.Serialize(piece); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathBulkYMLPieces, "Piece_" + piece.name + ".yml"), contents); } } Terminal context17 = args.Context; if (context17 != null) { context17.AddString("saved all Pieces from hammer " + text18 + " with category " + text17 + " in WackyBulk Pieces"); } WMRecipeCust.WLog.LogInfo((object)("saved all Pieces from hammer " + text18 + " with category " + text17 + " in WackyBulk Pieces")); } else { Terminal context18 = args.Context; if (context18 != null) { context18.AddString("Failure for category saving of pieces " + text18 + " in WackyBulk"); } WMRecipeCust.WLog.LogWarning((object)("Failure for category saving of pieces " + text18 + " in WackyBulk")); } } else { GetDataYML getDataYML6 = new GetDataYML(); int num2 = 0; ISerializer serializer6 = new SerializerBuilder().WithNewLine("\n").Build(); while (num2 != num) { PieceData pieceRecipeByNum = getDataYML6.GetPieceRecipeByNum(num2, text18, val42, instance4); num2++; if (pieceRecipeByNum != null) { string contents2 = serializer6.Serialize(pieceRecipeByNum); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathBulkYMLPieces, "Piece_" + pieceRecipeByNum.name + ".yml"), contents2); } } Terminal context19 = args.Context; if (context19 != null) { context19.AddString("saved all Pieces from hammer " + text18 + " in WackyBulk"); } WMRecipeCust.WLog.LogInfo((object)("saved all Pieces from hammer " + text18 + " in WackyBulk")); } } }; <>c.<>9__0_29 = val30; obj30 = (object)val30; } new ConsoleCommand("wackydb_all_pieces", "Get all Pieces in game by hammer and optionally by category", (ConsoleEvent)obj30, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj31 = <>c.<>9__0_30; if (obj31 == null) { ConsoleEvent val31 = delegate(ConsoleEventArgs args) { string text16 = args[1]; ObjectDB instance3 = ObjectDB.instance; GetDataYML getDataYML4 = new GetDataYML(); ISerializer serializer4 = new SerializerBuilder().WithNewLine("\n").Build(); StatusData statusEByName3 = getDataYML4.GetStatusEByName(text16, instance3); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathEffects, "SE_" + statusEByName3.Name + ".yml"), serializer4.Serialize(statusEByName3)); Terminal context15 = args.Context; if (context15 != null) { context15.AddString("saved SE effect " + text16 + " to SE_" + text16 + ".yml in Effects folder"); } WMRecipeCust.WLog.LogInfo((object)("saved SE effect " + text16 + " to SE_" + text16 + ".yml in Effects folder")); }; <>c.<>9__0_30 = val31; obj31 = (object)val31; } new ConsoleCommand("wackydb_se", "Get one SE effect by name", (ConsoleEvent)obj31, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj32 = <>c.<>9__0_31; if (obj32 == null) { ConsoleEvent val32 = delegate(ConsoleEventArgs args) { ObjectDB instance2 = ObjectDB.instance; GetDataYML getDataYML3 = new GetDataYML(); ISerializer serializer3 = new SerializerBuilder().WithNewLine("\n").Build(); StatusData statusEByName2 = getDataYML3.GetStatusEByName("SetEffect_TrollArmor", instance2); statusEByName2.Name = "SetEffect_New" + new Random().Next(1, 1000); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathEffects, "SE_" + statusEByName2.Name + ".yml"), serializer3.Serialize(statusEByName2)); Terminal context14 = args.Context; if (context14 != null) { context14.AddString("Created a clone from SetEffect_TrollArmor, saved as a file SE_" + statusEByName2.Name + ".yml in Effects folder, PLEASE ReNAME"); } WMRecipeCust.WLog.LogInfo((object)("Created a clone from SetEffect_TrollArmor, saved as a file SE_" + statusEByName2.Name + ".yml in Effects folder, PLEASE ReNAME")); }; <>c.<>9__0_31 = val32; obj32 = (object)val32; } new ConsoleCommand("wackydb_se_create", "Create a clone se_effect to use", (ConsoleEvent)obj32, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj33 = <>c.<>9__0_32; if (obj33 == null) { ConsoleEvent val33 = delegate(ConsoleEventArgs args) { //IL_061a: Unknown result type (might be due to invalid IL or missing references) //IL_061f: Unknown result type (might be due to invalid IL or missing references) //IL_0631: Unknown result type (might be due to invalid IL or missing references) //IL_064c: Expected I4, but got Unknown //IL_0663: Unknown result type (might be due to invalid IL or missing references) //IL_06b2: Unknown result type (might be due to invalid IL or missing references) //IL_06bc: Expected O, but got Unknown if (args.Length - 1 < 3) { Terminal context9 = args.Context; if (context9 != null) { context9.AddString("Not enough arguments"); } } else { string text10 = args[1]; string text11 = args[2]; string text12 = args[3]; string text13 = args[3]; if (text12 == "SwordTest") { Terminal context10 = args.Context; if (context10 != null) { context10.AddString("" + text12 + " is already a ingame name. -Bad "); } } else { ISerializer serializer2 = new SerializerBuilder().WithNewLine("\n").Build(); GetDataYML getDataYML2 = new GetDataYML(); if (text10 == "recipe" || text10 == "Recipe") { WMRecipeCust.CheckModFolder(); if (args.Length - 1 < 4) { RecipeData recipeDataByName2 = getDataYML2.GetRecipeDataByName(text11, ObjectDB.instance); if (recipeDataByName2 == null) { return; } recipeDataByName2.name = text12; recipeDataByName2.clonePrefabName = text11; File.WriteAllText(Path.Combine(WMRecipeCust.assetPathRecipes, "Recipe_" + recipeDataByName2.name + ".yml"), serializer2.Serialize(recipeDataByName2)); text13 = "Recipe" + recipeDataByName2.name; } else { string text14 = args[4]; RecipeData recipeDataByName3 = getDataYML2.GetRecipeDataByName(text14, ObjectDB.instance); if (recipeDataByName3 == null) { return; } recipeDataByName3.name = text12; recipeDataByName3.clonePrefabName = text11; File.WriteAllText(Path.Combine(WMRecipeCust.assetPathRecipes, "Recipe_" + recipeDataByName3.name + ".yml"), serializer2.Serialize(recipeDataByName3)); text13 = "Cloned Item " + recipeDataByName3.name + " Clone Recipe from " + text14; } } if (text10 == "item" || text10 == "Item") { WItemData itemDataByName2 = getDataYML2.GetItemDataByName(text11, ObjectDB.instance); if (itemDataByName2 == null) { return; } itemDataByName2.name = text12; itemDataByName2.clonePrefabName = text11; itemDataByName2.m_name = text12; WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathItems, "Item_" + itemDataByName2.name + ".yml"), serializer2.Serialize(itemDataByName2)); text13 = "Item_" + itemDataByName2.name; } if (text10 == "piece" || text10 == "Piece") { PieceData pieceRecipeByName = getDataYML2.GetPieceRecipeByName(text11, ObjectDB.instance); if (pieceRecipeByName == null) { return; } pieceRecipeByName.name = text12; pieceRecipeByName.clonePrefabName = text11; WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathPieces, "Piece_" + pieceRecipeByName.name + ".yml"), serializer2.Serialize(pieceRecipeByName)); text13 = "Piece_" + pieceRecipeByName.name; } switch (text10) { case "pickable": case "Pickable": case "Pickables": case "pickables": { Pickable[] array = Resources.FindObjectsOfTypeAll(); PickableData pickable = getDataYML2.GetPickable(text11, array); if (pickable == null) { return; } pickable.name = text12; pickable.cloneOfWhatPickable = text11; WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathPickables, "Pickable_" + pickable.name + ".yml"), serializer2.Serialize(pickable)); text13 = "Pickable_" + pickable.name; break; } } if (text10 == "treebase" || text10 == "Treebase") { TreeBase[] array2 = Resources.FindObjectsOfTypeAll(); TreeBaseData treeBase = getDataYML2.GetTreeBase(text11, array2); if (treeBase == null) { return; } treeBase.name = text12; treeBase.cloneOfWhatTree = text11; WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathPieces, "Treebase_" + treeBase.name + ".yml"), serializer2.Serialize(treeBase)); text13 = "Treebase_" + treeBase.name; } switch (text10) { case "creature": case "Creature": case "mob": { CreatureData creature = getDataYML2.GetCreature(text11); if (creature == null) { return; } creature.name = text12; creature.clone_creature = text11; WMRecipeCust.CheckModFolder(); File.WriteAllText(Path.Combine(WMRecipeCust.assetPathCreatures, "Creature_" + creature.name + ".yml"), serializer2.Serialize(creature)); text13 = "Creature_" + creature.name; break; } } switch (text10) { case "se": case "SE": case "Se": try { ObjectDB instance = ObjectDB.instance; StatusData statusEByName = new GetDataYML().GetStatusEByName(text11, instance); if (statusEByName == null) { WMRecipeCust.WLog.LogInfo((object)(statusEByName.Name + " Was not found")); } statusEByName.Name = text12; statusEByName.ClonedSE = text11; File.WriteAllText(Path.Combine(WMRecipeCust.assetPathEffects, "SE_" + statusEByName.Name + ".yml"), serializer2.Serialize(statusEByName)); Terminal context11 = args.Context; if (context11 != null) { context11.AddString("Created a clone from " + text11 + " , saved as a file SE_" + statusEByName.Name + ".yml in Effects folder"); } WMRecipeCust.WLog.LogInfo((object)("Created a clone from " + text11 + " , saved as a file SE_" + statusEByName.Name + ".yml in Effects folder")); } catch { WMRecipeCust.WLog.LogWarning((object)"wackydb_clone SE is unhappy, feed it better cookies"); text13 = "not saved"; } break; } switch (text10) { case "material": case "Material": case "mat": { string text15 = text11; if (WMRecipeCust.originalMaterials.ContainsKey(text15)) { Material val41 = WMRecipeCust.originalMaterials[text15]; YamlLoader yamlLoader = new YamlLoader(); MaterialInstance materialInstance = new MaterialInstance { original = text15, name = text12, overwrite = false }; int propertyCount = val41.shader.GetPropertyCount(); for (int i = 0; i < propertyCount; i++) { ShaderPropertyType propertyType = val41.shader.GetPropertyType(i); string propertyName = val41.shader.GetPropertyName(i); switch ((int)propertyType) { case 0: materialInstance.changes.colors.Add(propertyName, val41.GetColor(propertyName)); break; case 1: case 2: case 3: materialInstance.changes.floats.Add(propertyName, val41.GetFloat(propertyName)); break; case 4: { Texture texture = val41.GetTexture(propertyName); try { if ((Object)(object)texture != (Object)null) { materialInstance.changes.textures.Add(propertyName, (Texture2D)texture); TextureDataManager.SaveTexture(((Object)texture).name, texture); } } catch (Exception ex) { Debug.LogError((object)("[WackysDatabase]: Unable to write texture for property: " + propertyName + " - " + ex.Message)); } break; } } } yamlLoader.Write(Path.Combine(WMRecipeCust.assetPathMaterials, text12 + ".yml"), materialInstance); Terminal context12 = args.Context; if (context12 != null) { context12.AddString("Saved in the Material folder, as " + text12 + ".yml"); } } break; } } Terminal context13 = args.Context; if (context13 != null) { context13.AddString("saved cloned data to " + text13 + ".yml"); } } } }; <>c.<>9__0_32 = val33; obj33 = (object)val33; } object obj34 = <>c.<>9__0_33; if (obj34 == null) { ConsoleOptionsFetcher val34 = () => Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefabNames() : new List(); <>c.<>9__0_33 = val34; obj34 = (object)val34; } new ConsoleCommand("wackydb_clone", "Clone an Item/Piece/Recipe/Material/creature/SE with different stats, names, effects ect... ", (ConsoleEvent)obj33, false, false, false, false, false, (ConsoleOptionsFetcher)obj34, false, false, false); object obj35 = <>c.<>9__0_34; if (obj35 == null) { ConsoleEvent val35 = delegate(ConsoleEventArgs args) { WMRecipeCust.CheckModFolder(); if (args.Length - 1 < 2) { Terminal context7 = args.Context; if (context7 != null) { context7.AddString("Not enough arguments"); } } else { ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); GetDataYML getDataYML = new GetDataYML(); string text7 = args[1]; string text8 = args[2]; string text9 = args[2]; WItemData itemDataByName = getDataYML.GetItemDataByName(text7, ObjectDB.instance); if (itemDataByName != null) { itemDataByName.name = text8; itemDataByName.clonePrefabName = text7; itemDataByName.m_name = text8; File.WriteAllText(Path.Combine(WMRecipeCust.assetPathItems, "Item_" + itemDataByName.name + ".yml"), serializer.Serialize(itemDataByName)); RecipeData recipeDataByName = getDataYML.GetRecipeDataByName(text7, ObjectDB.instance); if (recipeDataByName != null) { recipeDataByName.name = "R" + text8; recipeDataByName.clonePrefabName = itemDataByName.name; File.WriteAllText(Path.Combine(WMRecipeCust.assetPathRecipes, "Recipe_" + recipeDataByName.name + ".yml"), serializer.Serialize(recipeDataByName)); text9 = "Cloned Item saved as Item_" + itemDataByName.name + ".yml, cloned Recipe saved as Recipe_" + recipeDataByName.name + ".yml which is from the Orginal Recipe " + text7; Terminal context8 = args.Context; if (context8 != null) { context8.AddString(text9 ?? ""); } } } } }; <>c.<>9__0_34 = val35; obj35 = (object)val35; } object obj36 = <>c.<>9__0_35; if (obj36 == null) { ConsoleOptionsFetcher val36 = () => Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefabNames() : new List(); <>c.<>9__0_35 = val36; obj36 = (object)val36; } new ConsoleCommand("wackydb_clone_recipeitem", "Clone recipe and item with the orginal prefab ", (ConsoleEvent)obj35, false, false, false, false, false, (ConsoleOptionsFetcher)obj36, false, false, false); object obj37 = <>c.<>9__0_36; if (obj37 == null) { ConsoleEvent val37 = delegate(ConsoleEventArgs args) { if (!WMRecipeCust.issettoSinglePlayer && WMRecipeCust.kickcount < 3) { string text4 = ""; try { text4 = args[1]; } catch { WMRecipeCust.WLog.LogWarning((object)"Congrats on finding the backdoor... You have 3 chances to guess the password or you will be called out that your a dirty cheater in chat and probably being kicked by Azu or an admin"); return; } WMRecipeCust.WLog.LogWarning((object)$"guess {WMRecipeCust.kickcount + 1}"); string text5 = Functions.ComputeSha256Hash(text4); string text6 = "f289b4717485d90d9dee6ce2a9992e4fcfa4317a9439c148053d52c637b0691b"; if (text5 == text6) { WMRecipeCust.WLog.LogWarning((object)"Congrats you cheater, Enjoy nothin"); } else { WMRecipeCust.kickcount++; if (WMRecipeCust.kickcount >= 3) { string name = ((Object)Player.m_localPlayer).name; ((Terminal)Chat.m_instance).AddString("[WackysDatabase]", "Cheater Cheater, pants on fire. " + name + " tried to get admin access and failed. Laugh at this person or kick them.", (Type)1, false); WMRecipeCust.WLog.LogWarning((object)"Cheater Cheater, pants on fire"); } } } }; <>c.<>9__0_36 = val37; obj37 = (object)val37; } new ConsoleCommand("wackydb_backdoor", "Gives you reload powers if you can guess the password", (ConsoleEvent)obj37, false, false, false, true, false, (ConsoleOptionsFetcher)null, false, false, false); object obj38 = <>c.<>9__0_37; if (obj38 == null) { ConsoleEvent val38 = delegate(ConsoleEventArgs args) { if (args.Length - 1 < 1) { Terminal context4 = args.Context; if (context4 != null) { context4.AddString("Not enough arguments "); } } else { string text3 = args[1]; WMRecipeCust.WLog.LogInfo((object)text3); try { VisualController.Export(PrefabAssistant.Describe(text3)); } catch { WMRecipeCust.WLog.LogWarning((object)"Error, Didnt save"); Terminal context5 = args.Context; if (context5 != null) { context5.AddString("Error, Didnt save"); } } Terminal context6 = args.Context; if (context6 != null) { context6.AddString("Saved in config folder Describe_" + text3 + ".yml"); } } }; <>c.<>9__0_37 = val38; obj38 = (object)val38; } object obj39 = <>c.<>9__0_38; if (obj39 == null) { ConsoleOptionsFetcher val39 = () => Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefabNames() : new List(); <>c.<>9__0_38 = val39; obj39 = (object)val39; } new ConsoleCommand("wackydb_describe", "Export visual description information for an item", (ConsoleEvent)obj38, false, false, false, false, false, (ConsoleOptionsFetcher)obj39, false, false, false); object obj40 = <>c.<>9__0_39; if (obj40 == null) { ConsoleEvent val40 = delegate(ConsoleEventArgs args) { if (args.Length - 1 < 1) { Terminal context = args.Context; if (context != null) { context.AddString("Not enough arguments"); } } else { string text = args[1]; string text2 = PrefabAssistant.SaveMaterial(text); if (text2 != null) { Terminal context2 = args.Context; if (context2 != null) { context2.AddString("Saved in the Material folder, as " + text2 + ".yml"); } } else { Terminal context3 = args.Context; if (context3 != null) { context3.AddString("Material '" + text + "' not found."); } } } }; <>c.<>9__0_39 = val40; obj40 = (object)val40; } new ConsoleCommand("wackydb_save_material", "Export default material settings for a material", (ConsoleEvent)obj40, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); } } [HarmonyPatch(typeof(Player), "UpdateEnvStatusEffects")] [Nullable(0)] [NullableContext(1)] internal static class UpdateEnvStatusEffects_Patch { internal static bool loadTranspiler = true; public static IEnumerable Transpiler(IEnumerable instructions) { //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Expected O, but got Unknown //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Expected O, but got Unknown //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Expected O, but got Unknown //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Expected O, but got Unknown //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Expected O, but got Unknown //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Expected O, but got Unknown if (loadTranspiler) { loadTranspiler = false; WMRecipeCust.Dbgl("Transpiling UpdateEnvStatusEffects"); List list = new List(instructions); List list2 = new List(); bool flag = true; for (int i = 0; i < list.Count; i++) { if (flag && list[i].opcode == OpCodes.Ldloc_S && list[i + 1].opcode == OpCodes.Ldc_I4_1 && list[i + 2].opcode == OpCodes.Beq && list[i + 3].opcode == OpCodes.Ldloc_S && list[i + 3].operand == list[i].operand && list[i + 4].opcode == OpCodes.Ldc_I4_5) { WMRecipeCust.Dbgl("Adding frost immune and ignore"); list2.Add(new CodeInstruction(list[i])); list2.Add(new CodeInstruction(OpCodes.Ldc_I4_3, (object)null)); list2.Add(new CodeInstruction(list[i + 2])); list2.Add(new CodeInstruction(list[i])); list2.Add(new CodeInstruction(OpCodes.Ldc_I4_4, (object)null)); list2.Add(new CodeInstruction(list[i + 2])); flag = false; } list2.Add(list[i]); } return list2.AsEnumerable(); } return instructions; } private static void Postfix(float dt, Player __instance, ItemData ___m_chestItem, ItemData ___m_legItem, ItemData ___m_helmetItem, ItemData ___m_shoulderItem, SEMan ___m_seman) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Invalid comparison between Unknown and I4 //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Invalid comparison between Unknown and I4 //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Invalid comparison between Unknown and I4 //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Invalid comparison between Unknown and I4 //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Invalid comparison between Unknown and I4 //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Invalid comparison between Unknown and I4 //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Invalid comparison between Unknown and I4 if (WMRecipeCust.modEnabled.Value && ___m_seman.HaveStatusEffect(StringExtensionMethods.GetStableHashCode("Wet"))) { DamageModifier newDamageTypeMod = ArmorHelpers.GetNewDamageTypeMod(ArmorHelpers.NewDamageTypes.Water, ___m_chestItem, ___m_legItem, ___m_helmetItem, ___m_shoulderItem); StatusEffect statusEffect = ___m_seman.GetStatusEffect(StringExtensionMethods.GetStableHashCode("Wet")); Traverse val = Traverse.Create((object)statusEffect); if ((int)newDamageTypeMod == 4 || (int)newDamageTypeMod == 3) { ___m_seman.RemoveStatusEffect(statusEffect, true); } else if ((int)newDamageTypeMod == 5 && !((Character)__instance).InLiquidSwimDepth()) { ___m_seman.RemoveStatusEffect(statusEffect, true); } else if ((int)newDamageTypeMod == 1) { val.Field("m_time").SetValue((object)(val.Field("m_time").GetValue() + dt)); ___m_seman.RemoveStatusEffect(statusEffect, true); ___m_seman.AddStatusEffect(statusEffect, false, 0, 0f); } else if ((int)newDamageTypeMod == 7) { val.Field("m_time").SetValue((object)(val.Field("m_time").GetValue() + dt)); ___m_seman.RemoveStatusEffect(statusEffect, true); ___m_seman.AddStatusEffect(statusEffect, false, 0, 0f); } else if ((int)newDamageTypeMod == 2) { val.Field("m_time").SetValue((object)(val.Field("m_time").GetValue() - dt / 3f)); ___m_seman.RemoveStatusEffect(statusEffect, true); ___m_seman.AddStatusEffect(statusEffect, false, 0, 0f); } else if ((int)newDamageTypeMod == 6) { val.Field("m_time").SetValue((object)(val.Field("m_time").GetValue() - dt * 2f / 3f)); ___m_seman.RemoveStatusEffect(statusEffect, true); ___m_seman.AddStatusEffect(statusEffect, false, 0, 0f); } } } } [HarmonyPatch(typeof(SEMan), "AddStatusEffect", new Type[] { typeof(StatusEffect), typeof(bool), typeof(int), typeof(float) })] internal static class SEMan_AddStatusEffect_Patch { [NullableContext(1)] private static bool Prefix(SEMan __instance, StatusEffect statusEffect, Character ___m_character, ref StatusEffect __result) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Invalid comparison between Unknown and I4 //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Invalid comparison between Unknown and I4 if (!WMRecipeCust.modEnabled.Value || !___m_character.IsPlayer()) { return true; } if (statusEffect.m_name == "$se_wet_name") { DamageModifier newDamageTypeMod = ArmorHelpers.GetNewDamageTypeMod(ArmorHelpers.NewDamageTypes.Water, ___m_character); if ((int)newDamageTypeMod == 4 || (int)newDamageTypeMod == 3) { __result = null; return false; } } return true; } } [HarmonyPatch(typeof(SE_Stats), "GetDamageModifiersTooltipString")] internal static class GetDamageModifiersTooltipString_Patch { [NullableContext(1)] private static void Postfix(ref string __result, List mods) { //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_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_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_0096: 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_00b8: 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_00bf: Invalid comparison between Unknown and I4 //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_00b3: Invalid comparison between Unknown and I4 //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_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_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Expected I4, but got Unknown //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Invalid comparison between Unknown and I4 if (!WMRecipeCust.modEnabled.Value || mods.Count == 0) { return; } bool flag = false; foreach (DamageModPair mod in mods) { if (!Enum.IsDefined(typeof(DamageType), mod.m_type)) { flag = true; break; } } if (!flag) { return; } __result = Regex.Replace(__result, "\\n.*", ""); foreach (DamageModPair mod2 in mods) { if ((!Enum.IsDefined(typeof(DamageType), mod2.m_type) || (int)mod2.m_type == 1024) && (int)mod2.m_modifier != 4 && (int)mod2.m_modifier != 0) { DamageModifier modifier = mod2.m_modifier; switch (modifier - 1) { case 6: __result += "\n$inventory_dmgmod: $inventory_resistant VS "; break; case 0: __result += "\n$inventory_dmgmod: $inventory_resistant VS "; break; case 1: __result += "\n$inventory_dmgmod: $inventory_weak VS "; break; case 2: __result += "\n$inventory_dmgmod: $inventory_immune VS "; break; case 4: __result += "\n$inventory_dmgmod: $inventory_veryresistant VS "; break; case 5: __result += "\n$inventory_dmgmod: $inventory_veryweak VS "; break; } if ((int)mod2.m_type == 1024) { __result = __result + "" + WMRecipeCust.WaterName.Value + ""; } } } } } [HarmonyPatch(typeof(Player), "GetTotalFoodValue")] [Nullable(0)] [NullableContext(1)] public static class Add_goodies_Wackydb { public static void Postfix(Player __instance, ref float hp, ref float stamina, ref float eitr) { if (!Object.op_Implicit((Object)(object)__instance) || WMRecipeCust.SEaddBonus.Count == 0 || (Object)(object)__instance != (Object)(object)Player.m_localPlayer) { return; } SEMan sEMan = ((Character)__instance).GetSEMan(); if (sEMan == null) { return; } List statusEffects = sEMan.GetStatusEffects(); if (statusEffects == null || statusEffects.Count == 0) { return; } float num = 0f; float num2 = 0f; float num3 = 0f; for (int i = 0; i < statusEffects.Count; i++) { StatusEffect val = statusEffects[i]; if (!((Object)(object)val == (Object)null) && TryGetBonus(val, out var bonus)) { if (bonus.AddHP.HasValue) { num += bonus.AddHP.Value; } if (bonus.AddStamina.HasValue) { num2 += bonus.AddStamina.Value; } if (bonus.AddEitr.HasValue) { num3 += bonus.AddEitr.Value; } } } hp += num; if (hp < 1f) { hp = 1f; } stamina += num2; eitr += num3; } private static bool TryGetBonus(StatusEffect se, out WackyStatusEffectBonus bonus) { bonus = null; if (!string.IsNullOrEmpty(((Object)se).name) && WMRecipeCust.SEaddBonus.TryGetValue(((Object)se).name, out bonus)) { return true; } return false; } } } namespace wackydatabase.OtherApi { [Nullable(0)] [NullableContext(1)] public static class Marketplace_API { [Flags] [NullableContext(0)] public enum TerritoryFlags { None = 0, PushAway = 1, NoBuild = 2, NoPickaxe = 4, NoInteract = 8, NoAttack = 0x10, PvpOnly = 0x20, PveOnly = 0x40, PeriodicHeal = 0x80, PeriodicDamage = 0x100, IncreasedPlayerDamage = 0x200, IncreasedMonsterDamage = 0x400, NoMonsters = 0x800, CustomEnvironment = 0x1000, MoveSpeedMultiplier = 0x2000, NoDeathPenalty = 0x4000, NoPortals = 0x8000, PeriodicHealALL = 0x10000, ForceGroundHeight = 0x20000, ForceBiome = 0x40000, AddGroundHeight = 0x80000, NoBuildDamage = 0x100000, MonstersAddStars = 0x200000, InfiniteFuel = 0x400000, NoInteractItems = 0x800000, NoInteractCraftingStation = 0x1000000, NoInteractItemStands = 0x2000000, NoInteractChests = 0x4000000, NoInteractDoors = 0x8000000, NoStructureSupport = 0x10000000, NoInteractPortals = 0x20000000, CustomPaint = 0x40000000, LimitZoneHeight = int.MinValue } [Flags] [NullableContext(0)] public enum AdditionalTerritoryFlags { None = 0, NoItemLoss = 1, SnowMask = 2, NoMist = 4, InfiniteEitr = 8, InfiniteStamina = 0x10, NoCreatureDrops = 0x20 } private static readonly bool _IsInstalled; private static readonly MethodInfo MI_IsPlayerInsideTerritory; private static readonly MethodInfo MI_IsObjectInsideTerritoryWithFlag; private static readonly MethodInfo MI_IsObjectInsideTerritoryWithFlag_Additional; private static readonly MethodInfo MI_ResetTraderItems; public static bool IsInstalled() { return _IsInstalled; } public static bool IsPlayerInsideTerritory(out string name, out TerritoryFlags flags, out AdditionalTerritoryFlags additionalFlags) { flags = TerritoryFlags.None; additionalFlags = AdditionalTerritoryFlags.None; name = ""; if (!_IsInstalled || MI_IsPlayerInsideTerritory == null) { return false; } object[] array = new object[3] { "", 0, 0 }; bool result = (bool)MI_IsPlayerInsideTerritory.Invoke(null, array); name = (string)array[0]; flags = (TerritoryFlags)array[1]; additionalFlags = (AdditionalTerritoryFlags)array[2]; return result; } public static bool IsObjectInsideTerritoryWithFlag(GameObject go, TerritoryFlags flag, out string name, out TerritoryFlags flags, out AdditionalTerritoryFlags additionalFlags) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return IsPointInsideTerritoryWithFlag(go.transform.position, flag, out name, out flags, out additionalFlags); } public static bool IsObjectInsideTerritoryWithFlag(GameObject go, AdditionalTerritoryFlags flag, out string name, out TerritoryFlags flags, out AdditionalTerritoryFlags additionalFlags) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return IsPointInsideTerritoryWithFlag(go.transform.position, flag, out name, out flags, out additionalFlags); } public static bool IsPointInsideTerritoryWithFlag(Vector3 pos, TerritoryFlags flag, out string name, out TerritoryFlags flags, out AdditionalTerritoryFlags additionalFlags) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) name = ""; flags = TerritoryFlags.None; additionalFlags = AdditionalTerritoryFlags.None; if (!_IsInstalled || MI_IsObjectInsideTerritoryWithFlag == null) { return false; } object[] array = new object[5] { pos, (int)flag, "", 0, 0 }; bool result = (bool)MI_IsObjectInsideTerritoryWithFlag.Invoke(null, array); name = (string)array[2]; flags = (TerritoryFlags)array[3]; additionalFlags = (AdditionalTerritoryFlags)array[4]; return result; } public static bool IsPointInsideTerritoryWithFlag(Vector3 pos, AdditionalTerritoryFlags flag, out string name, out TerritoryFlags flags, out AdditionalTerritoryFlags additionalFlags) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) name = ""; flags = TerritoryFlags.None; additionalFlags = AdditionalTerritoryFlags.None; if (!_IsInstalled || MI_IsObjectInsideTerritoryWithFlag_Additional == null) { return false; } object[] array = new object[5] { pos, (int)flag, "", 0, 0 }; bool result = (bool)MI_IsObjectInsideTerritoryWithFlag_Additional.Invoke(null, array); name = (string)array[2]; flags = (TerritoryFlags)array[3]; additionalFlags = (AdditionalTerritoryFlags)array[4]; return result; } public static void ResetTraderItems() { if (_IsInstalled && !(MI_ResetTraderItems == null)) { MI_ResetTraderItems.Invoke(null, null); } } static Marketplace_API() { Type type = Type.GetType("API.ClientSide, kg.Marketplace"); if ((object)type == null) { _IsInstalled = false; return; } _IsInstalled = true; MI_IsPlayerInsideTerritory = type.GetMethod("IsPlayerInsideTerritory", BindingFlags.Static | BindingFlags.Public); MI_IsObjectInsideTerritoryWithFlag = type.GetMethod("IsObjectInsideTerritoryWithFlag", BindingFlags.Static | BindingFlags.Public); MI_IsObjectInsideTerritoryWithFlag_Additional = type.GetMethod("IsObjectInsideTerritoryWithFlag_Additional", BindingFlags.Static | BindingFlags.Public); MI_ResetTraderItems = type.GetMethod("ResetTraderItems", BindingFlags.Static | BindingFlags.Public); } } } namespace wackydatabase.OBJimporter { [NullableContext(1)] [Nullable(0)] internal class HandleData { [CompilerGenerated] private sealed class d__11 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; [Nullable(new byte[] { 0, 1 })] public string[] requestedFiles; public long targetPeer; [Nullable(new byte[] { 0, 1 })] private string[] <>7__wrap1; private int <>7__wrap2; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__11(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>7__wrap1 = null; <>1__state = -2; } private bool MoveNext() { //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Expected O, but got Unknown int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -1; goto IL_0154; } <>1__state = -1; <>7__wrap1 = requestedFiles; <>7__wrap2 = 0; goto IL_0162; IL_0154: <>7__wrap2++; goto IL_0162; IL_0162: if (<>7__wrap2 < <>7__wrap1.Length) { string[] array = <>7__wrap1[<>7__wrap2].Split(new char[1] { ':' }); if (array.Length == 2) { string text = array[0]; string text2 = array[1]; string text3 = ""; string text4 = ""; switch (text2) { case "icon": text3 = WMRecipeCust.assetPathIcons; text4 = "*.png"; break; case "png": text3 = WMRecipeCust.assetPathObjects; text4 = "*.png"; break; case "obj": text3 = WMRecipeCust.assetPathObjects; text4 = "*.obj"; break; case "tex": text3 = WMRecipeCust.assetPathTextures; text4 = "*.png"; break; } if (!string.IsNullOrEmpty(text3)) { string[] files = Directory.GetFiles(text3, text + text4, SearchOption.AllDirectories); if (files.Length != 0) { string text5 = Convert.ToBase64String(File.ReadAllBytes(files[0])); ZRoutedRpc.instance.InvokeRoutedRPC(targetPeer, "WackyDB_AssetPayload", new object[3] { text2, text, text5 }); } <>2__current = (object)new WaitForEndOfFrame(); <>1__state = 1; return true; } } goto IL_0154; } <>7__wrap1 = null; WMRecipeCust.WLog.LogInfo((object)$"Finished streaming {requestedFiles.Length} files to Peer {targetPeer}."); ZRoutedRpc.instance.InvokeRoutedRPC(targetPeer, "WackyDB_ClientMSG", new object[1] { "WackyDB: Finished downloading missing assets. Restart game to apply!" }); PendingSyncClients.Remove(targetPeer); CheckPendingSyncClients(); 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(); } } internal static string bigDataR; internal static List bigDataRChucks = new List(); internal static string bigDataS; internal static List bigDataSChucks = new List(); internal static HashSet PendingSyncClients = new HashSet(); internal static long AdminPeerForSync = 0L; public static void RecievedData() { } public static void SendData(long peer, ZPackage go) { if (!ZNet.instance.IsServer()) { return; } if (WMRecipeCust.issettoSinglePlayer) { WMRecipeCust.WLog.LogInfo((object)"Singleplayer mode detected. Skipping SendData because there are no clients."); return; } PendingSyncClients.Clear(); AdminPeerForSync = peer; List peers = ZNet.instance.GetPeers(); if (peers != null) { foreach (ZNetPeer item in peers) { if (item.IsReady()) { PendingSyncClients.Add(item.m_uid); } } } WMRecipeCust.WLog.LogInfo((object)"Starting Object, Icon, and Texture folder Manifest generation"); StringBuilder sb = new StringBuilder(); MD5 md5 = MD5.Create(); try { AddFiles(WMRecipeCust.assetPathIcons, "icon", "*.png"); AddFiles(WMRecipeCust.assetPathObjects, "obj", "*.obj"); AddFiles(WMRecipeCust.assetPathObjects, "png", "*.png"); AddFiles(WMRecipeCust.assetPathTextures, "tex", "*.png"); } finally { if (md5 != null) { ((IDisposable)md5).Dispose(); } } string text = sb.ToString(); WMRecipeCust.WLog.LogInfo((object)$"Sending Asset Manifest ({text.Length} chars) to all clients."); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "WackyDB_AssetManifest", new object[1] { text }); if (peer != 0L) { ZRoutedRpc.instance.InvokeRoutedRPC(peer, "WackyDB_AdminLogMsg", new object[1] { "WackyDB: Server is calculating hashes and sending Manifests to clients..." }); } if (PendingSyncClients.Count == 0) { CheckPendingSyncClients(); } void AddFiles(string folder, string type, string search) { if (Directory.Exists(folder)) { string[] files = Directory.GetFiles(folder, search, SearchOption.AllDirectories); foreach (string path in files) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path); byte[] buffer = File.ReadAllBytes(path); string text2 = Convert.ToBase64String(md5.ComputeHash(buffer)); sb.Append(fileNameWithoutExtension + ":" + type + ":" + text2 + "?"); } } } } private static void CheckPendingSyncClients() { if (ZNet.instance.IsServer() && PendingSyncClients.Count == 0) { WMRecipeCust.WLog.LogInfo((object)"WackyDB: All clients have successfully synced server assets."); if (AdminPeerForSync != 0L) { ZRoutedRpc.instance.InvokeRoutedRPC(AdminPeerForSync, "WackyDB_AdminLogMsg", new object[1] { "WackyDB: All clients have successfully synced server assets." }); AdminPeerForSync = 0L; } } } public static void ReceiveManifest(long sender, string manifest) { if (ZNet.instance.IsServer()) { return; } WMRecipeCust.WLog.LogInfo((object)"Received Asset Manifest from server, checking local files..."); string[] separator = new string[1] { "?" }; string[] array = manifest.Split(separator, StringSplitOptions.RemoveEmptyEntries); List list = new List(); using (MD5 mD = MD5.Create()) { string[] array2 = array; for (int i = 0; i < array2.Length; i++) { string[] array3 = array2[i].Split(new char[1] { ':' }); if (array3.Length != 3) { continue; } string text = array3[0]; string text2 = array3[1]; string text3 = array3[2]; string text4 = ""; switch (text2) { case "icon": text4 = Path.Combine(WMRecipeCust.assetPathIcons, text + ".png"); break; case "png": text4 = Path.Combine(WMRecipeCust.assetPathObjects, text + ".png"); break; case "obj": text4 = Path.Combine(WMRecipeCust.assetPathObjects, text + ".obj"); break; case "tex": text4 = Path.Combine(WMRecipeCust.assetPathTextures, text + ".png"); break; } bool flag = true; if (!string.IsNullOrEmpty(text4) && File.Exists(text4)) { byte[] buffer = File.ReadAllBytes(text4); if (Convert.ToBase64String(mD.ComputeHash(buffer)) == text3) { flag = false; } } if (flag) { list.Add(text + ":" + text2); } } } if (list.Count > 0) { WMRecipeCust.WLog.LogInfo((object)$"Client missing {list.Count} files. Requesting specifically from server..."); string text5 = string.Join("?", list); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "WackyDB_AssetRequest", new object[1] { text5 }); return; } WMRecipeCust.WLog.LogInfo((object)"Client already has all WackyDB server assets up to date. Nothing to download!"); if ((Object)(object)Player.m_localPlayer != (Object)null) { MessageHud.instance.ShowMessage((MessageType)2, "WackyDB: All Assets already up to date!", 0, (Sprite)null, false); } ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "WackyDB_AssetRequest", new object[1] { "none" }); } public static void ReceiveRequest(long sender, string request) { if (ZNet.instance.IsServer()) { if (request == "none") { PendingSyncClients.Remove(sender); CheckPendingSyncClients(); return; } string[] separator = new string[1] { "?" }; string[] array = request.Split(separator, StringSplitOptions.RemoveEmptyEntries); WMRecipeCust.WLog.LogInfo((object)$"Peer {sender} requested {array.Length} missing asset files. Streaming to them..."); HandleData handleData = new HandleData(); ((MonoBehaviour)WMRecipeCust.context).StartCoroutine(handleData.SendRequestedFiles(sender, array)); } } [IteratorStateMachine(typeof(d__11))] private IEnumerator SendRequestedFiles(long targetPeer, string[] requestedFiles) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__11(0) { targetPeer = targetPeer, requestedFiles = requestedFiles }; } public static void ReceivePayload(long sender, string type, string filename, string base64) { if (ZNet.instance.IsServer()) { return; } try { byte[] bytes = Convert.FromBase64String(base64); string text = ""; switch (type) { case "icon": text = Path.Combine(WMRecipeCust.assetPathIcons, filename + ".png"); break; case "png": text = Path.Combine(WMRecipeCust.assetPathObjects, filename + ".png"); break; case "obj": text = Path.Combine(WMRecipeCust.assetPathObjects, filename + ".obj"); break; case "tex": text = Path.Combine(WMRecipeCust.assetPathTextures, filename + ".png"); break; } if (!string.IsNullOrEmpty(text)) { File.WriteAllBytes(text, bytes); WMRecipeCust.WLog.LogInfo((object)("Downloaded and saved " + filename + " of type " + type)); } } catch (Exception ex) { WMRecipeCust.WLog.LogError((object)("Error decoding/saving " + filename + ": " + ex.Message)); } } public static void ClientMSG(long sender, string msg) { if ((Object)(object)Player.m_localPlayer != (Object)null) { MessageHud.instance.ShowMessage((MessageType)2, msg, 0, (Sprite)null, false); } WMRecipeCust.WLog.LogInfo((object)("Server MSG: " + msg)); } public static void AdminLogMsg(long sender, string msg) { WMRecipeCust.WLog.LogInfo((object)msg); if ((Object)(object)Console.instance != (Object)null) { Console.instance.Print(msg); } } } [NullableContext(1)] [Nullable(0)] public static class ObjModelLoader { public static readonly Dictionary _loadedModels = new Dictionary(); public static readonly Dictionary _loadedIcons = new Dictionary(); private static readonly Dictionary pngFiles = new Dictionary(); private static readonly int MainTex = Shader.PropertyToID("_MainTex"); private static readonly int MetallicGlossMap = Shader.PropertyToID("_MetallicGlossMap"); private static readonly int BumpMap = Shader.PropertyToID("_BumpMap"); public static GameObject MockItemBase; public static AssetBundle asset; internal static void ClearObjs() { _loadedModels.Clear(); _loadedIcons.Clear(); pngFiles.Clear(); } private static AssetBundle GetAssetBundle(string filename) { Assembly executingAssembly = Assembly.GetExecutingAssembly(); string name = executingAssembly.GetManifestResourceNames().Single([NullableContext(0)] (string str) => str.EndsWith(filename)); using Stream stream = executingAssembly.GetManifestResourceStream(name); return AssetBundle.LoadFromStream(stream); } internal static void OnInit() { asset = GetAssetBundle("rootcube"); MockItemBase = asset.LoadAsset("RootCube"); } internal static void LoadObjs() { OnInit(); string[] files = Directory.GetFiles(WMRecipeCust.assetPathObjects, "*.png", SearchOption.AllDirectories); foreach (string text in files) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text); pngFiles.Add(fileNameWithoutExtension, text); } files = Directory.GetFiles(WMRecipeCust.assetPathObjects, "*.obj", SearchOption.AllDirectories); foreach (string text2 in files) { try { GameObject val = new OBJLoader().Load(text2); Object.DontDestroyOnLoad((Object)(object)val); string fileNameWithoutExtension2 = Path.GetFileNameWithoutExtension(text2); _loadedModels.Add(fileNameWithoutExtension2, val); ParsePNGs(val, fileNameWithoutExtension2); AddColliders(val); } catch (Exception arg) { WMRecipeCust.WLog.LogInfo((object)$"Failed to load model {text2}\n: {arg}"); } } files = Directory.GetFiles(WMRecipeCust.assetPathObjects, "*.fbx", SearchOption.AllDirectories); foreach (string text3 in files) { try { GameObject val2 = Resources.Load(text3); Object.DontDestroyOnLoad((Object)(object)val2); string fileNameWithoutExtension3 = Path.GetFileNameWithoutExtension(text3); _loadedModels.Add(fileNameWithoutExtension3, val2); AddColliders(val2); } catch (Exception arg2) { WMRecipeCust.WLog.LogInfo((object)$"Failed to load model fbx {text3}\n: {arg2}"); } } } private static void ParsePNGs(GameObject go, string name) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown //IL_0073: 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_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Expected O, but got Unknown //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Expected O, but got Unknown //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Expected O, but got Unknown string key = name + "_albedo"; string key2 = name + "_metallic"; string key3 = name + "_normal"; string key4 = name + "_icon"; if (pngFiles.TryGetValue(key4, out var value)) { Texture2D val = new Texture2D(2, 2); ImageConversion.LoadImage(val, File.ReadAllBytes(value)); Sprite value2 = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0f, 0f)); _loadedIcons.Add(name, value2); } MeshRenderer[] componentsInChildren = go.GetComponentsInChildren(); if (pngFiles.TryGetValue(key, out var value3)) { Texture2D val2 = new Texture2D(2, 2); ImageConversion.LoadImage(val2, File.ReadAllBytes(value3)); MeshRenderer[] array = componentsInChildren; for (int i = 0; i < array.Length; i++) { ((Renderer)array[i]).material.SetTexture(MainTex, (Texture)(object)val2); } } if (pngFiles.TryGetValue(key2, out value3)) { Texture2D val3 = new Texture2D(2, 2); ImageConversion.LoadImage(val3, File.ReadAllBytes(value3)); MeshRenderer[] array = componentsInChildren; for (int i = 0; i < array.Length; i++) { ((Renderer)array[i]).material.SetTexture(MetallicGlossMap, (Texture)(object)val3); } } if (pngFiles.TryGetValue(key3, out value3)) { Texture2D val4 = new Texture2D(2, 2); ImageConversion.LoadImage(val4, File.ReadAllBytes(value3)); MeshRenderer[] array = componentsInChildren; for (int i = 0; i < array.Length; i++) { ((Renderer)array[i]).material.SetTexture(BumpMap, (Texture)(object)val4); } } } private static void AddColliders(GameObject go) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) MeshFilter[] componentsInChildren = go.GetComponentsInChildren(); foreach (MeshFilter obj in componentsInChildren) { Mesh sharedMesh = obj.sharedMesh; if (!((Object)(object)obj == (Object)null)) { BoxCollider obj2 = go.AddComponent(); Bounds bounds = sharedMesh.bounds; obj2.center = ((Bounds)(ref bounds)).center; bounds = sharedMesh.bounds; obj2.size = ((Bounds)(ref bounds)).size; } } } } } namespace wackydatabase.GetData { [NullableContext(1)] [Nullable(0)] public class GetDataYML { internal RecipeData GetRecipeDataByName(string name, ObjectDB tod) { //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Expected O, but got Unknown GameObject val = DataHelpers.CheckforSpecialObjects(name); if ((Object)(object)val == (Object)null) { val = tod.GetItemPrefab(name); } if ((Object)(object)val == (Object)null) { foreach (Recipe recipe in tod.m_recipes) { if (!((Object)(object)recipe.m_item == (Object)null) && ((Object)recipe).name == name) { WMRecipeCust.Dbgl("An actual Recipe_ " + name + " has been found!-- Only Modification - No Cloning"); return GetRecip(recipe, tod, AllowClone: false); } } } if ((Object)(object)val == (Object)null) { WMRecipeCust.Dbgl("Recipe " + name + " not found!"); return null; } ItemData itemData = val.GetComponent().m_itemData; if (itemData == null) { WMRecipeCust.Dbgl("Item data not found!"); return null; } Recipe val2 = tod.GetRecipe(itemData); if (!Object.op_Implicit((Object)(object)val2)) { if (Chainloader.PluginInfos.ContainsKey("com.jotunn.jotunn")) { object value = ((object)Chainloader.PluginInfos["com.jotunn.jotunn"].Instance).GetType().Assembly.GetType("Jotunn.Managers.ItemManager").GetProperty("Instance", BindingFlags.Static | BindingFlags.Public).GetValue(null); MethodInfo methodInfo = AccessTools.Method(value.GetType(), "GetRecipe", (Type[])null, (Type[])null); object[] parameters = new string[1] { itemData.m_shared.m_name }; object obj = methodInfo.Invoke(value, parameters); if (obj != null) { val2 = (Recipe)AccessTools.Property(obj.GetType(), "Recipe").GetValue(obj); WMRecipeCust.Dbgl($"Jotunn recipe: {itemData.m_shared.m_name} {(Object)(object)val2 != (Object)null}"); } } if (!Object.op_Implicit((Object)(object)val2)) { WMRecipeCust.Dbgl("Recipe not found for item " + itemData.m_shared.m_name + "!"); return null; } } return GetRecip(val2, tod); } internal RecipeData GetRecipeDataByNum(int count, ObjectDB tod) { Recipe val = tod.m_recipes[count]; WMRecipeCust.Dbgl(" " + ((Object)val).name + " Item saving"); try { if (((Object)val).name.Contains("Recipe_")) { return GetRecip(val, tod, AllowClone: false); } return GetRecip(val, tod); } catch { WMRecipeCust.Dbgl(" Saving Actual Recipe Instead"); } return GetRecip(val, tod, AllowClone: false); } private RecipeData GetRecip(Recipe data, ObjectDB tod, bool AllowClone = true) { List list = new List(); Requirement[] resources = data.m_resources; foreach (Requirement val in resources) { list.Add($"{Utils.GetPrefabName(((Component)val.m_resItem).gameObject)}:{val.m_amount}:{val.m_amountPerLevel}:{val.m_recover}"); } string clonePrefabName = null; string text = ((Object)data).name; bool flag = false; if (!AllowClone) { if ((Object)(object)data.m_item != (Object)null) { if (text.Contains("_Recipe_")) { text = text.Substring(0, text.IndexOf("_Recipe_")); flag = true; } if (text != "Recipe_" + ((Object)data.m_item).name) { if (!flag) { clonePrefabName = "NO"; } ((Object)data).name = text; } else { ((Object)data).name = ((Object)data.m_item).name; } } else { clonePrefabName = "NO"; ((Object)data).name = text; } } else { ((Object)data).name = ((Object)data.m_item).name; } return new RecipeData { name = ((Object)data).name, amount = data.m_amount, clonePrefabName = clonePrefabName, craftingStation = (data.m_craftingStation?.m_name ?? ""), repairStation = (data.m_repairStation?.m_name ?? null), minStationLevel = data.m_minStationLevel, maxStationLevelCap = null, disabled = !data.m_enabled, disabledUpgrade = false, requireOnlyOneIngredient = data.m_requireOnlyOneIngredient, reqs = list }; } internal StatusData GetStatusEByName(string name, ObjectDB tod) { StatusEffect statusEffect = tod.GetStatusEffect(StringExtensionMethods.GetStableHashCode(name)); if ((Object)(object)statusEffect == (Object)null) { return null; } return GetStatusData(statusEffect); } internal StatusData GetStatusEByNum(int num, ObjectDB tod) { int num2 = tod.m_StatusEffects.Count(); if (num == num2) { return null; } string name = ((Object)tod.m_StatusEffects[num]).name; foreach (string noNotTheseSE in WMRecipeCust.NoNotTheseSEs) { if (name == noNotTheseSE) { return null; } } StatusData result = null; try { result = GetStatusData(tod.m_StatusEffects[num]); } catch { WMRecipeCust.WLog.LogWarning((object)("Something went wrong with a Status Effect " + ((Object)tod.m_StatusEffects[num]).name)); } return result; } private StatusData GetStatusData(StatusEffect effect) { //IL_04e0: Unknown result type (might be due to invalid IL or missing references) //IL_050e: Unknown result type (might be due to invalid IL or missing references) //IL_053c: Unknown result type (might be due to invalid IL or missing references) //IL_057c: Unknown result type (might be due to invalid IL or missing references) //IL_05aa: Unknown result type (might be due to invalid IL or missing references) //IL_061d: Unknown result type (might be due to invalid IL or missing references) //IL_071d: Unknown result type (might be due to invalid IL or missing references) //IL_072e: Unknown result type (might be due to invalid IL or missing references) //IL_0754: Unknown result type (might be due to invalid IL or missing references) //IL_077a: Unknown result type (might be due to invalid IL or missing references) Type type = ((object)effect).GetType(); WMRecipeCust.WLog.LogInfo((object)(" StatusEffect " + ((Object)effect).name)); SEShield sEShield = new SEShield(); if (Functions.getCast(type, "m_absorbDamage", effect) > 0f) { sEShield.AbsorbDmg = Functions.getCast(type, "m_absorbDamage", effect); sEShield.AbsorbDmgWorldLevel = Functions.getCast(type, "m_absorbDamageWorldLevel", effect); sEShield.LevelUpSkillFactor = Functions.getCast(type, "m_levelUpSkillFactor", effect); sEShield.TtlPerItemLevel = Functions.getCast(type, "m_ttlPerItemLevel", effect); sEShield.AbsorbDmgPerSkill = Functions.getCast(type, "m_absorbDamagePerSkillLevel", effect); } SEPoison sEPoison = new SEPoison(); if (Functions.getCast(type, "m_TTLPerDamagePlayer", effect) > 0f) { sEPoison.m_damageInterval = Functions.getCast(type, "m_damageInterval", effect); sEPoison.m_baseTTL = Functions.getCast(type, "m_baseTTL", effect); sEPoison.m_TTLPerDamagePlayer = Functions.getCast(type, "m_TTLPerDamagePlayer", effect); sEPoison.m_TTLPerDamage = Functions.getCast(type, "m_TTLPerDamage", effect); sEPoison.m_TTLPower = Functions.getCast(type, "m_TTLPower", effect); } SEFrost sEFrost = new SEFrost(); if (Functions.getCast(type, "m_freezeTimeEnemy", effect) > 0f) { sEFrost.m_freezeTimeEnemy = Functions.getCast(type, "m_freezeTimeEnemy", effect); sEFrost.m_freezeTimePlayer = Functions.getCast(type, "m_freezeTimePlayer", effect); sEFrost.m_minSpeedFactor = Functions.getCast(type, "m_minSpeedFactor", effect); } SEdata seData = new SEdata { m_heatlhUpFront = Functions.getCast(type, "m_healthUpFront", effect), m_tickInterval = Functions.getCast(type, "m_tickInterval", effect), m_healthPerTickMinHealthPercentage = Functions.getCast(type, "m_healthPerTickMinHealthPercentage", effect), m_healthPerTick = Functions.getCast(type, "m_healthPerTick", effect), m_healthOverTime = Functions.getCast(type, "m_healthOverTime", effect), m_healthOverTimeDuration = Functions.getCast(type, "m_healthOverTimeDuration", effect), m_healthOverTimeInterval = Functions.getCast(type, "m_healthOverTimeInterval", effect), m_healthOverTimeTimer = Functions.getCast(type, "m_healthOverTimeTimer", effect), m_healthOverTimeTicks = Functions.getCast(type, "m_healthOverTimeTicks", effect), m_healthOverTimeTickHP = Functions.getCast(type, "m_healthOverTimeTickHP", effect), m_staminaUpFront = Functions.getCast(type, "m_staminaUpFront", effect), m_staminaOverTime = Functions.getCast(type, "m_staminaOverTime", effect), m_staminaOverTimeDuration = Functions.getCast(type, "m_staminaOverTimeDuration", effect), m_staminaDrainPerSec = Functions.getCast(type, "m_staminaDrainPerSec", effect), m_runStaminaDrainModifier = Functions.getCast(type, "m_runStaminaDrainModifier", effect), m_jumpStaminaUseModifier = Functions.getCast(type, "m_jumpStaminaUseModifier", effect), m_attackStaminaUseModifier = Functions.getCast(type, "m_attackStaminaUseModifier", effect), m_blockStaminaUseModifier = Functions.getCast(type, "m_blockStaminaUseModifier", effect), m_dodgeStaminaUseModifier = Functions.getCast(type, "m_dodgeStaminaUseModifier", effect), m_swimStaminaUseModifier = Functions.getCast(type, "m_swimStaminaUseModifier", effect), m_homeItemStaminaUseModifier = Functions.getCast(type, "m_homeItemStaminaUseModifier", effect), m_sneakStaminaUseModifier = Functions.getCast(type, "m_sneakStaminaUseModifier", effect), m_runStaminaUseModifier = Functions.getCast(type, "m_runStaminaUseModifier", effect), m_blockStaminaUseFlatValue = Functions.getCast(type, "m_blockStaminaUseFlatValue", effect), m_adrenalineUpFront = Functions.getCast(type, "m_adrenalineUpFront", effect), m_adrenalineModifier = Functions.getCast(type, "m_adrenalineModifier", effect), m_staggerModifier = Functions.getCast(type, "m_staggerModifier", effect), m_staggerTimeBlockBonus = Functions.getCast(type, "m_timedBlockBonus", effect), m_eitrUpFront = Functions.getCast(type, "m_eitrUpFront", effect), m_eitrOverTime = Functions.getCast(type, "m_eitrOverTime", effect), m_eitrOverTimeDuration = Functions.getCast(type, "m_eitrOverTimeDuration", effect), m_healthRegenMultiplier = Functions.getCast(type, "m_healthRegenMultiplier", effect), m_staminaRegenMultiplier = Functions.getCast(type, "m_staminaRegenMultiplier", effect), m_eitrRegenMultiplier = Functions.getCast(type, "m_eitrRegenMultiplier", effect), m_armorAdd = Functions.getCast(type, "m_addArmor", effect), m_armorMultiplier = Functions.getCast(type, "m_armorMultiplier", effect), m_raiseSkill = Functions.getCast(type, "m_raiseSkill", effect), m_raiseSkillModifier = Functions.getCast(type, "m_raiseSkillModifier", effect), m_skillLevel = Functions.getCast(type, "m_skillLevel", effect), m_skillLevelModifier = Functions.getCast(type, "m_skillLevelModifier", effect), m_skillLevel2 = Functions.getCast(type, "m_skillLevel2", effect), m_skillLevelModifier2 = Functions.getCast(type, "m_skillLevelModifier2", effect), m_mods = Functions.getCast>(type, "m_mods", effect), m_modifyAttackSkill = Functions.getCast(type, "m_modifyAttackSkill", effect), m_damageModifier = Functions.getCast(type, "m_damageModifier", effect), m_percentDamageModifiers = Functions.getCast(type, "m_percentigeDamageModifiers", effect), m_noiseModifier = Functions.getCast(type, "m_noiseModifier", effect), m_stealthModifier = Functions.getCast(type, "m_stealthModifier", effect), m_addMaxCarryWeight = Functions.getCast(type, "m_addMaxCarryWeight", effect), m_speedModifier = Functions.getCast(type, "m_speedModifier", effect), m_jumpModifier = Functions.getCast(type, "m_jumpModifier", effect), m_maxMaxFallSpeed = Functions.getCast(type, "m_maxMaxFallSpeed", effect), m_fallDamageModifier = Functions.getCast(type, "m_fallDamageModifier", effect), m_tickTimer = Functions.getCast(type, "m_tickTimer", effect), m_windMovementModifier = Functions.getCast(type, "m_windMovementModifier", effect) }; StatusData statusData = new StatusData { Name = (((Object)effect).name ?? ""), Status_m_name = (effect.m_name ?? ""), Category = (effect.m_category ?? null), IconName = (((Object)effect.m_icon).name ?? ""), FlashIcon = effect.m_flashIcon, CooldownIcon = effect.m_cooldownIcon, Tooltip = (effect.m_tooltip ?? ""), Attributes = effect.m_attributes, StartMessageLoc = effect.m_startMessageType, StartMessage = (effect.m_startMessage ?? ""), StopMessageLoc = effect.m_stopMessageType, StopMessage = (effect.m_stopMessage ?? ""), RepeatMessageLoc = effect.m_repeatMessageType, RepeatMessage = (effect.m_repeatMessage ?? ""), RepeatInterval = effect.m_repeatInterval, TimeToLive = effect.m_ttl, StartEffect_PLUS = (ConvertEffectstoVerse(effect.m_startEffects?.m_effectPrefabs) ?? null), StopEffect_PLUS = (ConvertEffectstoVerse(effect.m_stopEffects?.m_effectPrefabs) ?? null), Cooldown = effect.m_cooldown, ActivationAnimation = (effect.m_activationAnimation ?? ""), SeData = seData }; if (Functions.getCast(type, "m_absorbDamage", effect) > 0f) { statusData.SeShield = sEShield; } if (Functions.getCast(type, "m_TTLPerDamagePlayer", effect) > 0f) { statusData.SePoison = sEPoison; } if (Functions.getCast(type, "m_freezeTimeEnemy", effect) > 0f) { statusData.SeFrost = sEFrost; } return statusData; } internal GameObject GetJustThePieceRecipeByName(string name, ObjectDB tod, bool warn = true) { WMRecipeCust.selectedPiecehammer = null; GameObject val = DataHelpers.GetPieces(tod).Find((GameObject g) => Utils.GetPrefabName(g) == name); if ((Object)(object)val == (Object)null) { val = DataHelpers.GetModdedPieces(name); if ((Object)(object)val == (Object)null) { val = DataHelpers.CheckforSpecialObjects(name); if ((Object)(object)val == (Object)null) { WMRecipeCust.Dbgl("Piece " + name + " not found! 3 layer search"); return null; } } else { WMRecipeCust.Dbgl($"Piece {name} from known hammer {WMRecipeCust.selectedPiecehammer}"); } } if ((Object)(object)val.GetComponent() == (Object)null) { WMRecipeCust.Dbgl("Piece data not found!"); return null; } return val; } internal PieceData GetPieceRecipeByName(string name, ObjectDB tod, bool warn = true) { WMRecipeCust.selectedPiecehammer = null; GameObject val = DataHelpers.GetPieces(tod).Find((GameObject g) => Utils.GetPrefabName(g) == name); if ((Object)(object)val == (Object)null) { val = DataHelpers.GetModdedPieces(name); if ((Object)(object)val == (Object)null) { val = DataHelpers.CheckforSpecialObjects(name); if ((Object)(object)val == (Object)null) { WMRecipeCust.Dbgl("Piece " + name + " not found! 3 layer search"); return null; } } else { WMRecipeCust.Dbgl($"Piece {name} from known hammer {WMRecipeCust.selectedPiecehammer}"); } } if ((Object)(object)val.GetComponent() == (Object)null) { WMRecipeCust.Dbgl("Piece data not found!"); return null; } string text = null; ItemDrop val2 = null; if ((Object)(object)WMRecipeCust.selectedPiecehammer != (Object)null) { val2 = ((Component)WMRecipeCust.selectedPiecehammer).GetComponent(); text = ((Object)WMRecipeCust.selectedPiecehammer).name; } else { if (text == null) { text = "Hammer"; } GameObject itemPrefab = tod.GetItemPrefab("Hammer"); val2 = ((itemPrefab != null) ? itemPrefab.GetComponent() : null); GameObject itemPrefab2 = tod.GetItemPrefab("Hoe"); ItemDrop val3 = ((itemPrefab2 != null) ? itemPrefab2.GetComponent() : null); if (Object.op_Implicit((Object)(object)val2) && val2.m_itemData.m_shared.m_buildPieces.m_pieces.Contains(val)) { text = "Hammer"; } else if (Object.op_Implicit((Object)(object)val3) && val3.m_itemData.m_shared.m_buildPieces.m_pieces.Contains(val)) { text = "Hoe"; val2 = val3; } else { WMRecipeCust.WLog.LogWarning((object)"Hammer selector needs help! in getdata GetPieceRecipeByName"); } } return GetPiece(val2, text, val, tod); } internal PieceData GetPieceRecipeByNum(int count, string hammername, ItemDrop HamerItemdrop, ObjectDB tod, ItemDrop itemD = null) { GameObject val = null; val = HamerItemdrop.m_itemData.m_shared.m_buildPieces.m_pieces[count]; return GetPiece(HamerItemdrop, hammername, val, tod); } internal PieceData GetPiece(ItemDrop HammerID, string Hammername, GameObject PieceID, ObjectDB tod) { //IL_0099: 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_01f3: 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_0243: Unknown result type (might be due to invalid IL or missing references) //IL_04d9: Unknown result type (might be due to invalid IL or missing references) //IL_0a7d: Unknown result type (might be due to invalid IL or missing references) Dictionary pieceCategoriesMap = PiecePrefabManager.GetPieceCategoriesMap(); Piece component = PieceID.GetComponent(); WMRecipeCust.WLog.LogInfo((object)("Piece " + ((Object)PieceID).name + " in " + Hammername)); PieceData pieceData = new PieceData { name = ((Object)PieceID).name, piecehammer = Hammername, craftingStation = (component.m_craftingStation?.m_name ?? ""), minStationLevel = 1, adminonly = false, m_name = component.m_name, m_description = component.m_description, piecehammerCategory = pieceCategoriesMap[component.m_category], sizeMultiplier = "1", customIcon = null, clonePrefabName = null, material = null, damagedMaterial = null, disabled = !((Behaviour)component).enabled, groundPiece = component.m_groundPiece, ground = component.m_groundOnly, waterPiece = component.m_waterPiece, noInWater = component.m_noInWater, notOnFloor = component.m_notOnFloor, onlyinTeleportArea = component.m_onlyInTeleportArea, allowedInDungeons = component.m_allowedInDungeons, canBeRemoved = component.m_canBeRemoved, notOnWood = component.m_notOnWood }; if (component.m_comfort != 0) { ComfortData obj = new ComfortData { comfort = component.m_comfort, comfortGroup = component.m_comfortGroup }; GameObject comfortObject = component.m_comfortObject; obj.comfortObjectName = ((comfortObject != null) ? ((Object)comfortObject).name : null); ComfortData comfort = obj; pieceData.comfort = comfort; } WearNTear val = default(WearNTear); if (PieceID.TryGetComponent(ref val)) { WearNTearData wearNTearData = new WearNTearData { health = val.m_health, damageModifiers = val.m_damages, noRoofWear = val.m_noRoofWear, noSupportWear = val.m_noSupportWear, supports = val.m_supports, triggerPrivateArea = val.m_triggerPrivateArea, materialType = val.m_materialType, burnable = val.m_burnable }; pieceData.wearNTearData = wearNTearData; } CraftingStation val2 = default(CraftingStation); if (PieceID.TryGetComponent(ref val2)) { CraftingStationData craftingStationData = new CraftingStationData { cStationCustomIcon = null, discoveryRange = val2.m_discoverRange, buildRange = val2.m_rangeBuild, craftRequiresRoof = val2.m_craftRequireRoof, craftRequiresFire = val2.m_craftRequireFire, showBasicRecipes = val2.m_showBasicRecipies, useDistance = val2.m_useDistance, useAnimation = val2.m_useAnimation }; pieceData.craftingStationData = craftingStationData; } StationExtension val3 = default(StationExtension); if (PieceID.TryGetComponent(ref val3)) { if (PieceID.GetComponents().Count() > 1) { pieceData.cSExtensionDataList = new List(); StationExtension[] components = PieceID.GetComponents(); foreach (StationExtension val4 in components) { CSExtensionData cSExtensionData = new CSExtensionData(); CraftingStation craftingStation = val4.m_craftingStation; cSExtensionData.MainCraftingStationName = ((craftingStation != null) ? ((Object)craftingStation).name : null) ?? ((object)val4.m_craftingStation).ToString(); cSExtensionData.maxStationDistance = val4.m_maxStationDistance; cSExtensionData.continousConnection = val4.m_continousConnection; cSExtensionData.stack = val4.m_stack; pieceData.cSExtensionDataList.Add(cSExtensionData); } } else { pieceData.cSExtensionDataList = new List(); CSExtensionData item = new CSExtensionData { MainCraftingStationName = ((Object)val3.m_craftingStation).name, maxStationDistance = val3.m_maxStationDistance, continousConnection = val3.m_continousConnection, stack = val3.m_stack }; pieceData.cSExtensionDataList.Add(item); } } Container val5 = default(Container); if (PieceID.TryGetComponent(ref val5)) { ContainerData contData = new ContainerData { Width = val5.m_width, Height = val5.m_height, CheckWard = val5.m_checkGuardStone, AutoDestoryIfEmpty = val5.m_autoDestroyEmpty }; pieceData.contData = contData; } Beehive val6 = default(Beehive); if (PieceID.TryGetComponent(ref val6)) { BeehiveData beehiveData = new BeehiveData { effectOnlyInDaylight = val6.m_effectOnlyInDaylight, maxCover = val6.m_maxCover, biomes = val6.m_biome, secPerUnit = val6.m_secPerUnit, maxAmount = val6.m_maxHoney, dropItem = ((Object)val6.m_honeyItem).name, effectsPLUS = (ConvertEffectstoVerse(val6.m_spawnEffect.m_effectPrefabs) ?? null), extractText = val6.m_extractText, checkText = val6.m_checkText, areaText = val6.m_areaText, freespaceText = val6.m_freespaceText, sleepText = val6.m_sleepText, happyText = val6.m_happyText }; pieceData.beehiveData = beehiveData; } CookingStation val7 = default(CookingStation); if (PieceID.TryGetComponent(ref val7)) { List list = new List(); foreach (ItemConversion item2 in val7.m_conversion) { CookStationConversionList cookStationConversionList = new CookStationConversionList(); cookStationConversionList.FromName = ((Object)item2.m_from).name; cookStationConversionList.ToName = ((Object)item2.m_to).name; cookStationConversionList.CookTime = item2.m_cookTime; cookStationConversionList.Remove = false; list.Add(cookStationConversionList); } CookingStationData cookingStationData = new CookingStationData(); if (((Object)val7).name == "piece_oven") { cookingStationData.addItemTooltip = val7.m_addItemTooltip; cookingStationData.overcookedItem = ((Object)val7.m_overCookedItem).name; cookingStationData.fuelItem = ((Object)val7.m_fuelItem).name; cookingStationData.requireFire = val7.m_requireFire; cookingStationData.maxFuel = val7.m_maxFuel; cookingStationData.secPerFuel = val7.m_secPerFuel; cookingStationData.cookConversion = list; pieceData.cookingStationData = cookingStationData; } else { cookingStationData.addItemTooltip = val7.m_addItemTooltip; cookingStationData.overcookedItem = ((Object)val7.m_overCookedItem).name; cookingStationData.requireFire = val7.m_requireFire; cookingStationData.cookConversion = list; pieceData.cookingStationData = cookingStationData; } } Fermenter val8 = default(Fermenter); if (PieceID.TryGetComponent(ref val8)) { List list2 = new List(); foreach (ItemConversion item3 in val8.m_conversion) { FermenterConversionList fermenterConversionList = new FermenterConversionList(); fermenterConversionList.FromName = ((Object)((Component)item3.m_from).gameObject).name; fermenterConversionList.ToName = ((Object)((Component)item3.m_to).gameObject).name; fermenterConversionList.Amount = item3.m_producedItems; fermenterConversionList.Remove = false; list2.Add(fermenterConversionList); } FermenterData fermenterData = new FermenterData(); fermenterData.fermDuration = val8.m_fermentationDuration; fermenterData.fermConversion = list2; pieceData.fermStationData = fermenterData; } Ship val9 = default(Ship); if (PieceID.TryGetComponent(ref val9)) { ShipData shipData = new ShipData(); shipData.ashlandProof = val9.m_ashlandsReady; pieceData.shipData = shipData; } ShieldGenerator val10 = default(ShieldGenerator); if (PieceID.TryGetComponent(ref val10)) { ShieldGenData shieldGenData = new ShieldGenData(); shieldGenData.name = val10.m_name; shieldGenData.nameAdd = val10.m_add; shieldGenData.fuelPerDamage = val10.m_fuelPerDamage; shieldGenData.offWhenOutofFuel = val10.m_offWhenNoFuel; shieldGenData.maxFuel = val10.m_maxFuel; shieldGenData.spawnWithFuel = val10.m_defaultFuel; shieldGenData.maxRadius = val10.m_maxShieldRadius; shieldGenData.minRadius = val10.m_minShieldRadius; shieldGenData.attack = val10.m_enableAttack; shieldGenData.attackChargeTime = val10.m_attackChargeTime; shieldGenData.attackPlayers = val10.m_damagePlayers; List list3 = new List(); foreach (ItemDrop fuelItem2 in val10.m_fuelItems) { list3.Add(((Object)fuelItem2).name); } shieldGenData.fuel = list3; pieceData.shieldGenData = shieldGenData; } SiegeMachine val11 = default(SiegeMachine); if (PieceID.TryGetComponent(ref val11)) { BatteringRamData batteringRamData = new BatteringRamData(); batteringRamData.chargeTime = val11.m_chargeTime; batteringRamData.maxFuel = PieceID.GetComponentInChildren().m_maxOre; pieceData.batteringRamData = batteringRamData; } Plant val12 = default(Plant); if (PieceID.TryGetComponent(ref val12)) { PlantData plantData = new PlantData(); plantData.m_name = val12.m_name; plantData.GrowTime = val12.m_growTime; plantData.MaxGrowTime = val12.m_growTimeMax; plantData.GrowPrefab = ((Object)val12.m_grownPrefabs[0]).name; plantData.MinSize = val12.m_minScale; plantData.MaxSize = val12.m_maxScale; plantData.GrowRadius = val12.m_growRadius; plantData.GrowRadiusVines = val12.m_growRadiusVines; plantData.CultivatedGround = val12.m_needCultivatedGround; plantData.DestroyIfCantGrow = val12.m_destroyIfCantGrow; plantData.TolerateHeat = val12.m_tolerateHeat; plantData.TolerateCold = val12.m_tolerateCold; plantData.Biomes = val12.m_biome; pieceData.plantData = plantData; } SapCollector val13 = default(SapCollector); if (PieceID.TryGetComponent(ref val13)) { SapData sapData = new SapData(); sapData.secPerUnit = val13.m_secPerUnit; sapData.maxLevel = val13.m_maxLevel; sapData.producedItem = ((Object)((Component)val13.m_spawnItem).gameObject).name; sapData.connectedToWhat = ((Object)((Component)val13.m_mustConnectTo).gameObject).name; sapData.extractText = val13.m_extractText; sapData.drainingText = val13.m_drainingText; sapData.drainingSlowText = val13.m_drainingSlowText; sapData.notConnectedText = val13.m_notConnectedText; sapData.fullText = val13.m_fullText; pieceData.sapData = sapData; } Incinerator val14 = default(Incinerator); if (PieceID.TryGetComponent(ref val14)) { ObliteratorData obliteratorData = new ObliteratorData(); obliteratorData.defaultCostPerDrop = val14.m_defaultCost; obliteratorData.defaultDrop = ((Object)val14.m_defaultResult).name; List list4 = new List(); foreach (IncineratorConversion conversion in val14.m_conversions) { ObliteratorList obliteratorList = new ObliteratorList(); obliteratorList.Priority = conversion.m_priority; obliteratorList.Result = ((Object)conversion.m_result).name; obliteratorList.ResultAmount = conversion.m_resultAmount; obliteratorList.RequireOnlyOne = conversion.m_requireOnlyOneIngredient; List list5 = new List(); foreach (Requirement requirement in conversion.m_requirements) { ObRequirementList obRequirementList = new ObRequirementList(); obRequirementList.Name = ((Object)requirement.m_resItem).name; obRequirementList.Amount = requirement.m_amount; list5.Add(obRequirementList); } obliteratorList.Requirements = list5; list4.Add(obliteratorList); } pieceData.incineratorData = obliteratorData; pieceData.incineratorData.incineratorConversion = list4; } Fireplace val15 = default(Fireplace); if (PieceID.TryGetComponent(ref val15)) { try { FireplaceData fireplaceData = new FireplaceData(); fireplaceData.StartFuel = val15.m_startFuel; fireplaceData.MaxFuel = val15.m_maxFuel; fireplaceData.SecPerFuel = val15.m_secPerFuel; fireplaceData.InfiniteFuel = val15.m_infiniteFuel; fireplaceData.FuelType = ((Object)val15.m_fuelItem).name; fireplaceData.IgniteInterval = val15.m_igniteInterval; fireplaceData.IgniteChance = val15.m_igniteChance; fireplaceData.IgniteSpread = val15.m_igniteSpread; pieceData.fireplaceData = fireplaceData; } catch { WMRecipeCust.WLog.LogWarning((object)"Error catch in Fireplace"); } } TeleportWorld val16 = default(TeleportWorld); if (PieceID.TryGetComponent(ref val16)) { TeleportWorldData teleportWorldData = new TeleportWorldData(); teleportWorldData.AllowAllItems = val16.m_allowAllItems; pieceData.teleportWorldData = teleportWorldData; } try { Smelter val17 = default(Smelter); if (PieceID.TryGetComponent(ref val17)) { if (((Object)val17).name == "charcoal_kiln" || ((Object)val17).name == "windmill" || ((Object)val17).name == "piece_spinningwheel") { List list6 = new List(); foreach (ItemConversion item4 in val17.m_conversion) { SmelterConversionList smelterConversionList = new SmelterConversionList(); smelterConversionList.FromName = ((Object)item4.m_from).name; smelterConversionList.ToName = ((Object)item4.m_to).name; smelterConversionList.Remove = false; list6.Add(smelterConversionList); } SmelterData smelterData = new SmelterData { smelterConversion = list6, emptyOreTooltip = val17.m_emptyOreTooltip, addOreTooltip = val17.m_addOreTooltip, maxOre = val17.m_maxOre, secPerProduct = val17.m_secPerProduct }; pieceData.smelterData = smelterData; } else { fuelItemData fuelItem = new fuelItemData { name = ((Object)val17.m_fuelItem).name }; List list7 = new List(); foreach (ItemConversion item5 in val17.m_conversion) { SmelterConversionList smelterConversionList2 = new SmelterConversionList(); smelterConversionList2.FromName = ((Object)item5.m_from).name; smelterConversionList2.ToName = ((Object)item5.m_to).name; smelterConversionList2.Remove = false; list7.Add(smelterConversionList2); } SmelterData smelterData2 = new SmelterData { addOreTooltip = val17.m_addOreTooltip, emptyOreTooltip = val17.m_emptyOreTooltip, fuelItem = fuelItem, maxOre = val17.m_maxOre, maxFuel = val17.m_maxFuel, fuelPerProduct = val17.m_fuelPerProduct, secPerProduct = val17.m_secPerProduct, spawnStack = val17.m_spawnStack, requiresRoof = val17.m_requiresRoof, addOreAnimationLength = val17.m_addOreAnimationDuration, smelterConversion = list7 }; pieceData.smelterData = smelterData2; } } } catch { } Requirement[] resources = component.m_resources; foreach (Requirement val18 in resources) { pieceData.build.Add($"{Utils.GetPrefabName(((Component)val18.m_resItem).gameObject)}:{val18.m_amount}:{val18.m_amountPerLevel}:{val18.m_recover}"); } return pieceData; } internal WItemData GetItemDataByName(string name, ObjectDB tod) { GameObject val = DataHelpers.CheckforSpecialObjects(name); if ((Object)(object)val == (Object)null) { val = tod.GetItemPrefab(name); } if ((Object)(object)val == (Object)null) { WMRecipeCust.Dbgl("GetItemDataByName data not found!"); return null; } if (val.GetComponent().m_itemData == null) { WMRecipeCust.Dbgl("Item GetItemDataByName not found! - componets"); return null; } return GetItem(val, tod); } internal WItemData GetItemDataByCount(int count, ObjectDB tod) { GameObject go = tod.m_items[count]; return GetItem(go, tod); } private string[] CheckEffectsArray(EffectData[] tosh) { if (tosh == null) { return null; } string[] result = null; try { if (tosh.Count() > 0 && tosh != null) { return tosh.Select([NullableContext(0)] (EffectData p) => ((Object)p.m_prefab).name).ToArray(); } } catch { } return result; } [return: Nullable(new byte[] { 2, 1 })] private EffectVerse[] ConvertEffectstoVerse(EffectData[] tosh) { if (tosh == null) { return null; } try { EffectVerse[] array = new EffectVerse[tosh.Count()]; int num = 0; foreach (EffectData val in tosh) { if (val != null) { if ((Object)(object)val.m_prefab != (Object)null) { EffectVerse effectVerse = new EffectVerse(); GameObject prefab = val.m_prefab; effectVerse.name = ((prefab != null) ? ((Object)prefab).name : null); effectVerse.m_enabled = val.m_enabled; effectVerse.m_variant = val.m_variant; effectVerse.m_attach = val.m_attach; effectVerse.m_follow = val.m_follow; effectVerse.m_inheritParentRotation = val.m_inheritParentRotation; effectVerse.m_inheritParentScale = val.m_inheritParentScale; effectVerse.m_multiplyParentVisualScale = val.m_multiplyParentVisualScale; effectVerse.m_randomRotation = val.m_randomRotation; effectVerse.m_scale = val.m_scale; effectVerse.m_childTransform = val.m_childTransform; array[num] = effectVerse; num++; } else { WMRecipeCust.WLog.LogWarning((object)" effect prefab is null, skipping effect"); } } else { WMRecipeCust.WLog.LogWarning((object)" effect is null, skipping effect"); } } return array; } catch { WMRecipeCust.WLog.LogWarning((object)" One Effect returned null - be careful with last item "); return null; } } private WItemData GetItem(GameObject go, ObjectDB tod) { //IL_0a4b: Unknown result type (might be due to invalid IL or missing references) //IL_0a61: Unknown result type (might be due to invalid IL or missing references) //IL_0a77: Unknown result type (might be due to invalid IL or missing references) //IL_0a8d: Unknown result type (might be due to invalid IL or missing references) //IL_0ca5: Unknown result type (might be due to invalid IL or missing references) //IL_1194: Unknown result type (might be due to invalid IL or missing references) //IL_1207: Unknown result type (might be due to invalid IL or missing references) //IL_1222: Unknown result type (might be due to invalid IL or missing references) //IL_123d: Unknown result type (might be due to invalid IL or missing references) //IL_13cd: Unknown result type (might be due to invalid IL or missing references) //IL_1886: Unknown result type (might be due to invalid IL or missing references) //IL_18f9: Unknown result type (might be due to invalid IL or missing references) //IL_1914: Unknown result type (might be due to invalid IL or missing references) //IL_192f: Unknown result type (might be due to invalid IL or missing references) ItemData itemData = go.GetComponent().m_itemData; if (itemData == null) { WMRecipeCust.Dbgl("Item GetItemDataByName not found! - componets"); return null; } bool flag = false; WDamages damage = null; if (itemData.m_shared.m_damages.m_blunt > 0f || itemData.m_shared.m_damages.m_chop > 0f || itemData.m_shared.m_damages.m_damage > 0f || itemData.m_shared.m_damages.m_fire > 0f || itemData.m_shared.m_damages.m_frost > 0f || itemData.m_shared.m_damages.m_lightning > 0f || itemData.m_shared.m_damages.m_pickaxe > 0f || itemData.m_shared.m_damages.m_pierce > 0f || itemData.m_shared.m_damages.m_poison > 0f || itemData.m_shared.m_damages.m_slash > 0f || itemData.m_shared.m_damages.m_spirit > 0f) { WMRecipeCust.Dbgl("Item " + ((Object)go.GetComponent()).name + " damage on "); flag = true; damage = new WDamages { Blunt = itemData.m_shared.m_damages.m_blunt, Chop = itemData.m_shared.m_damages.m_chop, Damage = itemData.m_shared.m_damages.m_damage, Fire = itemData.m_shared.m_damages.m_fire, Frost = itemData.m_shared.m_damages.m_frost, Lightning = itemData.m_shared.m_damages.m_lightning, Pickaxe = itemData.m_shared.m_damages.m_pickaxe, Pierce = itemData.m_shared.m_damages.m_pierce, Poison = itemData.m_shared.m_damages.m_poison, Slash = itemData.m_shared.m_damages.m_slash, Spirit = itemData.m_shared.m_damages.m_spirit }; } WDamages damage_Per_Level = null; if (itemData.m_shared.m_damagesPerLevel.m_blunt > 0f || itemData.m_shared.m_damagesPerLevel.m_chop > 0f || itemData.m_shared.m_damagesPerLevel.m_damage > 0f || itemData.m_shared.m_damagesPerLevel.m_fire > 0f || itemData.m_shared.m_damagesPerLevel.m_frost > 0f || itemData.m_shared.m_damagesPerLevel.m_lightning > 0f || itemData.m_shared.m_damagesPerLevel.m_pickaxe > 0f || itemData.m_shared.m_damagesPerLevel.m_pierce > 0f || itemData.m_shared.m_damagesPerLevel.m_poison > 0f || itemData.m_shared.m_damagesPerLevel.m_slash > 0f || itemData.m_shared.m_damagesPerLevel.m_spirit > 0f) { damage_Per_Level = new WDamages { Blunt = itemData.m_shared.m_damagesPerLevel.m_blunt, Chop = itemData.m_shared.m_damagesPerLevel.m_chop, Damage = itemData.m_shared.m_damagesPerLevel.m_damage, Fire = itemData.m_shared.m_damagesPerLevel.m_fire, Frost = itemData.m_shared.m_damagesPerLevel.m_frost, Lightning = itemData.m_shared.m_damagesPerLevel.m_lightning, Pickaxe = itemData.m_shared.m_damagesPerLevel.m_pickaxe, Pierce = itemData.m_shared.m_damagesPerLevel.m_pierce, Poison = itemData.m_shared.m_damagesPerLevel.m_poison, Slash = itemData.m_shared.m_damagesPerLevel.m_slash, Spirit = itemData.m_shared.m_damagesPerLevel.m_spirit }; } StatMods moddifiers = new StatMods { m_movementModifier = itemData.m_shared.m_movementModifier, m_EitrRegen = itemData.m_shared.m_eitrRegenModifier, m_homeItemsStaminaModifier = itemData.m_shared.m_homeItemsStaminaModifier, m_heatResistanceModifier = itemData.m_shared.m_heatResistanceModifier, m_jumpStaminaModifier = itemData.m_shared.m_jumpStaminaModifier, m_attackStaminaModifier = itemData.m_shared.m_attackStaminaModifier, m_blockStaminaModifier = itemData.m_shared.m_blockStaminaModifier, m_dodgeStaminaModifier = itemData.m_shared.m_dodgeStaminaModifier, m_swimStaminaModifier = itemData.m_shared.m_swimStaminaModifier, m_sneakStaminaModifier = itemData.m_shared.m_sneakStaminaModifier, m_runStaminaModifier = itemData.m_shared.m_runStaminaModifier }; GEffectsPLUS gEffectsPLUS = new GEffectsPLUS { Hit_Effects = ConvertEffectstoVerse(itemData.m_shared.m_hitEffect?.m_effectPrefabs), Hit_Terrain_Effects = ConvertEffectstoVerse(itemData.m_shared.m_hitTerrainEffect?.m_effectPrefabs), Start_Effect = ConvertEffectstoVerse(itemData.m_shared.m_startEffect?.m_effectPrefabs), Hold_Start_Effects = ConvertEffectstoVerse(itemData.m_shared.m_holdStartEffect?.m_effectPrefabs), Trigger_Effect = ConvertEffectstoVerse(itemData.m_shared.m_triggerEffect?.m_effectPrefabs), Trail_Effect = ConvertEffectstoVerse(itemData.m_shared.m_trailStartEffect?.m_effectPrefabs) }; AEffectsPLUS aEffectsPLUS = new AEffectsPLUS { Hit_Effects = ConvertEffectstoVerse(itemData.m_shared.m_attack?.m_hitEffect?.m_effectPrefabs), Hit_Terrain_Effects = ConvertEffectstoVerse(itemData.m_shared.m_attack?.m_hitTerrainEffect.m_effectPrefabs), Start_Effect = ConvertEffectstoVerse(itemData.m_shared.m_attack?.m_startEffect.m_effectPrefabs), Trigger_Effect = ConvertEffectstoVerse(itemData.m_shared.m_attack?.m_triggerEffect.m_effectPrefabs), Trail_Effect = ConvertEffectstoVerse(itemData.m_shared.m_attack?.m_trailStartEffect.m_effectPrefabs), Burst_Effect = ConvertEffectstoVerse(itemData.m_shared.m_attack?.m_burstEffect?.m_effectPrefabs) }; AEffectsPLUS aEffectsPLUS2 = new AEffectsPLUS { Hit_Effects = ConvertEffectstoVerse(itemData.m_shared.m_secondaryAttack?.m_hitEffect?.m_effectPrefabs), Hit_Terrain_Effects = ConvertEffectstoVerse(itemData.m_shared.m_secondaryAttack?.m_hitTerrainEffect.m_effectPrefabs), Start_Effect = ConvertEffectstoVerse(itemData.m_shared.m_secondaryAttack?.m_startEffect.m_effectPrefabs), Trigger_Effect = ConvertEffectstoVerse(itemData.m_shared.m_secondaryAttack?.m_triggerEffect.m_effectPrefabs), Trail_Effect = ConvertEffectstoVerse(itemData.m_shared.m_secondaryAttack?.m_trailStartEffect.m_effectPrefabs), Burst_Effect = ConvertEffectstoVerse(itemData.m_shared.m_secondaryAttack?.m_burstEffect?.m_effectPrefabs) }; WMRecipeCust.Dbgl("Item " + ((Object)go.GetComponent()).name + " Main "); WItemData wItemData = new WItemData { name = ((Object)go.GetComponent()).name, m_description = itemData.m_shared.m_description, m_durabilityDrain = itemData.m_shared.m_durabilityDrain, m_durabilityPerLevel = itemData.m_shared.m_durabilityPerLevel, m_backstabbonus = itemData.m_shared.m_backstabBonus, m_equipDuration = itemData.m_shared.m_equipDuration, m_maxDurability = itemData.m_shared.m_maxDurability, m_maxQuality = itemData.m_shared.m_maxQuality, m_maxStackSize = itemData.m_shared.m_maxStackSize, m_toolTier = itemData.m_shared.m_toolTier, m_useDurability = itemData.m_shared.m_useDurability, m_useDurabilityDrain = itemData.m_shared.m_useDurabilityDrain, m_value = itemData.m_shared.m_value, scale_weight_by_quality = itemData.m_shared.m_scaleWeightByQuality, sizeMultiplier = "1", m_weight = itemData.m_shared.m_weight, m_destroyBroken = itemData.m_shared.m_destroyBroken, m_dodgeable = itemData.m_shared.m_dodgeable, blockable = itemData.m_shared.m_blockable, m_canBeReparied = itemData.m_shared.m_canBeReparied, m_name = itemData.m_shared.m_name, m_questItem = itemData.m_shared.m_questItem, m_teleportable = itemData.m_shared.m_teleportable, m_knockback = itemData.m_shared.m_attackForce, m_skillType = itemData.m_shared.m_skillType, m_animationState = itemData.m_shared.m_animationState, m_itemType = itemData.m_shared.m_itemType, Attach_Override = itemData.m_shared.m_attachOverride, Damage = damage, Damage_Per_Level = damage_Per_Level, Moddifiers = moddifiers, damageModifiers = itemData.m_shared.m_damageModifiers.Select([NullableContext(0)] (DamageModPair m) => ((object)(DamageType)(ref m.m_type)).ToString() + ":" + ((object)(DamageModifier)(ref m.m_modifier)).ToString()).ToList(), GEffectsPLUS = gEffectsPLUS }; if (WMRecipeCust.ClonedPrefabsMap.ContainsKey(((Object)go).name)) { wItemData.clonePrefabName = WMRecipeCust.ClonedPrefabsMap[((Object)go).name]; } if ((Object)(object)itemData.m_shared.m_equipStatusEffect != (Object)null) { WMRecipeCust.Dbgl("Item " + ((Object)go.GetComponent()).name + " SEs "); SE_Equip sE_Equip = new SE_Equip { EffectName = ((Object)itemData.m_shared.m_equipStatusEffect).name }; wItemData.SE_Equip = sE_Equip; } if ((Object)(object)itemData.m_shared.m_setStatusEffect != (Object)null) { WMRecipeCust.Dbgl("Item " + ((Object)go.GetComponent()).name + " SEset "); SE_SET_Equip sE_SET_Equip = new SE_SET_Equip { SetName = (itemData.m_shared.m_setName ?? ""), Size = itemData.m_shared.m_setSize, EffectName = (((Object)itemData.m_shared.m_setStatusEffect).name ?? "") }; wItemData.SE_SET_Equip = sE_SET_Equip; } if (((Object)go).name == "StaffShield" || ((Object)go).name == "StaffSkeleton" || ((Object)go).name == "StaffRedTroll") { flag = true; } Attack val = default(Attack); if (go.TryGetComponent(ref val) && val != null && (val.m_attackAnimation != null || val.m_attackAnimation != "")) { flag = true; } if (flag) { WMRecipeCust.Dbgl("Item " + ((Object)go.GetComponent()).name + " attack "); AttackArm obj = new AttackArm { AttackType = itemData.m_shared.m_attack.m_attackType, Attack_Animation = itemData.m_shared.m_attack.m_attackAnimation, Attack_Random_Animation = itemData.m_shared.m_attack.m_attackRandomAnimations, Chain_Attacks = itemData.m_shared.m_attack.m_attackChainLevels, Hit_Terrain = itemData.m_shared.m_attack.m_hitTerrain, Hit_Friendly = itemData.m_shared.m_attack.m_hitFriendly, is_HomeItem = itemData.m_shared.m_attack.m_isHomeItem, Custom_AttackSpeed = 1f, m_attackStamina = itemData.m_shared.m_attack.m_attackStamina, m_attackAdrenaline = itemData.m_shared.m_attack.m_attackAdrenaline, m_attackUseAdrenaline = itemData.m_shared.m_attack.m_attackUseAdrenaline, m_eitrCost = itemData.m_shared.m_attack.m_attackEitr, AttackHealthCost = itemData.m_shared.m_attack.m_attackHealth, m_attackHealthPercentage = itemData.m_shared.m_attack.m_attackHealthPercentage, attack_Health_Low_BlockUsage = itemData.m_shared.m_attack.m_attackHealthLowBlockUse, Attack_Start_Noise = itemData.m_shared.m_attack.m_attackStartNoise, Attack_Hit_Noise = itemData.m_shared.m_attack.m_attackHitNoise, Dmg_Multiplier_Per_Missing_Health = itemData.m_shared.m_attack.m_damageMultiplierPerMissingHP, Damage_Multiplier_By_Health_Deficit_Percent = itemData.m_shared.m_attack.m_damageMultiplierByTotalHealthMissing, Stamina_Return_Per_Missing_HP = itemData.m_shared.m_attack.m_staminaReturnPerMissingHP, SelfDamage = itemData.m_shared.m_attack.m_selfDamage, Attack_Kills_Self = itemData.m_shared.m_attack.m_attackKillsSelf, SpeedFactor = itemData.m_shared.m_attack.m_speedFactor, DmgMultiplier = itemData.m_shared.m_attack.m_damageMultiplier, ForceMultiplier = itemData.m_shared.m_attack.m_forceMultiplier, StaggerMultiplier = itemData.m_shared.m_attack.m_staggerMultiplier, RecoilMultiplier = itemData.m_shared.m_attack.m_recoilPushback, AttackRange = itemData.m_shared.m_attack.m_attackRange, AttackHeight = itemData.m_shared.m_attack.m_attackHeight }; GameObject spawnOnTrigger = itemData.m_shared.m_attack.m_spawnOnTrigger; obj.Spawn_On_Trigger = ((spawnOnTrigger != null) ? ((Object)spawnOnTrigger).name : null); obj.cant_Use_InDungeon = itemData.m_shared.m_attack.m_cantUseInDungeon; obj.Requires_Reload = itemData.m_shared.m_attack.m_requiresReload; obj.Reload_Animation = itemData.m_shared.m_attack.m_reloadAnimation; obj.ReloadTime = itemData.m_shared.m_attack.m_reloadTime; obj.ReloadTimeMultiplier = 1f; obj.Reload_Stamina_Drain = itemData.m_shared.m_attack.m_reloadStaminaDrain; obj.Reload_Eitr_Drain = itemData.m_shared.m_attack.m_reloadEitrDrain; obj.Bow_Draw = itemData.m_shared.m_attack.m_bowDraw; obj.Bow_Duration_Min = itemData.m_shared.m_attack.m_drawDurationMin; obj.Bow_Stamina_Drain = itemData.m_shared.m_attack.m_drawStaminaDrain; obj.Bow_Animation_State = itemData.m_shared.m_attack.m_drawAnimationState; obj.Attack_Angle = itemData.m_shared.m_attack.m_attackAngle; obj.Attack_Ray_Width = itemData.m_shared.m_attack.m_attackRayWidth; obj.Lower_Dmg_Per_Hit = itemData.m_shared.m_attack.m_lowerDamagePerHit; obj.Hit_Through_Walls = itemData.m_shared.m_attack.m_hitThroughWalls; obj.Multi_Hit = itemData.m_shared.m_attack.m_multiHit; obj.Pickaxe_Special = itemData.m_shared.m_attack.m_pickaxeSpecial; obj.Last_Chain_Dmg_Multiplier = itemData.m_shared.m_attack.m_lastChainDamageMultiplier; obj.Reset_Chain_If_hit = itemData.m_shared.m_attack.m_resetChainIfHit; GameObject spawnOnHit = itemData.m_shared.m_attack.m_spawnOnHit; obj.SpawnOnHit = ((spawnOnHit != null) ? ((Object)spawnOnHit).name : null); obj.SpawnOnHit_Chance = itemData.m_shared.m_attack.m_spawnOnHitChance; obj.Raise_Skill_Amount = itemData.m_shared.m_attack.m_raiseSkillAmount; obj.Skill_Hit_Type = itemData.m_shared.m_attack.m_skillHitType; obj.Special_Hit_Skill = itemData.m_shared.m_attack.m_specialHitSkill; obj.Special_Hit_Type = itemData.m_shared.m_attack.m_specialHitType; GameObject attackProjectile = itemData.m_shared.m_attack.m_attackProjectile; obj.Attack_Projectile = ((attackProjectile != null) ? ((Object)attackProjectile).name : null); obj.Projectile_Vel = itemData.m_shared.m_attack.m_projectileVel; obj.Projectile_Accuracy = itemData.m_shared.m_attack.m_projectileAccuracy; obj.Projectile_Accuracy_Min = itemData.m_shared.m_attack.m_projectileAccuracyMin; obj.Projectiles = itemData.m_shared.m_attack.m_projectiles; obj.Skill_Accuracy = itemData.m_shared.m_attack.m_skillAccuracy; obj.Launch_Angle = itemData.m_shared.m_attack.m_launchAngle; obj.Projectile_Burst = itemData.m_shared.m_attack.m_projectileBursts; obj.Burst_Interval = itemData.m_shared.m_attack.m_burstInterval; obj.Destroy_Previous_Projectile = itemData.m_shared.m_attack.m_destroyPreviousProjectile; obj.PerBurst_Resource_usage = itemData.m_shared.m_attack.m_perBurstResourceUsage; obj.Looping_Attack = itemData.m_shared.m_attack.m_loopingAttack; obj.Consume_Item = itemData.m_shared.m_attack.m_consumeItem; obj.AEffectsPLUS = aEffectsPLUS; AttackArm primary_Attack = obj; AttackArm obj2 = new AttackArm { AttackType = itemData.m_shared.m_secondaryAttack.m_attackType, Attack_Animation = itemData.m_shared.m_secondaryAttack.m_attackAnimation, Attack_Random_Animation = itemData.m_shared.m_secondaryAttack.m_attackRandomAnimations, Chain_Attacks = itemData.m_shared.m_secondaryAttack.m_attackChainLevels, Hit_Terrain = itemData.m_shared.m_secondaryAttack.m_hitTerrain, Hit_Friendly = itemData.m_shared.m_secondaryAttack.m_hitFriendly, is_HomeItem = itemData.m_shared.m_secondaryAttack.m_isHomeItem, Custom_AttackSpeed = 1f, m_attackStamina = itemData.m_shared.m_secondaryAttack.m_attackStamina, m_attackAdrenaline = itemData.m_shared.m_secondaryAttack.m_attackAdrenaline, m_attackUseAdrenaline = itemData.m_shared.m_secondaryAttack.m_attackUseAdrenaline, m_eitrCost = itemData.m_shared.m_secondaryAttack.m_attackEitr, AttackHealthCost = itemData.m_shared.m_secondaryAttack.m_attackHealth, m_attackHealthPercentage = itemData.m_shared.m_secondaryAttack.m_attackHealthPercentage, attack_Health_Low_BlockUsage = itemData.m_shared.m_secondaryAttack.m_attackHealthLowBlockUse, Attack_Start_Noise = itemData.m_shared.m_secondaryAttack.m_attackStartNoise, Attack_Hit_Noise = itemData.m_shared.m_secondaryAttack.m_attackHitNoise, Dmg_Multiplier_Per_Missing_Health = itemData.m_shared.m_secondaryAttack.m_damageMultiplierPerMissingHP, Damage_Multiplier_By_Health_Deficit_Percent = itemData.m_shared.m_secondaryAttack.m_damageMultiplierByTotalHealthMissing, Stamina_Return_Per_Missing_HP = itemData.m_shared.m_secondaryAttack.m_staminaReturnPerMissingHP, SelfDamage = itemData.m_shared.m_secondaryAttack.m_selfDamage, Attack_Kills_Self = itemData.m_shared.m_secondaryAttack.m_attackKillsSelf, SpeedFactor = itemData.m_shared.m_secondaryAttack.m_speedFactor, DmgMultiplier = itemData.m_shared.m_secondaryAttack.m_damageMultiplier, ForceMultiplier = itemData.m_shared.m_secondaryAttack.m_forceMultiplier, StaggerMultiplier = itemData.m_shared.m_secondaryAttack.m_staggerMultiplier, RecoilMultiplier = itemData.m_shared.m_secondaryAttack.m_recoilPushback, AttackRange = itemData.m_shared.m_secondaryAttack.m_attackRange, AttackHeight = itemData.m_shared.m_secondaryAttack.m_attackHeight }; GameObject spawnOnTrigger2 = itemData.m_shared.m_secondaryAttack.m_spawnOnTrigger; obj2.Spawn_On_Trigger = ((spawnOnTrigger2 != null) ? ((Object)spawnOnTrigger2).name : null); obj2.cant_Use_InDungeon = itemData.m_shared.m_secondaryAttack.m_cantUseInDungeon; obj2.Requires_Reload = itemData.m_shared.m_secondaryAttack.m_requiresReload; obj2.Reload_Animation = itemData.m_shared.m_secondaryAttack.m_reloadAnimation; obj2.ReloadTimeMultiplier = 1f; obj2.Reload_Stamina_Drain = itemData.m_shared.m_secondaryAttack.m_reloadStaminaDrain; obj2.Bow_Draw = itemData.m_shared.m_secondaryAttack.m_bowDraw; obj2.Bow_Duration_Min = itemData.m_shared.m_secondaryAttack.m_drawDurationMin; obj2.Bow_Stamina_Drain = itemData.m_shared.m_secondaryAttack.m_drawStaminaDrain; obj2.Bow_Animation_State = itemData.m_shared.m_secondaryAttack.m_drawAnimationState; obj2.Attack_Angle = itemData.m_shared.m_secondaryAttack.m_attackAngle; obj2.Attack_Ray_Width = itemData.m_shared.m_secondaryAttack.m_attackRayWidth; obj2.Lower_Dmg_Per_Hit = itemData.m_shared.m_secondaryAttack.m_lowerDamagePerHit; obj2.Hit_Through_Walls = itemData.m_shared.m_secondaryAttack.m_hitThroughWalls; obj2.Multi_Hit = itemData.m_shared.m_secondaryAttack.m_multiHit; obj2.Pickaxe_Special = itemData.m_shared.m_secondaryAttack.m_pickaxeSpecial; obj2.Last_Chain_Dmg_Multiplier = itemData.m_shared.m_secondaryAttack.m_lastChainDamageMultiplier; obj2.Reset_Chain_If_hit = itemData.m_shared.m_secondaryAttack.m_resetChainIfHit; GameObject spawnOnHit2 = itemData.m_shared.m_secondaryAttack.m_spawnOnHit; obj2.SpawnOnHit = ((spawnOnHit2 != null) ? ((Object)spawnOnHit2).name : null); obj2.SpawnOnHit_Chance = itemData.m_shared.m_secondaryAttack.m_spawnOnHitChance; obj2.Raise_Skill_Amount = itemData.m_shared.m_secondaryAttack.m_raiseSkillAmount; obj2.Skill_Hit_Type = itemData.m_shared.m_secondaryAttack.m_skillHitType; obj2.Special_Hit_Skill = itemData.m_shared.m_secondaryAttack.m_specialHitSkill; obj2.Special_Hit_Type = itemData.m_shared.m_secondaryAttack.m_specialHitType; GameObject attackProjectile2 = itemData.m_shared.m_secondaryAttack.m_attackProjectile; obj2.Attack_Projectile = ((attackProjectile2 != null) ? ((Object)attackProjectile2).name : null); obj2.Projectile_Vel = itemData.m_shared.m_secondaryAttack.m_projectileVel; obj2.Projectile_Accuracy = itemData.m_shared.m_secondaryAttack.m_projectileAccuracy; obj2.Projectile_Accuracy_Min = itemData.m_shared.m_secondaryAttack.m_projectileAccuracyMin; obj2.Projectiles = itemData.m_shared.m_secondaryAttack.m_projectiles; obj2.Skill_Accuracy = itemData.m_shared.m_secondaryAttack.m_skillAccuracy; obj2.Launch_Angle = itemData.m_shared.m_secondaryAttack.m_launchAngle; obj2.Projectile_Burst = itemData.m_shared.m_secondaryAttack.m_projectileBursts; obj2.Burst_Interval = itemData.m_shared.m_secondaryAttack.m_burstInterval; obj2.Destroy_Previous_Projectile = itemData.m_shared.m_secondaryAttack.m_destroyPreviousProjectile; obj2.PerBurst_Resource_usage = itemData.m_shared.m_secondaryAttack.m_perBurstResourceUsage; obj2.Looping_Attack = itemData.m_shared.m_secondaryAttack.m_loopingAttack; obj2.Consume_Item = itemData.m_shared.m_secondaryAttack.m_consumeItem; obj2.AEffectsPLUS = aEffectsPLUS2; AttackArm secondary_Attack = obj2; wItemData.Primary_Attack = primary_Attack; wItemData.Secondary_Attack = secondary_Attack; } if (itemData.m_shared.m_armor != 0f) { WMRecipeCust.Dbgl("Item " + ((Object)go.GetComponent()).name + " armor "); ArmorData armor = new ArmorData { armor = itemData.m_shared.m_armor, armorPerLevel = itemData.m_shared.m_armorPerLevel }; wItemData.Armor = armor; } if (itemData.m_shared.m_food != 0f) { WMRecipeCust.Dbgl("Item " + ((Object)go.GetComponent()).name + " food "); FoodData foodData = new FoodData { m_foodHealth = itemData.m_shared.m_food, m_foodBurnTime = itemData.m_shared.m_foodBurnTime, m_foodRegen = itemData.m_shared.m_foodRegen, m_foodStamina = itemData.m_shared.m_foodStamina, m_FoodEitr = itemData.m_shared.m_foodEitr, eatAnimationTime = itemData.m_shared.m_foodEatAnimTime, isDrink = itemData.m_shared.m_isDrink }; Feast val2 = default(Feast); if (go.TryGetComponent(ref val2)) { WMRecipeCust.Dbgl(" Feast Found - Starting complicated fixing scheme"); foodData.feastStacks = val2.m_eatStacks; SharedData shared = tod.GetItemPrefab(((Object)go).name + "_Material").GetComponent().m_itemData.m_shared; wItemData.m_description = shared.m_description; wItemData.m_maxStackSize = shared.m_maxStackSize; wItemData.m_weight = shared.m_weight; } wItemData.FoodStats = foodData; } if (itemData.m_shared.m_maxAdrenaline != 0f) { AdrenalineData obj3 = new AdrenalineData { maxAdrenaline = itemData.m_shared.m_maxAdrenaline }; StatusEffect fullAdrenalineSE = itemData.m_shared.m_fullAdrenalineSE; obj3.fullAdrenalineSE = ((fullAdrenalineSE != null) ? ((Object)fullAdrenalineSE).name : null); obj3.blockAdrenaline = itemData.m_shared.m_blockAdrenaline; obj3.perfectBlockAdrenaline = itemData.m_shared.m_perfectBlockAdrenaline; AdrenalineData adrenalineStats = obj3; wItemData.AdrenalineStats = adrenalineStats; } if (itemData.m_shared.m_blockPower != 0f) { ShieldData obj4 = new ShieldData { m_blockPower = itemData.m_shared.m_blockPower, m_blockPowerPerLevel = itemData.m_shared.m_blockPowerPerLevel, m_timedBlockBonus = itemData.m_shared.m_timedBlockBonus, m_deflectionForce = itemData.m_shared.m_deflectionForce, m_deflectionForcePerLevel = itemData.m_shared.m_deflectionForcePerLevel, m_perfectBlockStaminaRegen = itemData.m_shared.m_perfectBlockStaminaRegen }; StatusEffect perfectBlockStatusEffect = itemData.m_shared.m_perfectBlockStatusEffect; obj4.m_perfectBlockStatusEffect = ((perfectBlockStatusEffect != null) ? ((Object)perfectBlockStatusEffect).name : null); obj4.m_buildBlockCharges = itemData.m_shared.m_buildBlockCharges; obj4.m_maxBlockCharges = itemData.m_shared.m_maxBlockCharges; obj4.m_blockChargeDecayTime = itemData.m_shared.m_blockChargeDecayTime; ShieldData shieldStats = obj4; wItemData.ShieldStats = shieldStats; } if ((Object)(object)itemData.m_shared.m_attackStatusEffect != (Object)null) { StatusEffect attackStatusEffect = itemData.m_shared.m_attackStatusEffect; wItemData.Attack_status_effect = ((attackStatusEffect != null) ? ((Object)attackStatusEffect).name : null); } wItemData.Attack_status_effect_chance = itemData.m_shared.m_attackStatusEffectChance; if ((Object)(object)itemData.m_shared.m_spawnOnHit != (Object)null) { GameObject spawnOnHit3 = itemData.m_shared.m_spawnOnHit; wItemData.spawn_on_hit = ((spawnOnHit3 != null) ? ((Object)spawnOnHit3).name : null); } if ((Object)(object)itemData.m_shared.m_spawnOnHitTerrain != (Object)null) { GameObject spawnOnHitTerrain = itemData.m_shared.m_spawnOnHitTerrain; wItemData.spawn_on_terrain_hit = ((spawnOnHitTerrain != null) ? ((Object)spawnOnHitTerrain).name : null); } StatusEffect consumeStatusEffect = itemData.m_shared.m_consumeStatusEffect; wItemData.ConsumableStatusEffect = ((consumeStatusEffect != null) ? ((Object)consumeStatusEffect).name : null) ?? null; ItemDrop appendToolTip = itemData.m_shared.m_appendToolTip; wItemData.AppendToolTip = ((appendToolTip == null) ? null : ((Object)appendToolTip).name?.ToString()) ?? null; wItemData.snapshotOnMaterialChange = true; return wItemData; } internal CreatureData GetCreature(string name) { GameObject[] array = Resources.FindObjectsOfTypeAll(); CreatureData creatureData = new CreatureData(); GameObject[] array2 = array; foreach (GameObject val in array2) { if (((Object)val).name == name) { creatureData.name = ((Object)val).name; creatureData.mob_display_name = ((Character)val.GetComponent()).m_name; return creatureData; } } return null; } internal bool GetAllCreature() { Humanoid[] array = Resources.FindObjectsOfTypeAll(); ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); Humanoid[] array2 = array; foreach (Humanoid val in array2) { CreatureData creatureData = new CreatureData(); string name = ((Object)val).name; creatureData.name = ((Object)val).name; creatureData.mob_display_name = ((Character)((Component)val).GetComponent()).m_name; File.WriteAllText(Path.Combine(WMRecipeCust.assetPathBulkYMLCreatures, "Creature_" + name + ".yml"), serializer.Serialize(creatureData)); } return true; } internal PickableData GetPickable(string name, Pickable[] array) { //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) PickableData pickableData = new PickableData(); try { Destructible val2 = default(Destructible); foreach (Pickable val in array) { if (!(((Object)val).name == name)) { continue; } pickableData.name = ((Object)val).name; pickableData.itemPrefab = ((Object)val.m_itemPrefab).name; pickableData.amount = val.m_amount; pickableData.overrideName = val.m_overrideName; pickableData.respawnTimer = val.m_respawnTimeMinutes; pickableData.spawnOffset = val.m_spawnOffset; if (Object.op_Implicit((Object)(object)val.m_hideWhenPicked)) { pickableData.hiddenChildWhenPicked = ((Object)val.m_hideWhenPicked).name; } if (((Component)val).TryGetComponent(ref val2)) { pickableData.ifHasHealth = val2.m_health; } if (val?.m_extraDrops != null && val != null && val.m_extraDrops.m_drops.Count() > 0) { ExtraDrops extraDrops = new ExtraDrops(); extraDrops.dropChance = val.m_extraDrops.m_dropChance; extraDrops.dropMin = val.m_extraDrops.m_dropMin; extraDrops.dropMax = val.m_extraDrops.m_dropMax; extraDrops.dropOneOfEach = val.m_extraDrops.m_oneOfEach; List list = new List(); foreach (DropData drop in val.m_extraDrops.m_drops) { list.Add(((Object)drop.m_item).name); } extraDrops.drops = list; pickableData.extraDrops = extraDrops; } return pickableData; } } catch { WMRecipeCust.WLog.LogWarning((object)("An Error happened with " + pickableData.name)); } return null; } internal TreeBaseData GetTreeBase(string name, TreeBase[] array) { TreeBaseData treeBaseData = new TreeBaseData(); foreach (TreeBase val in array) { if (((Object)val).name == name) { treeBaseData.name = ((Object)val).name; treeBaseData.treeHealth = val.m_health; treeBaseData.minToolTier = val.m_minToolTier; return treeBaseData; } } return null; } internal bool GetAllPickables() { //IL_023c: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0245: Unknown result type (might be due to invalid IL or missing references) _ = ObjectDB.instance; ISerializer serializer = new SerializerBuilder().WithNewLine("\n").Build(); Pickable[] array = Resources.FindObjectsOfTypeAll(); try { Pickable[] array2 = array; Destructible val2 = default(Destructible); foreach (Pickable val in array2) { if (((Object)val).name.Contains("Clone")) { continue; } PickableData pickableData = new PickableData(); pickableData.name = ((val != null) ? ((Object)val).name : null); WMRecipeCust.WLog.LogInfo((object)("Saving " + ((val != null) ? ((Object)val).name : null))); object itemPrefab; if (val == null) { itemPrefab = null; } else { GameObject itemPrefab2 = val.m_itemPrefab; itemPrefab = ((itemPrefab2 != null) ? ((Object)itemPrefab2).name : null); } pickableData.itemPrefab = (string)itemPrefab; pickableData.amount = val?.m_amount; pickableData.overrideName = val?.m_overrideName; pickableData.respawnTimer = val?.m_respawnTimeMinutes; pickableData.spawnOffset = val?.m_spawnOffset; if (Object.op_Implicit((Object)(object)val?.m_hideWhenPicked)) { object hiddenChildWhenPicked; if (val == null) { hiddenChildWhenPicked = null; } else { GameObject hideWhenPicked = val.m_hideWhenPicked; hiddenChildWhenPicked = ((hideWhenPicked != null) ? ((Object)hideWhenPicked).name : null); } pickableData.hiddenChildWhenPicked = (string)hiddenChildWhenPicked; } if (((Component)val).TryGetComponent(ref val2)) { pickableData.ifHasHealth = val2?.m_health; } if (val?.m_extraDrops != null && val != null && val.m_extraDrops.m_drops.Count() > 0) { ExtraDrops extraDrops = new ExtraDrops(); extraDrops.dropChance = val.m_extraDrops.m_dropChance; extraDrops.dropMin = val.m_extraDrops.m_dropMin; extraDrops.dropMax = val.m_extraDrops.m_dropMax; extraDrops.dropOneOfEach = val.m_extraDrops.m_oneOfEach; List list = new List(); foreach (DropData drop in val.m_extraDrops.m_drops) { list.Add(((Object)drop.m_item).name); } extraDrops.drops = list; pickableData.extraDrops = extraDrops; } File.WriteAllText(Path.Combine(WMRecipeCust.assetPathBulkYMLPickables, "Pickable_" + pickableData.name + ".yml"), serializer.Serialize(pickableData)); } TreeBase[] array3 = Resources.FindObjectsOfTypeAll(); foreach (TreeBase val3 in array3) { if (!((Object)val3).name.Contains("Clone")) { TreeBaseData treeBaseData = new TreeBaseData(); WMRecipeCust.WLog.LogInfo((object)("Saving " + ((Object)val3).name)); treeBaseData.name = ((Object)val3).name; treeBaseData.treeHealth = val3.m_health; treeBaseData.minToolTier = val3.m_minToolTier; File.WriteAllText(Path.Combine(WMRecipeCust.assetPathBulkYMLPickables, "Treebase_" + treeBaseData.name + ".yml"), serializer.Serialize(treeBaseData)); } } } catch (Exception ex) { WMRecipeCust.WLog.LogWarning((object)("An Error happened with Getallpickables " + ex)); } return true; } } } namespace wackydatabase.Datas { [Serializable] [Nullable(0)] [CanBeNull] [NullableContext(1)] public class CreatureData { public string name; public string mob_display_name; [Nullable(2)] public string clone_creature; [Nullable(2)] public string creature_replacer; } [Nullable(0)] [NullableContext(1)] public class DataHelpers { public static CraftingStation GetCraftingStation(string name) { if (name == "" || name == null) { return null; } foreach (Recipe recipe in ObjectDB.instance.m_recipes) { if (recipe?.m_craftingStation?.m_name == name) { return recipe.m_craftingStation; } } foreach (GameObject piece in GetPieces()) { if (!(piece.GetComponent()?.m_craftingStation?.m_name == name)) { Piece component = piece.GetComponent(); object obj; if (component == null) { obj = null; } else { CraftingStation craftingStation = component.m_craftingStation; obj = ((craftingStation != null) ? ((Object)craftingStation).name : null); } if (!((string?)obj == name)) { continue; } } return piece.GetComponent().m_craftingStation; } try { GameObject moddedPieces = GetModdedPieces(name); if (moddedPieces.GetComponent()?.m_craftingStation?.m_name == name) { return moddedPieces.GetComponent().m_craftingStation; } } catch { } foreach (CraftingStation newCraftingStation in WMRecipeCust.NewCraftingStations) { if (((Object)newCraftingStation).name == name) { return newCraftingStation; } if ("$" + ((Object)newCraftingStation).name == name) { return newCraftingStation; } } return null; } public static List GetPieces(ObjectDB Instant) { List list = new List(); if (!Object.op_Implicit((Object)(object)Instant)) { return list; } GameObject itemPrefab = Instant.GetItemPrefab("Hammer"); ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent() : null); if (Object.op_Implicit((Object)(object)val)) { list.AddRange(Traverse.Create((object)val.m_itemData.m_shared.m_buildPieces).Field("m_pieces").GetValue>()); } GameObject itemPrefab2 = Instant.GetItemPrefab("Hoe"); ItemDrop val2 = ((itemPrefab2 != null) ? itemPrefab2.GetComponent() : null); if (Object.op_Implicit((Object)(object)val2)) { list.AddRange(Traverse.Create((object)val2.m_itemData.m_shared.m_buildPieces).Field("m_pieces").GetValue>()); } return list; } public static List GetPieces() { List list = new List(); if (!Object.op_Implicit((Object)(object)ObjectDB.instance)) { return list; } GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("Hammer"); ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent() : null); if (Object.op_Implicit((Object)(object)val)) { list.AddRange(Traverse.Create((object)val.m_itemData.m_shared.m_buildPieces).Field("m_pieces").GetValue>()); } GameObject itemPrefab2 = ObjectDB.instance.GetItemPrefab("Hoe"); ItemDrop val2 = ((itemPrefab2 != null) ? itemPrefab2.GetComponent() : null); if (Object.op_Implicit((Object)(object)val2)) { list.AddRange(Traverse.Create((object)val2.m_itemData.m_shared.m_buildPieces).Field("m_pieces").GetValue>()); } return list; } public static GameObject GetModdedPieces(string name) { WMRecipeCust.selectedPiecehammer = null; GameObject val = null; if (WMRecipeCust.MaybePieceStations == null || WMRecipeCust.MaybePieceStations.Count() == 0) { return null; } PieceTable[] maybePieceStations = WMRecipeCust.MaybePieceStations; foreach (PieceTable val2 in maybePieceStations) { val = val2.m_pieces.Find([NullableContext(0)] (GameObject g) => Utils.GetPrefabName(g) == name); if ((Object)(object)val != (Object)null) { WMRecipeCust.selectedPiecehammer = val2; return val; } } return val; } public static GameObject FindPieceObjectName(string name) { GameObject val = GetPieces().Find((GameObject g) => Utils.GetPrefabName(g) == name); if ((Object)(object)val == (Object)null) { val = GetModdedPieces(name); if ((Object)(object)val == (Object)null) { val = CheckforSpecialObjects(name); } } return val; } public static void GetPieceStations() { WMRecipeCust.MaybePieceStations = Resources.FindObjectsOfTypeAll(); } public static void GetPiecesatStart() { } internal static GameObject CheckforSpecialObjects(string name) { GameObject val = null; string text = ""; int num = 0; if (name == null) { goto IL_0221; } int length = name.Length; if (length <= 11) { if (length != 3) { if (length != 7) { if (length != 11) { goto IL_0221; } char c = name[0]; if (c != 'S') { if (c != 's' || !(name == "stone_floor")) { goto IL_0221; } text = "stone_floor"; } else { if (!(name == "SpearBronze")) { goto IL_0221; } text = "SpearBronze"; } } else { if (!(name == "AxeIron")) { goto IL_0221; } text = "AxeIron"; } } else { char c = name[0]; if (c != 'B') { if (c != 'b' || !(name == "bow")) { goto IL_0221; } text = "Bow"; } else { if (!(name == "Bow")) { goto IL_0221; } text = "Bow"; } } } else if (length != 12) { if (length != 16) { if (length != 19 || !(name == "ShieldBronzeBuckler")) { goto IL_0221; } text = "ShieldBronzeBuckler"; } else { if (!(name == "CrossbowArbalest")) { goto IL_0221; } int num2 = 0; foreach (GameObject item in ObjectDB.instance.m_items) { if (((Object)item.GetComponent()).name == "CrossbowArbalest") { num2++; val = item; } } WMRecipeCust.Dbgl("Found " + num2 + " For CrossbowArbalest in DB"); text = "CrossbowArbalest"; } } else { char c = name[0]; if (c != 'H') { if (c != 'T' || !(name == "TrophyDraugr")) { goto IL_0221; } text = "TrophyDraugr"; num = 255610059; } else { if (!(name == "HelmetBronze")) { goto IL_0221; } text = "HelmetBronze"; } } goto IL_0223; IL_0223: if (text == "") { return null; } try { WMRecipeCust.WLog.LogInfo((object)(" ZnetScene Special Object Search with " + text)); val = ZNetScene.instance.GetPrefab(text); if (num != 0) { val = ZNetScene.instance.GetPrefab(num); if ((Object)(object)val != (Object)null) { WMRecipeCust.WLog.LogInfo((object)("Found Special Object with Hash " + ((Object)val).name + " known issue")); } } } catch { } return val; IL_0221: val = null; goto IL_0223; } public static bool ECheck(string checker) { return string.IsNullOrEmpty(checker); } public static bool ECheck(int checker) { return checker == 0; } public static bool ECheck(float checker) { return checker == 0f; } public static bool ECheck(List strings) { return strings.Count == 0; } public static bool ECheck(bool whatis) { return false; } } [Serializable] [Nullable(0)] [NullableContext(1)] public class DescriptorData { public string Name; public List Renderers = new List(); } [Nullable(0)] [NullableContext(1)] public class MaterialPropertyDescriptor { public string Name; public string Type; public string Value; public string Range; } [Nullable(0)] [NullableContext(1)] public class MaterialDescriptor { public string Name; public string Shader; public List MaterialProperties = new List(); } [NullableContext(1)] [Nullable(0)] public class RendererDescriptor { public string Name; public List Materials = new List(); } [Serializable] [Nullable(0)] [NullableContext(2)] [CanBeNull] public class WItemData { [Nullable(1)] public string name; public float m_weight; public string m_name; public string m_description; public string clonePrefabName; public string mockName; public string customIcon; public string material; [Nullable(new byte[] { 2, 1 })] public string[] materials; public CustomVisual customVisual; public string snapshotRotation; public bool? snapshotOnMaterialChange; public string sizeMultiplier; public float? scale_weight_by_quality; public AttackArm Primary_Attack; public AttackArm Secondary_Attack; public WDamages Damage; public WDamages Damage_Per_Level; public ArmorData Armor; public FoodData FoodStats; public StatMods Moddifiers; public SE_Equip SE_Equip; public SE_SET_Equip SE_SET_Equip; public ShieldData ShieldStats; public AdrenalineData AdrenalineStats; public int? m_maxStackSize; public bool? m_canBeReparied; public bool? m_destroyBroken; public bool? m_dodgeable; public bool? blockable; public string Attack_status_effect; public float? Attack_status_effect_chance; public string spawn_on_hit; public string spawn_on_terrain_hit; public bool? m_questItem; public bool? m_teleportable; public float? m_backstabbonus; public float? m_knockback; public bool? m_useDurability; public float? m_useDurabilityDrain; public float? m_durabilityDrain; public float? m_maxDurability; public float? m_durabilityPerLevel; public float? m_equipDuration; public ItemType? Attach_Override; public SkillType? m_skillType; public AnimationState? m_animationState; public ItemType? m_itemType; public int? m_toolTier; public int? m_maxQuality; public int? m_value; public string ConsumableStatusEffect; public string AppendToolTip; [Nullable(new byte[] { 2, 1 })] public List damageModifiers = new List(); public GEffects GEffects; public GEffectsPLUS GEffectsPLUS; } [Serializable] [Nullable(0)] [NullableContext(2)] public class AttackArm { public AttackType? AttackType; public string Attack_Animation; public int? Attack_Random_Animation; public int? Chain_Attacks; public bool? Hit_Terrain; public bool? Hit_Friendly; public bool? is_HomeItem; public float? Custom_AttackSpeed; public float? m_attackStamina; public float? m_attackAdrenaline; public float? m_attackUseAdrenaline; public float? m_eitrCost; public float? AttackHealthCost; public float? m_attackHealthPercentage; public bool? attack_Health_Low_BlockUsage; public float? SpeedFactor; public float? Attack_Start_Noise; public float? Attack_Hit_Noise; public float? Dmg_Multiplier_Per_Missing_Health; public float? Damage_Multiplier_By_Health_Deficit_Percent; public float? Stamina_Return_Per_Missing_HP; public float? DmgMultiplier; public float? ForceMultiplier; public float? StaggerMultiplier; public float? RecoilMultiplier; public int? SelfDamage; public bool? Attack_Kills_Self; public float? AttackRange; public float? AttackHeight; public string Spawn_On_Trigger; public bool? cant_Use_InDungeon; public bool? Requires_Reload; public string Reload_Animation; public float? ReloadTime; public float? ReloadTimeMultiplier; public float? Reload_Stamina_Drain; public float? Reload_Eitr_Drain; public bool? Bow_Draw; public float? Bow_Duration_Min; public float? Bow_Stamina_Drain; public string Bow_Animation_State; public float? Attack_Angle; public float? Attack_Ray_Width; public bool? Lower_Dmg_Per_Hit; public bool? Hit_Through_Walls; public bool? Multi_Hit; public bool? Pickaxe_Special; public float? Last_Chain_Dmg_Multiplier; public DestructibleType? Reset_Chain_If_hit; public string SpawnOnHit; public float? SpawnOnHit_Chance; public string Attack_status_effect; public float? Attack_status_effect_chance; public float? Raise_Skill_Amount; public DestructibleType? Skill_Hit_Type; public SkillType? Special_Hit_Skill; public DestructibleType? Special_Hit_Type; public string Attack_Projectile; public float? Projectile_Vel; public float? Projectile_Accuraccy; public float? Projectile_Accuracy; public float? Projectile_Accuracy_Min; public int? Projectiles; public bool? Skill_Accuracy; public float? Launch_Angle; public int? Projectile_Burst; public float? Burst_Interval; public bool? Destroy_Previous_Projectile; public bool? PerBurst_Resource_usage; public bool? Looping_Attack; public bool? Consume_Item; public AEffects AEffects; public AEffectsPLUS AEffectsPLUS; } [Serializable] [NullableContext(2)] [Nullable(0)] public class CustomVisual { public string base_mat; public string chest; public string legs; public string realtime; } [Serializable] [Nullable(0)] [NullableContext(2)] public class EffectVerse { public string name; public bool? m_enabled; public int? m_variant; 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; } public class AEffects { [Nullable(new byte[] { 2, 0 })] public string[] Hit_Effects; [Nullable(new byte[] { 2, 0 })] public string[] Hit_Terrain_Effects; [Nullable(new byte[] { 2, 0 })] public string[] Start_Effect; [Nullable(new byte[] { 2, 0 })] public string[] Trigger_Effect; [Nullable(new byte[] { 2, 0 })] public string[] Trail_Effect; [Nullable(new byte[] { 2, 0 })] public string[] Burst_Effect; } public class GEffects { [Nullable(new byte[] { 2, 0 })] public string[] Hit_Effects; [Nullable(new byte[] { 2, 0 })] public string[] Hit_Terrain_Effects; [Nullable(new byte[] { 2, 0 })] public string[] Start_Effect; [Nullable(new byte[] { 2, 0 })] public string[] Hold_Start_Effects; [Nullable(new byte[] { 2, 0 })] public string[] Trigger_Effect; [Nullable(new byte[] { 2, 0 })] public string[] Trail_Effect; } public class AEffectsPLUS { [Nullable(new byte[] { 2, 0 })] public EffectVerse[] Hit_Effects; [Nullable(new byte[] { 2, 0 })] public EffectVerse[] Hit_Terrain_Effects; [Nullable(new byte[] { 2, 0 })] public EffectVerse[] Start_Effect; [Nullable(new byte[] { 2, 0 })] public EffectVerse[] Trigger_Effect; [Nullable(new byte[] { 2, 0 })] public EffectVerse[] Trail_Effect; [Nullable(new byte[] { 2, 0 })] public EffectVerse[] Burst_Effect; } public class GEffectsPLUS { [Nullable(new byte[] { 2, 0 })] public EffectVerse[] Hit_Effects; [Nullable(new byte[] { 2, 0 })] public EffectVerse[] Hit_Terrain_Effects; [Nullable(new byte[] { 2, 0 })] public EffectVerse[] Start_Effect; [Nullable(new byte[] { 2, 0 })] public EffectVerse[] Hold_Start_Effects; [Nullable(new byte[] { 2, 0 })] public EffectVerse[] Trigger_Effect; [Nullable(new byte[] { 2, 0 })] public EffectVerse[] Trail_Effect; } [Serializable] public class FoodData { public int? feastStacks; public float? m_foodHealth; public float? m_foodStamina; public float? m_foodRegen; public float? m_foodBurnTime; public float? m_FoodEitr; public float? eatAnimationTime; public bool? isDrink; } [Serializable] public class StatMods { public float? m_movementModifier; public float? m_EitrRegen; public float? m_homeItemsStaminaModifier; public float? m_heatResistanceModifier; public float? m_jumpStaminaModifier; public float? m_attackStaminaModifier; public float? m_blockStaminaModifier; public float? m_dodgeStaminaModifier; public float? m_swimStaminaModifier; public float? m_sneakStaminaModifier; public float? m_runStaminaModifier; } [Serializable] public class SE_Equip { [Nullable(2)] public string EffectName; } [Serializable] [NullableContext(2)] [Nullable(0)] public class SE_SET_Equip { public string SetName; public int? Size; public string EffectName; } [Serializable] public class ShieldData { public float? m_blockPower; public float? m_blockPowerPerLevel; public float? m_timedBlockBonus; public float? m_deflectionForce; public float? m_deflectionForcePerLevel; public float? m_perfectBlockStaminaRegen; [Nullable(2)] public string m_perfectBlockStatusEffect; public bool? m_buildBlockCharges; public int? m_maxBlockCharges; public float? m_blockChargeDecayTime; } [Serializable] public class AdrenalineData { public float? maxAdrenaline; [Nullable(2)] public string fullAdrenalineSE; public float? blockAdrenaline; public float? perfectBlockAdrenaline; } [Serializable] public class ArmorData { public float? armor; public float? armorPerLevel; } [Serializable] public class WDamages { public float Blunt; public float Chop; public float Damage; public float Fire; public float Frost; public float Lightning; public float Pickaxe; public float Pierce; public float Poison; public float Slash; public float Spirit; } [Serializable] public class WIngredients { public string id; public int amount; public int amountPerLevel; } [Serializable] [Nullable(0)] [NullableContext(1)] public class MaterialInstance { public string name; public string original; public bool overwrite; public MaterialData changes = new MaterialData(); } [Serializable] [NullableContext(1)] [Nullable(0)] public class MaterialData { public Dictionary colors = new Dictionary(); public Dictionary floats = new Dictionary(); public Dictionary textures = new Dictionary(); } [Serializable] [NullableContext(2)] [Nullable(0)] [CanBeNull] public class PickableData { [Nullable(1)] public string name; [Nullable(1)] public string itemPrefab; public string cloneOfWhatPickable; public string material; public int? amount; public string size; public string overrideName; public float? respawnTimer; public float? spawnOffset; public float? ifHasHealth; public string hiddenChildWhenPicked; public ExtraDrops extraDrops; } [Serializable] [NullableContext(2)] [Nullable(0)] [CanBeNull] public class TreeBaseData { [Nullable(1)] public string name; public float treeHealth; public string cloneOfWhatTree; public string material; public string size; public int? minToolTier; } [Serializable] [CanBeNull] public class ExtraDrops { [Nullable(1)] public List drops; public int? dropMin; public int? dropMax; public float? dropChance; public bool? dropOneOfEach; } [Serializable] [NullableContext(2)] [Nullable(0)] public class PieceData { [Nullable(1)] public string name; [Nullable(1)] public string piecehammer; public string m_name; public string sizeMultiplier; public string m_description; public string customIcon; public string clonePrefabName; public string material; public string damagedMaterial; public string craftingStation; public string piecehammerCategory; public string categoryOrderBeforePrefab; public int? minStationLevel; public bool? disabled; public bool? adminonly; public ComfortData comfort; public bool? groundPiece; public bool? ground; public bool? waterPiece; public bool? noInWater; public bool? notOnFloor; public bool? onlyinTeleportArea; public bool? allowedInDungeons; public bool? canBeRemoved; public bool? notOnWood; public WearNTearData wearNTearData; public CraftingStationData craftingStationData; public CSExtensionData cSExtensionData; [Nullable(new byte[] { 2, 1 })] public List cSExtensionDataList; public ContainerData contData; public SmelterData smelterData; public CookingStationData cookingStationData; public BeehiveData beehiveData; public FermenterData fermStationData; public SapData sapData; public ObliteratorData incineratorData; public FireplaceData fireplaceData; public TeleportWorldData teleportWorldData; public PlantData plantData; public ShipData shipData; public ShieldGenData shieldGenData; public BatteringRamData batteringRamData; [Nullable(new byte[] { 2, 1 })] public List build = new List(); } public class ComfortData { public int? comfort; public ComfortGroup? comfortGroup; [Nullable(2)] public string comfortObjectName; } public class WearNTearData { public float? health; public DamageModifiers damageModifiers; public bool? noRoofWear; public bool? noSupportWear; public bool? supports; public bool? triggerPrivateArea; public MaterialType? materialType; public bool? burnable; } public class ShipData { public bool? ashlandProof; } [Nullable(0)] [NullableContext(2)] public class ShieldGenData { public string name; public string nameAdd; public int? maxFuel; public int? spawnWithFuel; public float? fuelPerDamage; public float? minRadius; public float? maxRadius; public bool? offWhenOutofFuel; public bool? attack; public float? attackChargeTime; public bool? attackPlayers; [Nullable(new byte[] { 2, 1 })] public List fuel; } public class BatteringRamData { public float? chargeTime; public int? maxFuel; } public class CraftingStationData { [Nullable(2)] public string cStationCustomIcon; public float? discoveryRange; public float? buildRange; public bool? craftRequiresRoof; public bool? craftRequiresFire; public bool? showBasicRecipes; public float? useDistance; public int? useAnimation; } public class CSExtensionData { [Nullable(2)] public string MainCraftingStationName; public float? maxStationDistance; public bool? continousConnection; public bool? stack; } public class ContainerData { public int? Width; public int? Height; public bool? CheckWard; public bool? AutoDestoryIfEmpty; } [NullableContext(2)] [Nullable(0)] public class SmelterData { public string addOreTooltip; public string emptyOreTooltip; public fuelItemData fuelItem; public int? maxOre; public int? maxFuel; public int? fuelPerProduct; public float? secPerProduct; public bool? spawnStack; public bool? requiresRoof; public float? addOreAnimationLength; [Nullable(new byte[] { 2, 1 })] public List smelterConversion; } [Nullable(0)] [NullableContext(2)] public class CookingStationData { public string addItemTooltip; public string overcookedItem; public string fuelItem; public bool? requireFire; public int? maxFuel; public int? secPerFuel; [Nullable(new byte[] { 2, 1 })] public List cookConversion; } public class FermenterData { public float? fermDuration; [Nullable(new byte[] { 2, 1 })] public List fermConversion; } [Nullable(0)] [NullableContext(2)] public class SapData { public float? secPerUnit; public int? maxLevel; public string producedItem; public string connectedToWhat; public string extractText; public string drainingText; public string drainingSlowText; public string notConnectedText; public string fullText; } [Nullable(0)] [NullableContext(2)] public class BeehiveData { public bool? effectOnlyInDaylight; public float? maxCover; public Biome? biomes; public float? secPerUnit; public int? maxAmount; public string dropItem; [Nullable(new byte[] { 2, 1 })] public string[] effects; [Nullable(new byte[] { 2, 1 })] public EffectVerse[] effectsPLUS; public string extractText; public string checkText; public string areaText; public string freespaceText; public string sleepText; public string happyText; } public class ObliteratorData { [Nullable(2)] public string defaultDrop; public int? defaultCostPerDrop; [Nullable(new byte[] { 2, 1 })] public List incineratorConversion; } public class fuelItemData { [Nullable(2)] public string name; } [NullableContext(2)] [Nullable(0)] public class SmelterConversionList { public string FromName; public string ToName; public bool? Remove = false; } [NullableContext(2)] [Nullable(0)] public class CookStationConversionList { public string FromName; public string ToName; public float? CookTime; public bool? Remove = false; } [NullableContext(2)] [Nullable(0)] public class FermenterConversionList { public string FromName; public string ToName; public int? Amount; public bool? Remove = false; } public class ObliteratorList { [Nullable(2)] public string Result; public int? ResultAmount; public int? Priority; public bool? RequireOnlyOne; [Nullable(new byte[] { 2, 1 })] public List Requirements; } public class FireplaceData { public float? StartFuel; public float? MaxFuel; public float? SecPerFuel; public bool? InfiniteFuel; [Nullable(2)] public string FuelType; public float? IgniteInterval; public float? IgniteChance; public int? IgniteSpread; } [NullableContext(2)] [Nullable(0)] public class PlantData { public string m_name; public float? GrowTime; public float? MaxGrowTime; public string GrowPrefab; public float? MinSize; public float? MaxSize; public float? GrowRadius; public float? GrowRadiusVines; public bool? CultivatedGround; public bool? DestroyIfCantGrow; public bool? TolerateHeat; public bool? TolerateCold; public Biome? Biomes; } public class ObRequirementList { [Nullable(2)] public string Name; public int? Amount; } public class TeleportWorldData { public bool? AllowAllItems; } [Serializable] [CanBeNull] [NullableContext(2)] [Nullable(0)] public class RecipeData { public string name; public string clonePrefabName; public string craftingStation; public int? minStationLevel; public int? maxStationLevelCap; public string repairStation; public int? amount; public bool? disabled; public bool? disabledUpgrade; public bool? requireOnlyOneIngredient; [Nullable(new byte[] { 2, 1 })] public List upgrade_reqs = new List(); [Nullable(new byte[] { 2, 1 })] public List reqs = new List(); } [Serializable] [NullableContext(2)] [Nullable(0)] [CanBeNull] public class StatusData { public string Name; public string Status_m_name; public string Category; public string IconName; public string ClonedSE; public string CustomIcon; public bool? FlashIcon; public bool? CooldownIcon; public string Tooltip; public StatusAttribute? Attributes; public MessageType? StartMessageLoc; public string StartMessage; public MessageType? StopMessageLoc; public string StopMessage; public MessageType? RepeatMessageLoc; public string RepeatMessage; public float? RepeatInterval; public float? TimeToLive; public string EndingStatusEffect; [Nullable(1)] public string[] StartEffect_; [Nullable(1)] public string[] StopEffect_; [Nullable(1)] public EffectVerse[] StartEffect_PLUS; [Nullable(1)] public EffectVerse[] StopEffect_PLUS; public float? Cooldown; public string ActivationAnimation; public SEdata SeData; [Nullable(1)] public SEShield SeShield; [Nullable(1)] public SEPoison SePoison; [Nullable(1)] public SEFrost SeFrost; public float? AddHP; public float? AddStamina; public float? AddEitr; } [Serializable] [CanBeNull] public class SEShield { public float? AbsorbDmg; public float? AbsorbDmgWorldLevel; public float? LevelUpSkillFactor; public int? TtlPerItemLevel; public float? AbsorbDmgPerSkill; } [Serializable] [CanBeNull] public class SEPoison { public float? m_damageInterval; public float? m_baseTTL; public float? m_TTLPerDamagePlayer; public float? m_TTLPerDamage; public float? m_TTLPower; } [Serializable] [CanBeNull] public class SEFrost { public float? m_freezeTimeEnemy; public float? m_freezeTimePlayer; public float? m_minSpeedFactor; } [Serializable] [CanBeNull] public class SEdata { public float? m_tickTimer; public float? m_healthOverTimeTimer; public float? m_healthOverTimeTicks; public float? m_healthOverTimeTickHP; public float? m_heatlhUpFront; public float? m_tickInterval; public float? m_healthPerTickMinHealthPercentage; public float? m_healthPerTick; public float? m_healthOverTime; public float? m_healthOverTimeDuration; public float? m_healthOverTimeInterval; public float? m_staminaUpFront; public float? m_staminaOverTime; public float? m_staminaOverTimeDuration; public float? m_staminaDrainPerSec; public float? m_runStaminaDrainModifier; public float? m_jumpStaminaUseModifier; public float? m_attackStaminaUseModifier; public float? m_blockStaminaUseModifier; public float? m_dodgeStaminaUseModifier; public float? m_swimStaminaUseModifier; public float? m_homeItemStaminaUseModifier; public float? m_sneakStaminaUseModifier; public float? m_runStaminaUseModifier; public float? m_blockStaminaUseFlatValue; public float? m_adrenalineUpFront; public float? m_adrenalineModifier; public float? m_staggerModifier; public float? m_staggerTimeBlockBonus; public float? m_eitrUpFront; public float? m_eitrOverTime; public float? m_eitrOverTimeDuration; public float? m_healthRegenMultiplier; public float? m_staminaRegenMultiplier; public float? m_eitrRegenMultiplier; public float? m_armorAdd; public float? m_armorMultiplier; public SkillType? m_raiseSkill; public float? m_raiseSkillModifier; public SkillType? m_skillLevel; public float? m_skillLevelModifier; public SkillType? m_skillLevel2; public float? m_skillLevelModifier2; [Nullable(2)] public List m_mods = new List(); public SkillType? m_modifyAttackSkill; public float? m_damageModifier; public float? m_noiseModifier; public float? m_stealthModifier; public float? m_addMaxCarryWeight; public float? m_speedModifier; public Vector3? m_jumpModifier; public float? m_maxMaxFallSpeed; public float? m_fallDamageModifier; public float? m_windMovementModifier; public DamageTypes? m_percentDamageModifiers { get; set; } } [Serializable] public enum TextureEffect { Screen, Multiply, Overlay, Edge } [Serializable] [NullableContext(1)] [Nullable(0)] public class TextureData { public string Name; public TextureEffect Effect; public List Colors; public TextureData() { Name = ""; Effect = TextureEffect.Screen; Colors = new List(); } } [Serializable] [NullableContext(1)] [Nullable(0)] public class ValheimTime { private const int DAY_LENGTH = 86400; public int Hour { get; } public int Minute { get; } public int Second { get; } public int Day { get; } public ValheimTime(int hour = 0, int minute = 0, int second = 0, int day = -1) { Day = day; Hour = hour; Minute = minute; Second = second; } public string ToDataString() { return Hour + ":" + Minute + ":" + Second + " (" + Day + ")"; } public int ToSeconds() { return (int)new TimeSpan(Hour, Minute, Second).TotalSeconds; } public static float RatioUntilTime(ValheimTime a, ValheimTime b, ValheimTime span) { if (Mathf.Abs(a.ToSeconds() - b.ToSeconds()) < span.ToSeconds()) { float num = Mathf.Abs(a.ToSeconds() - b.ToSeconds()); return 1f - num / (float)span.ToSeconds(); } if (Mathf.Abs(a.ToSeconds() + 86400 - b.ToSeconds()) < span.ToSeconds()) { float num2 = Mathf.Abs(a.ToSeconds() + 86400 - b.ToSeconds()); return 1f - num2 / (float)span.ToSeconds(); } if (Mathf.Abs(a.ToSeconds() - (b.ToSeconds() + 86400)) < span.ToSeconds()) { float num3 = Mathf.Abs(a.ToSeconds() - (b.ToSeconds() + 86400)); return 1f - num3 / (float)span.ToSeconds(); } return 0f; } public static ValheimTime Get() { if (!Object.op_Implicit((Object)(object)EnvMan.instance)) { return new ValheimTime(-1); } float smoothDayFraction = EnvMan.instance.m_smoothDayFraction; int currentDay = EnvMan.instance.GetCurrentDay(); int num = (int)(smoothDayFraction * 24f); int num2 = (int)((smoothDayFraction * 24f - (float)num) * 60f); int second = (int)(((smoothDayFraction * 24f - (float)num) * 60f - (float)num2) * 60f); return new ValheimTime(num, num2, second, currentDay); } } [Nullable(0)] [NullableContext(1)] public class TextureConverter : IYamlTypeConverter { public bool Accepts(Type type) { return type == typeof(Texture2D); } public object ReadYaml(IParser parser, Type type) { //IL_0003: 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) string text = null; FilterMode result = (FilterMode)0; if (parser.TryConsume(out var _)) { MappingEnd event2; while (!parser.TryConsume(out event2)) { string value = parser.Consume().Value; string value2 = parser.Consume().Value; if (!(value == "name")) { if (value == "filterMode") { Enum.TryParse(value2, out result); } } else { text = value2; } } } else { text = parser.Consume().Value; } Texture2D val = TextureDataManager.LoadTexture(text); if ((Object)(object)val != (Object)null) { ((Object)val).name = text; ((Texture)val).filterMode = result; } else { WMRecipeCust.WLog.LogInfo((object)("Texture '" + text + "' not found")); } return val; } public void WriteYaml(IEmitter emitter, object value, Type type) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) Texture2D val = (Texture2D)value; if ((int)((Texture)val).filterMode == 0) { emitter.Emit(new YamlDotNet.Core.Events.Scalar(((Object)val).name)); return; } emitter.Emit(new MappingStart(null, null, isImplicit: false, MappingStyle.Block)); emitter.Emit(new YamlDotNet.Core.Events.Scalar("name")); emitter.Emit(new YamlDotNet.Core.Events.Scalar(((Object)val).name)); emitter.Emit(new YamlDotNet.Core.Events.Scalar("filterMode")); FilterMode filterMode = ((Texture)val).filterMode; emitter.Emit(new YamlDotNet.Core.Events.Scalar(((object)(FilterMode)(ref filterMode)).ToString())); emitter.Emit(new MappingEnd()); } } [NullableContext(1)] [Nullable(0)] public class YamlLoader { private IDeserializer _deserializer; private ISerializer _serializer; private StringBuilder _stringBuilder; public YamlLoader() { _deserializer = new DeserializerBuilder().WithTypeConverter(new ColorConverter()).WithTypeConverter(new TextureConverter()).WithTypeConverter(new ValheimTimeConverter()) .IgnoreUnmatchedProperties() .Build(); _serializer = new SerializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).WithTypeConverter(new ColorConverter()).WithTypeConverter(new TextureConverter()) .WithTypeConverter(new ValheimTimeConverter()) .Build(); _stringBuilder = new StringBuilder(); } public bool Load<[Nullable(2)] T>(string file, List items, string ymlread = null) { try { string text = ((ymlread != null) ? ymlread : File.ReadAllText(file)); _stringBuilder.Append(text); _stringBuilder.Append(WMRecipeCust.StringSeparator); T val = _deserializer.Deserialize(text); if (val != null) { items.Add(val); return true; } } catch (Exception ex) { WMRecipeCust.WLog.LogWarning((object)("Something went wrong in file " + file)); WMRecipeCust.WLog.LogError((object)ex.Message); } return false; } public bool Write<[Nullable(2)] T>(string file, T data) { try { string contents = _serializer.Serialize(data); File.WriteAllText(file, contents); return true; } catch (Exception ex) { WMRecipeCust.WLog.LogError((object)ex.Message); } return false; } public override string ToString() { return _stringBuilder.ToString(); } } [NullableContext(1)] [Nullable(0)] public class ColorConverter : IYamlTypeConverter { public bool Accepts(Type type) { return type == typeof(Color); } public object ReadYaml(IParser parser, Type type) { //IL_009d: Unknown result type (might be due to invalid IL or missing references) parser.Consume(); List list = new List(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { string value = parser.Consume().Value; value = value.Replace(',', '.'); list.Add(float.Parse(value, NumberFormatInfo.InvariantInfo)); } return (object)new Color((list.Count > 0) ? list[0] : 0f, (list.Count > 1) ? list[1] : 0f, (list.Count > 2) ? list[2] : 0f, (list.Count > 3) ? list[3] : 0f); } public void WriteYaml(IEmitter emitter, object value, Type type) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) emitter.Emit(new SequenceStart(null, null, isImplicit: false, SequenceStyle.Flow)); Color val = (Color)value; emitter.Emit(new YamlDotNet.Core.Events.Scalar(val.r.ToString(NumberFormatInfo.InvariantInfo))); emitter.Emit(new YamlDotNet.Core.Events.Scalar(val.g.ToString(NumberFormatInfo.InvariantInfo))); emitter.Emit(new YamlDotNet.Core.Events.Scalar(val.b.ToString(NumberFormatInfo.InvariantInfo))); emitter.Emit(new YamlDotNet.Core.Events.Scalar(val.a.ToString(NumberFormatInfo.InvariantInfo))); emitter.Emit(new SequenceEnd()); } } [NullableContext(1)] [Nullable(0)] public class ValheimTimeConverter : IYamlTypeConverter { public bool Accepts(Type type) { return type == typeof(ValheimTime); } public object ReadYaml(IParser parser, Type type) { parser.Consume(); List list = new List(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { string value = parser.Consume().Value; list.Add(int.Parse(value)); } return new ValheimTime((list.Count > 0) ? list[0] : 0, (list.Count > 1) ? list[1] : 0, (list.Count > 2) ? list[2] : 0, (list.Count > 3) ? list[3] : 0); } public void WriteYaml(IEmitter emitter, object value, Type type) { emitter.Emit(new SequenceStart(null, null, isImplicit: false, SequenceStyle.Flow)); ValheimTime valheimTime = (ValheimTime)value; emitter.Emit(new YamlDotNet.Core.Events.Scalar(valheimTime.Hour.ToString())); emitter.Emit(new YamlDotNet.Core.Events.Scalar(valheimTime.Minute.ToString())); emitter.Emit(new YamlDotNet.Core.Events.Scalar(valheimTime.Second.ToString())); emitter.Emit(new YamlDotNet.Core.Events.Scalar(valheimTime.Day.ToString())); emitter.Emit(new SequenceEnd()); } } } namespace wackydatabase.Armor { public class ArmorHelpers { public enum NewDamageTypes { Water = 0x400 } internal static bool ShouldOverride(DamageModifier a, DamageModifier b) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Invalid comparison between Unknown and I4 //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Invalid comparison between Unknown and I4 //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Invalid comparison between Unknown and I4 if ((int)a != 4) { if ((int)b != 3) { if ((int)a != 5 || (int)b != 1) { if ((int)a == 6) { return (int)b != 2; } return true; } return false; } return true; } return false; } [NullableContext(1)] internal static DamageModifier GetNewDamageTypeMod(NewDamageTypes type, Character character) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) Traverse val = Traverse.Create((object)character); return GetNewDamageTypeMod(type, val.Field("m_chestItem").GetValue(), val.Field("m_legItem").GetValue(), val.Field("m_helmetItem").GetValue(), val.Field("m_shoulderItem").GetValue()); } [NullableContext(1)] internal static DamageModifier GetNewDamageTypeMod(NewDamageTypes type, ItemData chestItem, ItemData legItem, ItemData helmetItem, ItemData shoulderItem) { //IL_000f: 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_0034: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_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_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0069: 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_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: 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_009d: 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_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) DamageModPair val = default(DamageModPair); if (chestItem != null) { val = ((IEnumerable)chestItem.m_shared.m_damageModifiers).FirstOrDefault((Func)((DamageModPair s) => (int)s.m_type == (int)type)); } if (legItem != null) { DamageModPair val2 = ((IEnumerable)legItem.m_shared.m_damageModifiers).FirstOrDefault((Func)((DamageModPair s) => (int)s.m_type == (int)type)); if (ShouldOverride(val.m_modifier, val2.m_modifier)) { val = val2; } } if (helmetItem != null) { DamageModPair val3 = ((IEnumerable)helmetItem.m_shared.m_damageModifiers).FirstOrDefault((Func)((DamageModPair s) => (int)s.m_type == (int)type)); if (ShouldOverride(val.m_modifier, val3.m_modifier)) { val = val3; } } if (shoulderItem != null) { DamageModPair val4 = ((IEnumerable)shoulderItem.m_shared.m_damageModifiers).FirstOrDefault((Func)((DamageModPair s) => (int)s.m_type == (int)type)); if (ShouldOverride(val.m_modifier, val4.m_modifier)) { val = val4; } } return val.m_modifier; } } } namespace API { [Nullable(0)] [NullableContext(1)] [PublicAPI] public class WackyDatabase_API { private static readonly bool _IsInstalled; private static MethodInfo eAddBlacklistClone; private static MethodInfo eGetClonedMap; public static bool IsInstalled() { return _IsInstalled; } public static void AddBlacklistClone(string value) { eAddBlacklistClone?.Invoke(null, new object[1] { value }); } public static string GetClonedMap(string maybeclone) { string result = ""; if (eGetClonedMap != null) { result = (string)eGetClonedMap.Invoke(null, new object[1] { maybeclone }); } return result; } static WackyDatabase_API() { if (Type.GetType("API.WackyAPI, WackysDatabase") == null) { _IsInstalled = false; return; } Type? type = Type.GetType("API.WackyAPI, WackysDatabase"); _IsInstalled = true; eAddBlacklistClone = type.GetMethod("AddBlacklistClone", BindingFlags.Static | BindingFlags.Public); eGetClonedMap = type.GetMethod("GetClonedMap", BindingFlags.Static | BindingFlags.Public); } } [NullableContext(1)] [Nullable(0)] public static class WackyAPI { public static void AddBlacklistClone(string value) { WMRecipeCust.AddBlacklistClone(value); } public static string GetClonedMap(string maybeclone) { if (WMRecipeCust.ClonedPrefabsMap.ContainsKey(maybeclone)) { return WMRecipeCust.ClonedPrefabsMap[maybeclone]; } return ""; } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<34cd89b2-4f11-42c7-95ae-6cd28145f804>Embedded] internal sealed class <34cd89b2-4f11-42c7-95ae-6cd28145f804>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [<34cd89b2-4f11-42c7-95ae-6cd28145f804>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)] [<34cd89b2-4f11-42c7-95ae-6cd28145f804>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; } } [<34cd89b2-4f11-42c7-95ae-6cd28145f804>Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [CompilerGenerated] internal sealed class <3519a4e3-ad03-44db-a068-700588bcd149>NullableContextAttribute : Attribute { public readonly byte Flag; public <3519a4e3-ad03-44db-a068-700588bcd149>NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace YamlDotNet { [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal sealed class CultureInfoAdapter : CultureInfo { private readonly IFormatProvider provider; public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider) : base(baseCulture.LCID) { this.provider = provider; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] public override object GetFormat(Type formatType) { return provider.GetFormat(formatType); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal static class ReflectionExtensions { [Nullable(2)] private static readonly FieldInfo RemoteStackTraceField = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic); [return: Nullable(2)] 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 (object)type.GetConstructor(bindingFlags, null, Type.EmptyTypes, null) != null; } return true; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } [return: Nullable(2)] public static PropertyInfo GetPublicProperty(this Type type, string name) { return type.GetProperty(name); } [return: Nullable(2)] 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([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (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 + "'."); } [return: Nullable(2)] public static MethodInfo GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes) { return type.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, parameterTypes, null); } [return: Nullable(2)] 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 ((object)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<[Nullable(2)] TAttribute>(this PropertyInfo property) { return Attribute.GetCustomAttributes(property, typeof(TAttribute), inherit: true); } } internal static class PropertyInfoExtensions { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [return: Nullable(2)] 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 { [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal abstract class BuilderSkeleton<[Nullable(0)] TBuilder> 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<[Nullable(2)] TClass>(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) { if (typeConverter == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter.GetType(), (Nothing _) => typeConverter)); return Self; } public TBuilder WithTypeConverter<[Nullable(0)] TYamlTypeConverter>(WrapperFactory typeConverterFactory, Action> where) where TYamlTypeConverter : IYamlTypeConverter { if (typeConverterFactory == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory(wrapped))); return Self; } public TBuilder WithoutTypeConverter<[Nullable(0)] TYamlTypeConverter>() where TYamlTypeConverter : IYamlTypeConverter { return WithoutTypeConverter(typeof(TYamlTypeConverter)); } public TBuilder WithoutTypeConverter(Type converterType) { if ((object)converterType == null) { throw new ArgumentNullException("converterType"); } typeConverterFactories.Remove(converterType); return Self; } public TBuilder WithTypeInspector<[Nullable(0)] TTypeInspector>(Func typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeInspector<[Nullable(0)] TTypeInspector>(Func typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { if (typeInspectorFactory == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory(inner))); return Self; } public TBuilder WithTypeInspector<[Nullable(0)] TTypeInspector>(WrapperFactory typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { if (typeInspectorFactory == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory(wrapped, inner))); return Self; } public TBuilder WithoutTypeInspector<[Nullable(0)] TTypeInspector>() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if ((object)inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } protected IEnumerable BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } internal delegate TComponent WrapperFactory<[Nullable(2)] TComponentBase, TComponent>(TComponentBase wrapped) where TComponent : TComponentBase; internal delegate TComponent WrapperFactory<[Nullable(2)] TArgument, [Nullable(2)] TComponentBase, TComponent>(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase; [Flags] internal enum DefaultValuesHandling { Preserve = 0, OmitNull = 1, OmitDefaults = 2, OmitEmptyCollections = 4 } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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<[Nullable(2)] T>(string input) { using StringReader input2 = new StringReader(input); return Deserialize(input2); } public T Deserialize<[Nullable(2)] T>(TextReader input) { return Deserialize(new Parser(input)); } [return: Nullable(2)] public object Deserialize(TextReader input) { return Deserialize(input, typeof(object)); } [return: Nullable(2)] public object Deserialize(string input, Type type) { using StringReader input2 = new StringReader(input); return Deserialize(input2, type); } [return: Nullable(2)] public object Deserialize(TextReader input, Type type) { return Deserialize(new Parser(input), type); } public T Deserialize<[Nullable(2)] T>(IParser parser) { return (T)Deserialize(parser, typeof(T)); } [return: Nullable(2)] public object Deserialize(IParser parser) { return Deserialize(parser, typeof(object)); } [return: Nullable(2)] public object Deserialize(IParser parser, Type type) { if (parser == null) { throw new ArgumentNullException("parser"); } if ((object)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; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(new byte[] { 0, 1 })] 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) { if (objectFactory == null) { throw new ArgumentNullException("objectFactory"); } this.objectFactory = new Lazy(() => objectFactory, 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) { if (nodeDeserializer == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer.GetType(), (Nothing _) => nodeDeserializer)); return this; } public DeserializerBuilder WithNodeDeserializer<[Nullable(0)] TNodeDeserializer>(WrapperFactory nodeDeserializerFactory, Action> where) where TNodeDeserializer : INodeDeserializer { if (nodeDeserializerFactory == null) { throw new ArgumentNullException("nodeDeserializerFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory(wrapped))); return this; } public DeserializerBuilder WithoutNodeDeserializer<[Nullable(0)] TNodeDeserializer>() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public DeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if ((object)nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action> where) { if (nodeTypeResolver == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver.GetType(), (Nothing _) => nodeTypeResolver)); return this; } public DeserializerBuilder WithNodeTypeResolver<[Nullable(0)] TNodeTypeResolver>(WrapperFactory nodeTypeResolverFactory, Action> where) where TNodeTypeResolver : INodeTypeResolver { if (nodeTypeResolverFactory == null) { throw new ArgumentNullException("nodeTypeResolverFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory(wrapped))); return this; } public DeserializerBuilder WithoutNodeTypeResolver<[Nullable(0)] TNodeTypeResolver>() where TNodeTypeResolver : INodeTypeResolver { return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); } public DeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) { if ((object)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 ((object)type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(tag, out var 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<[Nullable(2)] TInterface, [Nullable(0)] TConcrete>() 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)); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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<[Nullable(0)] T>() where T : IObjectGraphVisitor { return preProcessingPhaseVisitors.OfType().Single(); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] protected ObjectEventInfo(IObjectDescriptor source) : base(source) { } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public MappingStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class MappingEndEventInfo : EventInfo { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public MappingEndEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public SequenceStyle Style { get; set; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public SequenceStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceEndEventInfo : EventInfo { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public SequenceEndEventInfo(IObjectDescriptor source) : base(source) { } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IAliasProvider { AnchorName GetAlias(object target); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IDeserializer { T Deserialize<[Nullable(2)] T>(string input); T Deserialize<[Nullable(2)] T>(TextReader input); [return: Nullable(2)] object Deserialize(TextReader input); [return: Nullable(2)] object Deserialize(string input, Type type); [return: Nullable(2)] object Deserialize(TextReader input, Type type); T Deserialize<[Nullable(2)] T>(IParser parser); [return: Nullable(2)] object Deserialize(IParser parser); [return: Nullable(2)] object Deserialize(IParser parser, Type type); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface INamingConvention { string Apply(string value); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface INodeDeserializer { bool Deserialize(IParser reader, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface INodeTypeResolver { bool Resolve([Nullable(2)] NodeEvent nodeEvent, ref Type currentType); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IObjectAccessor { void Set(string name, object target, object value); [return: Nullable(2)] object Read(string name, object target); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IObjectDescriptor { [Nullable(2)] object Value { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] get; } Type Type { get; } Type StaticType { get; } ScalarStyle ScalarStyle { get; } } internal static class ObjectDescriptorExtensions { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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."); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IObjectFactory { object Create(Type type); [return: Nullable(2)] object CreatePrimitive(Type type); bool GetDictionary(IObjectDescriptor descriptor, [Nullable(2)] out IDictionary dictionary, [Nullable(new byte[] { 2, 1 })] out Type[] genericArguments); Type GetValueType(Type type); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IObjectGraphTraversalStrategy { void Traverse<[Nullable(2)] TContext>(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IObjectGraphVisitor<[Nullable(2)] TContext> { 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); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IPropertyDescriptor { string Name { get; } bool CanWrite { get; } Type Type { get; } [Nullable(2)] Type TypeOverride { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] get; [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] set; } int Order { get; set; } ScalarStyle ScalarStyle { get; set; } T GetCustomAttribute<[Nullable(0)] T>() where T : Attribute; IObjectDescriptor Read(object target); void Write(object target, [Nullable(2)] object value); } internal interface IRegistrationLocationSelectionSyntax<[Nullable(2)] TBaseRegistrationType> { void InsteadOf() where TRegistrationType : TBaseRegistrationType; void Before() where TRegistrationType : TBaseRegistrationType; void After() where TRegistrationType : TBaseRegistrationType; void OnTop(); void OnBottom(); } internal interface ITrackingRegistrationLocationSelectionSyntax<[Nullable(2)] TBaseRegistrationType> { void InsteadOf() where TRegistrationType : TBaseRegistrationType; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface ITypeInspector { IEnumerable GetProperties(Type type, [Nullable(2)] object container); IPropertyDescriptor GetProperty(Type type, [Nullable(2)] object container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface ITypeResolver { Type Resolve(Type staticType, [Nullable(2)] object actualValue); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IValueDeserializer { [return: Nullable(2)] object DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer); } internal interface IValuePromise { [Nullable(new byte[] { 1, 2 })] event Action ValueAvailable; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] internal interface IValueSerializer { void SerializeValue([Nullable(1)] IEmitter emitter, object value, Type type); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IYamlConvertible { void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer); void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer); } [return: Nullable(2)] internal delegate object ObjectDeserializer(Type type); internal delegate void ObjectSerializer(object value, Type type = null); [Obsolete("Please use IYamlConvertible instead")] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IYamlSerializable { void ReadYaml(IParser parser); void WriteYaml(IEmitter emitter); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IYamlTypeConverter { bool Accepts(Type type); [return: Nullable(2)] object ReadYaml(IParser parser, Type type); void WriteYaml(IEmitter emitter, [Nullable(2)] object value, Type type); } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal sealed class LazyComponentRegistrationList<[Nullable(2)] TArgument, [Nullable(2)] TComponent> : IEnumerable>, IEnumerable { [Nullable(0)] public sealed class LazyComponentRegistration { public readonly Type ComponentType; public readonly Func Factory; public LazyComponentRegistration(Type componentType, Func factory) { ComponentType = componentType; Factory = factory; } } [Nullable(0)] public sealed class TrackingLazyComponentRegistration { public readonly Type ComponentType; public readonly Func Factory; public TrackingLazyComponentRegistration(Type componentType, Func factory) { ComponentType = componentType; Factory = factory; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] private class RegistrationLocationSelector : IRegistrationLocationSelectionSyntax { [Nullable(1)] private readonly LazyComponentRegistrationList registrations; [Nullable(new byte[] { 1, 0, 0 })] private readonly LazyComponentRegistration newRegistration; [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public RegistrationLocationSelector(LazyComponentRegistrationList registrations, [Nullable(new byte[] { 1, 0, 0 })] LazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void IRegistrationLocationSelectionSyntax.InsteadOf() { if ((object)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); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] private class TrackingRegistrationLocationSelector : ITrackingRegistrationLocationSelectionSyntax { [Nullable(1)] private readonly LazyComponentRegistrationList registrations; [Nullable(new byte[] { 1, 0, 0 })] private readonly TrackingLazyComponentRegistration newRegistration; [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public TrackingRegistrationLocationSelector(LazyComponentRegistrationList registrations, [Nullable(new byte[] { 1, 0, 0 })] TrackingLazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void ITrackingRegistrationLocationSelectionSyntax.InsteadOf() { if ((object)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, [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] (TArgument arg) => newRegistration.Factory(innerComponentFactory(arg), arg)); } } [Nullable(new byte[] { 1, 1, 0, 0 })] 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 ((object)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([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (LazyComponentRegistration e) => e.Factory).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private int IndexOfRegistration(Type registrationType) { for (int i = 0; i < entries.Count; i++) { if ((object)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."); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal static class LazyComponentRegistrationListExtensions { public static TComponent BuildComponentChain<[Nullable(2)] TComponent>(this LazyComponentRegistrationList registrations, TComponent innerComponent) { return registrations.InReverseOrder.Aggregate(innerComponent, [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (TComponent inner, Func factory) => factory(inner)); } public static TComponent BuildComponentChain<[Nullable(2)] TArgument, [Nullable(2)] TComponent>(this LazyComponentRegistrationList registrations, TComponent innerComponent, Func argumentBuilder) { return registrations.InReverseOrder.Aggregate(innerComponent, [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (TComponent inner, Func factory) => factory(argumentBuilder(inner))); } public static List BuildComponentList<[Nullable(2)] TComponent>(this LazyComponentRegistrationList registrations) { return registrations.Select([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (Func factory) => factory(default(Nothing))).ToList(); } public static List BuildComponentList<[Nullable(2)] TArgument, [Nullable(2)] TComponent>(this LazyComponentRegistrationList registrations, TArgument argument) { return registrations.Select([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (Func factory) => factory(argument)).ToList(); } } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct Nothing { } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal sealed class ObjectDescriptor : IObjectDescriptor { [Nullable(2)] [field: Nullable(2)] public object Value { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] get; [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] private set; } public Type Type { get; private set; } public Type StaticType { get; private set; } public ScalarStyle ScalarStyle { get; private set; } public ObjectDescriptor([Nullable(2)] object value, Type type, Type staticType) : this(value, type, staticType, ScalarStyle.Any) { } public ObjectDescriptor([Nullable(2)] 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); [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal sealed class PropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; public string Name { get; set; } public Type Type => baseDescriptor.Type; [Nullable(2)] public Type TypeOverride { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] get { return baseDescriptor.TypeOverride; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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, [Nullable(2)] object value) { baseDescriptor.Write(target, value); } public T GetCustomAttribute<[Nullable(0)] T>() where T : Attribute { return baseDescriptor.GetCustomAttribute(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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 ((object)type == null) { throw new ArgumentNullException("type"); } EmitDocument(emitter, graph, type); } private void EmitDocument(IEmitter emitter, object graph, [Nullable(2)] 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()); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(new byte[] { 0, 1 })] internal sealed class SerializerBuilder : BuilderSkeleton { [Nullable(0)] 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; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] public void SerializeValue([Nullable(1)] IEmitter emitter, object value, Type type) { 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), [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (IObjectGraphVisitor inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); traversalStrategy.Traverse(graph, visitor, emitter); [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] void NestedObjectSerializer(object v, Type t) { SerializeValue(emitter, 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<[Nullable(0)] TEventEmitter>(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public SerializerBuilder WithEventEmitter<[Nullable(0)] TEventEmitter>(Func eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { if (eventEmitterFactory == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory(inner))); return Self; } public SerializerBuilder WithEventEmitter<[Nullable(0)] TEventEmitter>(WrapperFactory eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { if (eventEmitterFactory == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory(wrapped, inner))); return Self; } public SerializerBuilder WithoutEventEmitter<[Nullable(0)] TEventEmitter>() where TEventEmitter : IEventEmitter { return WithoutEventEmitter(typeof(TEventEmitter)); } public SerializerBuilder WithoutEventEmitter(Type eventEmitterType) { if ((object)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 ((object)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 ((object)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([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] ([Nullable(1)] IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: true, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); return WithTypeInspector([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] ([Nullable(1)] 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([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] ([Nullable(1)] IEventEmitter inner) => new JsonEventEmitter(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); } public SerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitor == null) { throw new ArgumentNullException("objectGraphVisitor"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable _) => objectGraphVisitor)); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, IEnumerable _) => objectGraphVisitorFactory(wrapped))); return this; } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if ((object)objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public SerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory) { this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory; return this; } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(Func objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(Func objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(args))); return this; } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(wrapped, args))); return this; } public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if ((object)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; } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal abstract class StaticBuilderSkeleton<[Nullable(0)] TBuilder> 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) { if (typeConverter == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter.GetType(), (Nothing _) => typeConverter)); return Self; } public TBuilder WithTypeConverter<[Nullable(0)] TYamlTypeConverter>(WrapperFactory typeConverterFactory, Action> where) where TYamlTypeConverter : IYamlTypeConverter { if (typeConverterFactory == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory(wrapped))); return Self; } public TBuilder WithoutTypeConverter<[Nullable(0)] TYamlTypeConverter>() where TYamlTypeConverter : IYamlTypeConverter { return WithoutTypeConverter(typeof(TYamlTypeConverter)); } public TBuilder WithoutTypeConverter(Type converterType) { if ((object)converterType == null) { throw new ArgumentNullException("converterType"); } typeConverterFactories.Remove(converterType); return Self; } public TBuilder WithTypeInspector<[Nullable(0)] TTypeInspector>(Func typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeInspector<[Nullable(0)] TTypeInspector>(Func typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { if (typeInspectorFactory == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory(inner))); return Self; } public TBuilder WithTypeInspector<[Nullable(0)] TTypeInspector>(WrapperFactory typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { if (typeInspectorFactory == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory(wrapped, inner))); return Self; } public TBuilder WithoutTypeInspector<[Nullable(0)] TTypeInspector>() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if ((object)inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } protected IEnumerable BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal abstract class StaticContext { public virtual StaticObjectFactory GetFactory() { throw new NotImplementedException(); } public virtual ITypeInspector GetTypeInspector() { throw new NotImplementedException(); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(new byte[] { 0, 1 })] 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) { if (nodeDeserializer == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer.GetType(), (Nothing _) => nodeDeserializer)); return this; } public StaticDeserializerBuilder WithNodeDeserializer<[Nullable(0)] TNodeDeserializer>(WrapperFactory nodeDeserializerFactory, Action> where) where TNodeDeserializer : INodeDeserializer { if (nodeDeserializerFactory == null) { throw new ArgumentNullException("nodeDeserializerFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory(wrapped))); return this; } public StaticDeserializerBuilder WithoutNodeDeserializer<[Nullable(0)] TNodeDeserializer>() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public StaticDeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if ((object)nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action> where) { if (nodeTypeResolver == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver.GetType(), (Nothing _) => nodeTypeResolver)); return this; } public StaticDeserializerBuilder WithNodeTypeResolver<[Nullable(0)] TNodeTypeResolver>(WrapperFactory nodeTypeResolverFactory, Action> where) where TNodeTypeResolver : INodeTypeResolver { if (nodeTypeResolverFactory == null) { throw new ArgumentNullException("nodeTypeResolverFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory(wrapped))); return this; } public StaticDeserializerBuilder WithoutNodeTypeResolver<[Nullable(0)] TNodeTypeResolver>() where TNodeTypeResolver : INodeTypeResolver { return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); } public StaticDeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) { if ((object)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 ((object)type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(tag, out var 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<[Nullable(2)] TInterface, [Nullable(0)] TConcrete>() 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)); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(new byte[] { 0, 1 })] internal sealed class StaticSerializerBuilder : StaticBuilderSkeleton { [Nullable(0)] 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; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] public void SerializeValue([Nullable(1)] IEmitter emitter, object value, Type type) { 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), [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (IObjectGraphVisitor inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); traversalStrategy.Traverse(graph, visitor, emitter); [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] void NestedObjectSerializer(object v, Type t) { SerializeValue(emitter, 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<[Nullable(0)] TEventEmitter>(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticSerializerBuilder WithEventEmitter<[Nullable(0)] TEventEmitter>(Func eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { if (eventEmitterFactory == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory(inner))); return Self; } public StaticSerializerBuilder WithEventEmitter<[Nullable(0)] TEventEmitter>(WrapperFactory eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { if (eventEmitterFactory == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory(wrapped, inner))); return Self; } public StaticSerializerBuilder WithoutEventEmitter<[Nullable(0)] TEventEmitter>() where TEventEmitter : IEventEmitter { return WithoutEventEmitter(typeof(TEventEmitter)); } public StaticSerializerBuilder WithoutEventEmitter(Type eventEmitterType) { if ((object)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 ((object)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 ((object)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([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] ([Nullable(1)] IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: true, tagMappings, quoteNecessaryStrings), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); return WithTypeInspector([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] ([Nullable(1)] 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([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] ([Nullable(1)] IEventEmitter inner) => new JsonEventEmitter(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); } public StaticSerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitor == null) { throw new ArgumentNullException("objectGraphVisitor"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable _) => objectGraphVisitor)); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, IEnumerable _) => objectGraphVisitorFactory(wrapped))); return this; } public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if ((object)objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public StaticSerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory) { this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory; return this; } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(Func objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(Func objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(args))); return this; } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(wrapped, args))); return this; } public StaticSerializerBuilder WithoutEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public StaticSerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if ((object)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); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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); } } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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); } [return: Nullable(2)] internal Type GetMapping(string tag) { if (!mappings.TryGetValue(tag, out var value)) { return null; } return value; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal sealed class YamlAttributeOverrides { [Nullable(0)] private struct AttributeKey { public readonly Type AttributeType; public readonly string PropertyName; public AttributeKey(Type attributeType, string propertyName) { AttributeType = attributeType; PropertyName = propertyName; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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()); } } [Nullable(0)] private sealed class AttributeMapping { public readonly Type RegisteredType; public readonly Attribute Attribute; public AttributeMapping(Type registeredType, Attribute attribute) { RegisteredType = registeredType; Attribute = attribute; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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 ((object)type != null) { num++; if ((object)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<[Nullable(0)] T>(Type type, string member) where T : Attribute { if (overrides.TryGetValue(new AttributeKey(typeof(T), member), out var 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 var 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<[Nullable(2)] TClass>(Expression> propertyAccessor, Attribute attribute) { PropertyInfo propertyInfo = propertyAccessor.AsProperty(); Add(typeof(TClass), propertyInfo.Name, attribute); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal sealed class YamlAttributeOverridesInspector : TypeInspectorSkeleton { [Nullable(0)] 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; [Nullable(2)] public Type TypeOverride { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] get { return baseDescriptor.TypeOverride; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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, [Nullable(2)] object value) { baseDescriptor.Write(target, value); } public T GetCustomAttribute<[Nullable(0)] T>() 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, [Nullable(2)] object container) { IEnumerable enumerable = innerTypeDescriptor.GetProperties(type, container); if (overrides != null) { enumerable = enumerable.Select((Func)([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (IPropertyDescriptor p) => new OverridePropertyDescriptor(p, overrides, type))); } return enumerable; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal sealed class YamlAttributesTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; public YamlAttributesTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor; } public override IEnumerable GetProperties(Type type, [Nullable(2)] object container) { return from p in (from p in innerTypeDescriptor.GetProperties(type, container) where p.GetCustomAttribute() == null select p).Select((Func)([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (IPropertyDescriptor p) => { PropertyDescriptor propertyDescriptor = new PropertyDescriptor(p); YamlMemberAttribute customAttribute = p.GetCustomAttribute(); if (customAttribute != null) { if ((object)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; } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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)] [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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 { [Nullable(new byte[] { 0, 1 })] 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"); } } } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] [Nullable(0)] 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; [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public ValuePromise(YamlDotNet.Core.Events.AnchorAlias alias) { Alias = alias; } public ValuePromise(object value) { HasValue = true; this.value = value; } } [Nullable(1)] private readonly IValueDeserializer innerDeserializer; [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public AliasValueDeserializer(IValueDeserializer innerDeserializer) { this.innerDeserializer = innerDeserializer ?? throw new ArgumentNullException("innerDeserializer"); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [return: Nullable(2)] public object DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { if (parser.TryConsume(out var @event)) { if (!state.Get().TryGetValue(@event.Value, out var 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 var value2)) { aliasState2.Add(anchorName, new ValuePromise(obj)); } else if (!value2.HasValue) { value2.Value = obj; } else { aliasState2[anchorName] = new ValuePromise(obj); } } return obj; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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"); } [return: Nullable(2)] public object DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { 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, [return: Nullable(2)] (IParser r, Type t) => nestedObjectDeserializer.DeserializeValue(r, t, state, nestedObjectDeserializer), out var 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([Nullable(2)] 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(); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] internal interface ITypeConverter { object ChangeType(object value, [Nullable(1)] Type expectedType); } internal class NullTypeConverter : ITypeConverter { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] public object ChangeType(object value, [Nullable(1)] Type expectedType) { return value; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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 var 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)][Nullable(2)] out string anchor) { return anchorsByObject.TryGetValue(@object, out anchor); } } internal class ReflectionTypeConverter : ITypeConverter { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] public object ChangeType(object value, [Nullable(1)] Type expectedType) { return TypeConverter.ChangeType(value, expectedType); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal static class ReflectionUtility { [return: Nullable(2)] public static Type GetImplementedGenericInterface(Type type, Type genericInterfaceType) { foreach (Type implementedInterface in GetImplementedInterfaces(type)) { if (implementedInterface.IsGenericType() && (object)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 { [Nullable(1)] private readonly IDictionary items = new Dictionary(); [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public T Get() where T : class, new() { if (!items.TryGetValue(typeof(T), out var 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(); } } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal static class StringExtensions { private static string ToCamelOrPascalCase(string str, Func firstLetterTransform) { string text = Regex.Replace(str, "([_\\-])(?[a-z])", [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (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) { str = char.ToLower(str[0]) + str.Substring(1); str = Regex.Replace(str.ToCamelCase(), "(?[A-Z])", [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (Match match) => separator + match.Groups["char"].Value.ToLowerInvariant()); return str; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal static class TypeConverter { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] [return: Nullable(1)] public static T ChangeType(object value) { return (T)ChangeType(value, typeof(T)); } public static T ChangeType<[Nullable(2)] T>([Nullable(2)] object value, IFormatProvider provider) { return (T)ChangeType(value, typeof(T), provider); } public static T ChangeType<[Nullable(2)] T>([Nullable(2)] object value, CultureInfo culture) { return (T)ChangeType(value, typeof(T), culture); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] public static object ChangeType(object value, [Nullable(1)] Type destinationType) { return ChangeType(value, destinationType, CultureInfo.InvariantCulture); } [return: Nullable(2)] public static object ChangeType([Nullable(2)] object value, Type destinationType, IFormatProvider provider) { return ChangeType(value, destinationType, new CultureInfoAdapter(CultureInfo.CurrentCulture, provider)); } [return: Nullable(2)] public static object ChangeType([Nullable(2)] 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 ((object)destinationType == type || destinationType.IsAssignableFrom(type)) { return value; } if (destinationType.IsGenericType() && (object)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 ((object)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 ((object)type == typeof(string)) { try { MethodInfo publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string), typeof(IFormatProvider)); if ((object)publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[2] { value, culture }); } publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string)); if ((object)publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[1] { value }); } } catch (TargetInvocationException ex2) { throw ex2.Unwrap(); } } if ((object)destinationType == typeof(TimeSpan)) { return TimeSpan.Parse((string)ChangeType(value, typeof(string), CultureInfo.InvariantCulture)); } return Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public static void RegisterTypeConverter<[Nullable(2)] TConvertible, TConverter>() where TConverter : System.ComponentModel.TypeConverter { if (!TypeDescriptor.GetAttributes(typeof(TConvertible)).OfType().Any([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (TypeConverterAttribute a) => a.ConverterTypeName == typeof(TConverter).AssemblyQualifiedName)) { TypeDescriptor.AddAttributes(typeof(TConvertible), new TypeConverterAttribute(typeof(TConverter))); } } } } namespace YamlDotNet.Serialization.TypeResolvers { internal sealed class DynamicTypeResolver : ITypeResolver { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public Type Resolve(Type staticType, [Nullable(2)] object actualValue) { if (actualValue == null) { return staticType; } return actualValue.GetType(); } } internal sealed class StaticTypeResolver : ITypeResolver { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public Type Resolve(Type staticType, [Nullable(2)] object actualValue) { return staticType; } } } namespace YamlDotNet.Serialization.TypeInspectors { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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, [Nullable(2)] object container) { return cache.GetOrAdd(type, (Type t) => innerTypeDescriptor.GetProperties(t, container).ToList()); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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, [Nullable(2)] object container) { return typeInspectors.SelectMany([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (ITypeInspector i) => i.GetProperties(type, container)); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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, [Nullable(2)] object container) { return innerTypeDescriptor.GetProperties(type, container).Select([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (IPropertyDescriptor p) => { YamlMemberAttribute customAttribute = p.GetCustomAttribute(); return (customAttribute != null && !customAttribute.ApplyNamingConventions) ? p : new PropertyDescriptor(p) { Name = namingConvention.Apply(p.Name) }; }); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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, [Nullable(2)] object container) { return from p in innerTypeDescriptor.GetProperties(type, container) where p.CanWrite select p; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal sealed class ReadableFieldsTypeInspector : TypeInspectorSkeleton { [Nullable(0)] private sealed class ReflectionFieldDescriptor : IPropertyDescriptor { private readonly FieldInfo fieldInfo; private readonly ITypeResolver typeResolver; public string Name => fieldInfo.Name; public Type Type => fieldInfo.FieldType; [Nullable(2)] [field: Nullable(2)] public Type TypeOverride { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] get; [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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, [Nullable(2)] object value) { fieldInfo.SetValue(target, value); } public T GetCustomAttribute<[Nullable(0)] T>() 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, [Nullable(2)] object container) { return type.GetPublicFields().Select((Func)([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (FieldInfo p) => new ReflectionFieldDescriptor(p, typeResolver))); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal sealed class ReadablePropertiesTypeInspector : TypeInspectorSkeleton { [Nullable(0)] private sealed class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly ITypeResolver typeResolver; public string Name => propertyInfo.Name; public Type Type => propertyInfo.PropertyType; [Nullable(2)] [field: Nullable(2)] public Type TypeOverride { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] get; [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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, [Nullable(2)] object value) { propertyInfo.SetValue(target, value, null); } public T GetCustomAttribute<[Nullable(0)] T>() 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, [Nullable(2)] object container) { return type.GetProperties(includeNonPublicProperties).Where(IsValidProperty).Select((Func)([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (PropertyInfo p) => new ReflectionPropertyDescriptor(p, typeResolver))); } } internal abstract class TypeInspectorSkeleton : ITypeInspector { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public abstract IEnumerable GetProperties(Type type, [Nullable(2)] object container); [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public IPropertyDescriptor GetProperty(Type type, [Nullable(2)] object container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched) { IEnumerable enumerable = from p in GetProperties(type, container) where p.Name == name select p; using IEnumerator enumerator = enumerable.GetEnumerator(); if (!enumerator.MoveNext()) { if (ignoreUnmatched) { return null; } throw new SerializationException("Property '" + name + "' not found on type '" + type.FullName + "'."); } IPropertyDescriptor current = enumerator.Current; if (enumerator.MoveNext()) { throw new SerializationException("Multiple properties with the name/alias '" + name + "' 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; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal sealed class WritablePropertiesTypeInspector : TypeInspectorSkeleton { [Nullable(0)] private sealed class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly ITypeResolver typeResolver; public string Name => propertyInfo.Name; public Type Type => propertyInfo.PropertyType; [Nullable(2)] [field: Nullable(2)] public Type TypeOverride { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] get; [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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, [Nullable(2)] object value) { propertyInfo.SetValue(target, value, null); } public T GetCustomAttribute<[Nullable(0)] T>() 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, [Nullable(2)] object container) { return type.GetProperties(includeNonPublicProperties).Where(IsValidProperty).Select((Func)([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (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 { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal sealed class AnchorAssigner : PreProcessingPhaseObjectGraphVisitorSkeleton, IAliasProvider { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] 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 var 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 var value)) { return value.Anchor; } return AnchorName.Empty; } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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) { IYamlTypeConverter yamlTypeConverter = typeConverters.FirstOrDefault([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (IYamlTypeConverter t) => t.Accepts(value.Type)); if (yamlTypeConverter != null) { yamlTypeConverter.WriteYaml(context, value.Value, value.Type); return false; } if (value.Value is IYamlConvertible yamlConvertible) { yamlConvertible.Write(context, nestedObjectSerializer); return false; } if (value.Value is IYamlSerializable yamlSerializable) { yamlSerializable.WriteYaml(context); return false; } return base.Enter(value, context); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal sealed class DefaultExclusiveObjectGraphVisitor : ChainedObjectGraphVisitor { public DefaultExclusiveObjectGraphVisitor(IObjectGraphVisitor nextVisitor) : base(nextVisitor) { } [return: Nullable(2)] 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; } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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; } [return: Nullable(2)] 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); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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) { if (typeConverters.FirstOrDefault([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (IYamlTypeConverter t) => t.Accepts(value.Type)) != null) { return false; } if (value.Value is IYamlConvertible) { return false; } if (value.Value is IYamlSerializable) { return false; } return Enter(value); } 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 { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal class FullObjectGraphTraversalStrategy : IObjectGraphTraversalStrategy { [Nullable(0)] 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<[Nullable(2)] TContext>(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context) { Traverse("", graph, visitor, context, new Stack(maxRecursion)); } protected virtual void Traverse<[Nullable(2)] TContext>(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 || (object)value.Type == typeof(TimeSpan)) { visitor.VisitScalar(value, context); return; } Type underlyingType = Nullable.GetUnderlyingType(value.Type); if ((object)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<[Nullable(2)] TContext>(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<[Nullable(2)] TContext>(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<[Nullable(2)] TContext>(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<[Nullable(2)] TContext>(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([Nullable(2)] object value, Type staticType) { return new ObjectDescriptor(value, typeResolver.Resolve(staticType, value), staticType); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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<[Nullable(2)] TContext>(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { if (!value.Type.HasDefaultConstructor(settings.AllowPrivateConstructors) && !converters.Any([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (IYamlTypeConverter c) => c.Accepts(value.Type))) { throw new InvalidOperationException($"Type '{value.Type}' cannot be deserialized because it does not have a default constructor or a type converter."); } base.TraverseProperties(value, visitor, context, path); } } } namespace YamlDotNet.Serialization.ObjectFactories { [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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 var 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); } } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal abstract class ObjectFactoryBase : IObjectFactory { public abstract object Create(Type type); [return: Nullable(2)] public virtual object CreatePrimitive(Type type) { if (!type.IsValueType()) { return null; } return Activator.CreateInstance(type); } public virtual bool GetDictionary(IObjectDescriptor descriptor, [Nullable(2)] out IDictionary dictionary, [Nullable(new byte[] { 2, 1 })] out Type[] genericArguments) { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(descriptor.Type, typeof(IDictionary<, >)); if ((object)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 ((object)implementedGenericInterface == null) { return typeof(object); } return implementedGenericInterface.GetGenericArguments()[0]; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(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); [return: Nullable(2)] 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, [Nullable(2)] out IDictionary dictionary, [Nullable(new byte[] { 2, 1 })] out Type[] genericArguments) { dictionary = null; genericArguments = null; return false; } } } namespace YamlDotNet.Serialization.NodeTypeResolvers { internal sealed class DefaultContainersNodeTypeResolver : INodeTypeResolver { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] bool INodeTypeResolver.Resolve([Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { if ((object)currentType == typeof(object)) { if (nodeEvent is SequenceStart) { currentType = typeof(List); return true; } if (nodeEvent is MappingStart) { currentType = typeof(Dictionary); return true; } } return false; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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([Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { if (_mappings.TryGetValue(currentType, out var value)) { currentType = value; return true; } return false; } } internal class PreventUnknownTagsNodeTypeResolver : INodeTypeResolver { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] bool INodeTypeResolver.Resolve([Nullable(2)] 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; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal sealed class TagNodeTypeResolver : INodeTypeResolver { private readonly IDictionary tagMappings; public TagNodeTypeResolver(IDictionary tagMappings) { this.tagMappings = tagMappings ?? throw new ArgumentNullException("tagMappings"); } bool INodeTypeResolver.Resolve([Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty && tagMappings.TryGetValue(nodeEvent.Tag, out var 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 { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] bool INodeTypeResolver.Resolve([Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty) { Type type = Type.GetType(nodeEvent.Tag.Value.Substring(1), throwOnError: false); if ((object)type != null) { currentType = type; return true; } } return false; } } internal sealed class YamlConvertibleTypeResolver : INodeTypeResolver { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public bool Resolve([Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { return typeof(IYamlConvertible).IsAssignableFrom(currentType); } } internal sealed class YamlSerializableTypeResolver : INodeTypeResolver { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public bool Resolve([Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { return typeof(IYamlSerializable).IsAssignableFrom(currentType); } } } namespace YamlDotNet.Serialization.NodeDeserializers { internal sealed class ArrayNodeDeserializer : INodeDeserializer { [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] private sealed class ArrayList : IList, ICollection, IEnumerable { [Nullable(new byte[] { 1, 2 })] 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; [Nullable(1)] public object SyncRoot { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] get { return 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(); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public void CopyTo(Array array, int index) { Array.Copy(data, 0, array, index, Count); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public IEnumerator GetEnumerator() { int i = 0; while (i < Count) { yield return data[i]; int num = i + 1; i = num; } } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] 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 { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] protected static void DeserializeHelper(Type tItem, IParser parser, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, IList result, bool canUpdate, IObjectFactory objectFactory) { 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 = result.Add(objectFactory.CreatePrimitive(tItem)); valuePromise.ValueAvailable += [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] (object v) => { result[index] = v; }; } else { result.Add(obj); } } } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { bool canUpdate = true; Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(ICollection<>)); Type type; IList list; if ((object)implementedGenericInterface != null) { type = implementedGenericInterface.GetGenericArguments()[0]; value = objectFactory.Create(expectedType); list = value as IList; if (list == null) { canUpdate = (object)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, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, IList result, bool canUpdate) { 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 = result.Add(tItem.IsValueType() ? Activator.CreateInstance(tItem) : null); valuePromise.ValueAvailable += [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] (object v) => { result[index] = YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(v, tItem); }; } else { result.Add(YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(obj, tItem)); } } } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, IDictionary 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 += [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] (object v) => { result[v] = value; }; continue; } bool hasFirstPart = false; valuePromise2.ValueAvailable += [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] (object v) => { if (hasFirstPart) { TryAssign(result, v, value, property); } else { key = v; hasFirstPart = true; } }; valuePromise.ValueAvailable += [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] (object v) => { if (hasFirstPart) { TryAssign(result, 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(result, key, value, property); continue; } valuePromise.ValueAvailable += [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] (object v) => { result[key] = v; }; } } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IDictionary<, >)); Type type; Type type2; IDictionary dictionary; if ((object)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 { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { Type type; if ((object)expectedType == typeof(IEnumerable)) { type = typeof(object); } else { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IEnumerable<>)); if ((object)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 { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { value = null; if (parser.Accept(out var @event) && NodeIsNull(@event)) { parser.SkipThisAndNestedEvents(); return true; } return false; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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; } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] 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 += [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] (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; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] 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 ((object)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, }); } [return: Nullable(2)] 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, [Nullable(2)] out object value) { try { value = attempt(); return true; } catch { value = null; return false; } } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal sealed class StaticArrayNodeDeserializer : INodeDeserializer { [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] private sealed class ArrayList : IList, ICollection, IEnumerable { [Nullable(new byte[] { 1, 2 })] 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; [Nullable(1)] public object SyncRoot { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] get { return 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(); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public void CopyTo(Array array, int index) { Array.Copy(data, 0, array, index, Count); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] 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; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] 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, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, IList result, IObjectFactory factory) { parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { _ = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise valuePromise) { int index = result.Add(factory.CreatePrimitive(tItem)); valuePromise.ValueAvailable += [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] (object v) => { result[index] = v; }; } else { result.Add(obj); } } } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] 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; } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { IYamlTypeConverter yamlTypeConverter = converters.FirstOrDefault([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (IYamlTypeConverter c) => c.Accepts(expectedType)); if (yamlTypeConverter == null) { value = null; return false; } value = yamlTypeConverter.ReadYaml(parser, expectedType); return true; } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal sealed class YamlConvertibleNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public YamlConvertibleNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory; } public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { if (typeof(IYamlConvertible).IsAssignableFrom(expectedType)) { IYamlConvertible yamlConvertible = (IYamlConvertible)objectFactory.Create(expectedType); yamlConvertible.Read(parser, expectedType, [return: Nullable(2)] (Type type) => nestedObjectDeserializer(parser, type)); value = yamlConvertible; return true; } value = null; return false; } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal sealed class YamlSerializableNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public YamlSerializableNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory; } public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] 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 { [Nullable(1)] public static readonly INamingConvention Instance = new CamelCaseNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public CamelCaseNamingConvention() { } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public string Apply(string value) { return value.ToCamelCase(); } } internal sealed class HyphenatedNamingConvention : INamingConvention { [Nullable(1)] public static readonly INamingConvention Instance = new HyphenatedNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public HyphenatedNamingConvention() { } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public string Apply(string value) { return value.FromCamelCase("-"); } } internal sealed class LowerCaseNamingConvention : INamingConvention { [Nullable(1)] public static readonly INamingConvention Instance = new LowerCaseNamingConvention(); private LowerCaseNamingConvention() { } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public string Apply(string value) { return value.ToCamelCase().ToLower(); } } internal sealed class NullNamingConvention : INamingConvention { [Nullable(1)] public static readonly INamingConvention Instance = new NullNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public NullNamingConvention() { } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public string Apply(string value) { return value; } } internal sealed class PascalCaseNamingConvention : INamingConvention { [Nullable(1)] public static readonly INamingConvention Instance = new PascalCaseNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public PascalCaseNamingConvention() { } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public string Apply(string value) { return value.ToPascalCase(); } } internal sealed class UnderscoredNamingConvention : INamingConvention { [Nullable(1)] public static readonly INamingConvention Instance = new UnderscoredNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public UnderscoredNamingConvention() { } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public string Apply(string value) { return value.FromCamelCase("_"); } } } namespace YamlDotNet.Serialization.EventEmitters { [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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 ((object)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); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal sealed class TypeAssigningEventEmitter : ChainedEventEmitter { private readonly bool requireTagWhenStaticAndActualTypesAreDifferent; private readonly IDictionary tagMappings; private readonly bool quoteNecessaryStrings; [Nullable(2)] 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 ((object)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 && (object)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; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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 { [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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, [Nullable(2)] 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 (object)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, [Nullable(2)] 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; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal class GuidConverter : IYamlTypeConverter { private readonly bool jsonCompatible; public GuidConverter(bool jsonCompatible) { this.jsonCompatible = jsonCompatible; } public bool Accepts(Type type) { return (object)type == typeof(Guid); } public object ReadYaml(IParser parser, Type type) { return new Guid(parser.Consume().Value); } public void WriteYaml(IEmitter emitter, [Nullable(2)] 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)); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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, [Nullable(2)] 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.RepresentationModel { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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 var value)) { return value; } throw new AnchorNotFoundException(in start, in end, $"The anchor '{anchor}' does not exists"); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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); } } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal class EmitterState { public HashSet EmittedAnchors { get; } = new HashSet(); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IYamlVisitor { void Visit(YamlStream stream); void Visit(YamlDocument document); void Visit(YamlScalarNode scalar); void Visit(YamlSequenceNode sequence); void Visit(YamlMappingNode mapping); } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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(">"); } } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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."); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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; } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal class YamlDocument { [Nullable(0)] 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); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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([Nullable(new byte[] { 1, 0, 1, 1 })] params KeyValuePair[] children) : this((IEnumerable>)children) { } public YamlMappingNode([Nullable(new byte[] { 1, 0, 1, 1 })] 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); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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 var 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(); } } [return: Nullable(new byte[] { 1, 0, 1, 1 })] 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; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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 var 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)([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (string i) => i))); } [return: Nullable(2)] 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; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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 } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [DebuggerDisplay("{Value}")] internal sealed class YamlScalarNode : YamlNode, IYamlConvertible { [Nullable(2)] [field: Nullable(2)] public string Value { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] get; [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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() { } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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); } [return: Nullable(2)] 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}")] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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()); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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(); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] [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); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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] [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal sealed class ConcurrentObjectPool where T : class { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] [DebuggerDisplay("{value,nq}")] private struct Element { [Nullable(2)] internal T value; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] internal delegate T Factory(); [Nullable(2)] private T firstItem; [Nullable(new byte[] { 1, 0, 0 })] private readonly Element[] items; [Nullable(new byte[] { 1, 0 })] private readonly Factory factory; internal ConcurrentObjectPool([Nullable(new byte[] { 1, 0 })] Factory factory) : this(factory, Environment.ProcessorCount * 2) { } internal ConcurrentObjectPool([Nullable(new byte[] { 1, 0 })] 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++) { } } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal static class ExpressionExtensions { public static PropertyInfo AsProperty(this LambdaExpression propertyAccessor) { return TryGetMemberExpression(propertyAccessor) ?? throw new ArgumentException("Expected a lambda expression in the form: x => x.SomeProperty", "propertyAccessor"); } [return: MaybeNull] private static TMemberInfo TryGetMemberExpression<[Nullable(0)] TMemberInfo>(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; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] [Nullable(0)] internal sealed class GenericCollectionToNonGenericAdapter : IList, ICollection, IEnumerable { [Nullable(1)] 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(); } } [Nullable(1)] public object SyncRoot { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] get { throw new NotSupportedException(); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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(); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public void CopyTo(Array array, int index) { throw new NotSupportedException(); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public IEnumerator GetEnumerator() { return genericCollection.GetEnumerator(); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal sealed class GenericDictionaryToNonGenericAdapterNullable(2)] TValue> : IDictionary, ICollection, IEnumerable { [Nullable(0)] private class DictionaryEnumerator : IDictionaryEnumerator, IEnumerator { [Nullable(new byte[] { 1, 0, 1, 1 })] private readonly IEnumerator> enumerator; public DictionaryEntry Entry => new DictionaryEntry(Key, Value); public object Key => enumerator.Current.Key; [Nullable(2)] public object Value { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] get { return enumerator.Current.Value; } } public object Current => Entry; public DictionaryEnumerator([Nullable(new byte[] { 1, 0, 1, 1 })] 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(); } } [Nullable(2)] public object this[object key] { [return: Nullable(2)] get { throw new NotSupportedException(); } [param: Nullable(2)] 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, [Nullable(2)] 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(); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IOrderedDictionaryNullable(2)] TValue> : IDictionary, ICollection>, IEnumerable>, IEnumerable { [Nullable(new byte[] { 0, 1, 1 })] KeyValuePair this[int index] { [return: Nullable(new byte[] { 0, 1, 1 })] get; [param: Nullable(new byte[] { 0, 1, 1 })] 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] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal sealed class OrderedDictionaryNullable(2)] TValue> : IOrderedDictionary, IDictionary, ICollection>, IEnumerable>, IEnumerable { [Nullable(0)] 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([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (KeyValuePair kvp) => kvp.Key).GetEnumerator(); } public bool Remove(TKey item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [Nullable(0)] 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([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (KeyValuePair kvp) => kvp.Value).GetEnumerator(); } public bool Remove(TValue item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [NonSerialized] private Dictionary dictionary; [Nullable(new byte[] { 1, 0, 1, 1 })] private readonly List> list; private readonly IEqualityComparer comparer; public TValue this[TKey key] { get { return dictionary[key]; } set { if (dictionary.ContainsKey(key)) { int index = list.FindIndex(([Nullable(new byte[] { 0, 1, 1 })] KeyValuePair kvp) => comparer.Equals(kvp.Key, key)); dictionary[key] = value; list[index] = new KeyValuePair(key, value); } else { Add(key, value); } } } public ICollection Keys => new KeyCollection(this); public ICollection Values => new ValueCollection(this); public int Count => dictionary.Count; public bool IsReadOnly => false; [Nullable(new byte[] { 0, 1, 1 })] public KeyValuePair this[int index] { [return: Nullable(new byte[] { 0, 1, 1 })] get { return list[index]; } [param: Nullable(new byte[] { 0, 1, 1 })] 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([Nullable(new byte[] { 0, 1, 1 })] KeyValuePair item) { dictionary.Add(item.Key, item.Value); list.Add(item); } public void Clear() { dictionary.Clear(); list.Clear(); } public bool Contains([Nullable(new byte[] { 0, 1, 1 })] KeyValuePair item) { return dictionary.Contains(item); } public bool ContainsKey(TKey key) { return dictionary.ContainsKey(key); } public void CopyTo([Nullable(new byte[] { 1, 0, 1, 1 })] KeyValuePair[] array, int arrayIndex) { list.CopyTo(array, arrayIndex); } [return: Nullable(new byte[] { 1, 0, 1, 1 })] 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) { if (dictionary.ContainsKey(key)) { int index = list.FindIndex(([Nullable(new byte[] { 0, 1, 1 })] KeyValuePair kvp) => comparer.Equals(kvp.Key, key)); list.RemoveAt(index); if (!dictionary.Remove(key)) { throw new InvalidOperationException(); } return true; } return false; } public bool Remove([Nullable(new byte[] { 0, 1, 1 })] 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; } } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [DebuggerStepThrough] [Nullable(0)] internal static class StringBuilderPool { [Nullable(0)] 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)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public static void ThrowArgumentOutOfRangeException(string paramName, string message) { throw new ArgumentOutOfRangeException(paramName, message); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal static class ReadOnlyCollectionExtensions { [Nullable(0)] private sealed class ReadOnlyListAdapter<[Nullable(2)] T> : IReadOnlyList, IEnumerable, IEnumerable, IReadOnlyCollection { private readonly List list; public T this[int index] => list[index]; public int Count => list.Count; public ReadOnlyListAdapter(List list) { this.list = list ?? throw new ArgumentNullException("list"); } public IEnumerator GetEnumerator() { return list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return list.GetEnumerator(); } } [Nullable(0)] private sealed class ReadOnlyDictionaryAdapterNullable(2)] TValue> : IReadOnlyDictionary, IEnumerable>, IEnumerable, IReadOnlyCollection> { private readonly Dictionary dictionary; public TValue this[TKey key] => dictionary[key]; public IEnumerable Keys => dictionary.Keys; public IEnumerable Values => dictionary.Values; public int Count => dictionary.Count; public ReadOnlyDictionaryAdapter(Dictionary dictionary) { this.dictionary = dictionary ?? throw new ArgumentNullException("dictionary"); } public bool ContainsKey(TKey key) { return dictionary.ContainsKey(key); } [return: Nullable(new byte[] { 1, 0, 1, 1 })] public IEnumerator> GetEnumerator() { return dictionary.GetEnumerator(); } public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { return dictionary.TryGetValue(key, out value); } IEnumerator IEnumerable.GetEnumerator() { return dictionary.GetEnumerator(); } } public static IReadOnlyList AsReadonlyList<[Nullable(2)] T>(this List list) { return new ReadOnlyListAdapter(list); } public static IReadOnlyDictionary AsReadonlyDictionaryNullable(2)] TValue>(this Dictionary dictionary) { return new ReadOnlyDictionaryAdapter(dictionary); } } } namespace YamlDotNet.Core { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal struct AnchorName : IEquatable { public static readonly AnchorName Empty = default(AnchorName); private static readonly Regex AnchorPattern = new Regex("^[^\\[\\]\\{\\},]+$", RegexOptions.Compiled); [Nullable(2)] 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); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] public static implicit operator AnchorName(string value) { if (value != null) { return new AnchorName(value); } return Empty; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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) { } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] [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 { [Nullable(1)] 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; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(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; } } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal class Emitter : IEmitter { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] private class AnchorData { public AnchorName Anchor; public bool IsAlias; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] [Nullable(0)] private class TagData { public string Handle; public string Suffix; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] private class ScalarData { [Nullable(1)] 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}", new object[2] { 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([Nullable(new byte[] { 2, 1 })] 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; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] private int SafeStringLength(string value) { return value?.Length ?? 0; } private bool CheckEmptySequence() { return CheckEmptyStructure(); } private bool CheckEmptyMapping() { return CheckEmptyStructure(); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] 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, [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] ([Nullable(1)] 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; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(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() { } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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 } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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) { } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] [Nullable(0)] 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; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IEmitter { void Emit(ParsingEvent @event); } internal interface ILookAheadBuffer { bool EndOfInput { get; } char Peek(int offset); void Skip(int length); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal sealed class InsertionQueue<[Nullable(2)] T> : 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(); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] internal interface IParser { ParsingEvent Current { get; } bool MoveNext(); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] internal interface IScanner { Mark CurrentPosition { get; } Token Current { get; } bool MoveNext(); bool MoveNextWithoutConsuming(); void ConsumeCurrent(); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] [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; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public override string ToString() { return $"Line: {Line}, Col: {Column}, Idx: {Index}"; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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())); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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; } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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) { } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal sealed class MergingParser : IParser { [Nullable(0)] 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([Nullable(new byte[] { 2, 1 })] 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; } } } } [Nullable(0)] private sealed class ParsingEventCloner : IParsingEventVisitor { [Nullable(2)] 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; [Nullable(2)] public ParsingEvent Current { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] get { return 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([Nullable(new byte[] { 2, 1 })] 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, [Nullable(new byte[] { 2, 1 })] 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([<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] (ParsingEvent e) => (nesting += e.NestingIncrease) >= 0) select cloner.Clone(e); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal class Parser : IParser { [Nullable(0)] 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; [Nullable(2)] private Token currentToken; [Nullable(2)] private VersionDirective version; private readonly EventQueue pendingEvents = new EventQueue(); [Nullable(2)] [field: Nullable(2)] public ParsingEvent Current { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] get; [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] private set; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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; } [return: Nullable(2)] 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); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal static class ParserExtensions { public static T Consume<[Nullable(0)] T>(this IParser parser) where T : ParsingEvent { T result = parser.Require(); parser.MoveNext(); return result; } public static bool TryConsume<[Nullable(0)] T>(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<[Nullable(0)] T>(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<[Nullable(0)] T>(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<[Nullable(0)] T>(this IParser parser) where T : ParsingEvent { return parser.Consume(); } [Obsolete("Please use TryConsume(out var evt) instead")] [return: MaybeNull] [return: Nullable(2)] public static T Allow<[Nullable(0)] T>(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] [return: Nullable(2)] public static T Peek<[Nullable(0)] T>(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<[Nullable(0)] T>(this IParser parser) where T : ParsingEvent { T @event; return parser.Accept(out @event); } } 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 } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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; [Nullable(2)] private Token previous; [Nullable(2)] private Anchor previousAnchor; [Nullable(2)] private YamlDotNet.Core.Tokens.Scalar lastScalar; private static readonly byte[] EmptyBytes = new byte[0]; public bool SkipComments { get; private set; } [Nullable(2)] [field: Nullable(2)] public Token Current { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] get; [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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([Nullable(2)] 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); } } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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) { } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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 { [Nullable(1)] private readonly string value; public int Position { get; private set; } public int Length => value.Length; public bool EndOfInput => IsOutside(Position); [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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) { } } [Nullable(new byte[] { 0, 1, 1 })] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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)); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal readonly struct TagName : IEquatable { public static readonly TagName Empty; [Nullable(2)] 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); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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()); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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, [Nullable(2)] 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) { } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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) { } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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) { } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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) { } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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"); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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) { } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] 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 { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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 + "]"; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(2)] [Nullable(0)] 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) { } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public override string ToString() { return $"Document start [isImplicit = {IsImplicit}]"; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum EventType { None, StreamStart, StreamEnd, DocumentStart, DocumentEnd, Alias, Scalar, SequenceStart, SequenceEnd, MappingStart, MappingEnd, Comment } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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); } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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; } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public abstract void Accept(IParsingEventVisitor visitor); internal ParsingEvent(in Mark start, in Mark end) { Start = start; End = end; } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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); } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] 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 } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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); } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] 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 { [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal sealed class Lazy<[Nullable(2)] T> { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] private enum ValueState { NotCreated, Creating, Created } private T value; [Nullable(new byte[] { 2, 1 })] private Func valueFactory; [Nullable(0)] private ValueState valueState; private readonly bool isThreadSafe; public T Value { get { if (isThreadSafe) { lock (this) { return ComputeValue(); } } return ComputeValue(); } } public Lazy(T value) { this.value = value; valueState = ValueState.Created; } public Lazy(Func valueFactory) { this.valueFactory = valueFactory; isThreadSafe = false; valueState = ValueState.NotCreated; } public Lazy(Func valueFactory, bool isThreadSafe) { this.valueFactory = valueFactory; this.isThreadSafe = isThreadSafe; valueState = ValueState.NotCreated; value = default(T); } private T ComputeValue() { switch (valueState) { case ValueState.NotCreated: valueState = ValueState.Creating; value = valueFactory(); valueState = ValueState.Created; valueFactory = null; break; case ValueState.Creating: throw new InvalidOperationException("ValueFactory attempted to access the Value property of this instance."); } return value; } } [Nullable(0)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal struct ValueTuple<[Nullable(2)] T1, [Nullable(2)] T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } } namespace System.Runtime.CompilerServices { internal sealed class TupleElementNamesAttribute : Attribute { [Nullable(new byte[] { 1, 2 })] [field: Nullable(new byte[] { 1, 2 })] public IList TransformNames { [return: Nullable(new byte[] { 1, 2 })] get; } public TupleElementNamesAttribute([Nullable(new byte[] { 1, 2 })] string[] transformNames) { TransformNames = transformNames; } } } namespace System.Linq { internal static class Enumerable2 { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public static IEnumerable Zip<[Nullable(2)] TFirst, [Nullable(2)] TSecond, [Nullable(2)] TResult>(this IEnumerable first, IEnumerable second, Func resultSelector) { using IEnumerator firstEnumerator = first.GetEnumerator(); using IEnumerator secondEnumerator = second.GetEnumerator(); while (firstEnumerator.MoveNext() && secondEnumerator.MoveNext()) { yield return resultSelector(firstEnumerator.Current, secondEnumerator.Current); } } } } namespace System.Collections.Concurrent { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] internal sealed class ConcurrentDictionary<[Nullable(2)] TKey, [Nullable(2)] TValue> { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(0)] public delegate TValue ValueFactory(TKey key); private readonly Dictionary entries = new Dictionary(); public TValue GetOrAdd(TKey key, [Nullable(new byte[] { 1, 0, 0 })] ValueFactory valueFactory) { lock (entries) { if (!entries.TryGetValue(key, out var value)) { value = valueFactory(key); entries.Add(key, value); } return value; } } public bool TryAdd(TKey key, TValue value) { lock (entries) { if (!entries.ContainsKey(key)) { entries.Add(key, value); return true; } return false; } } public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { lock (entries) { return entries.TryGetValue(key, out value); } } } } namespace System.Collections.Generic { internal static class DeconstructionExtensions { [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] public static void Deconstruct<[Nullable(2)] TKey, [Nullable(2)] TValue>([Nullable(new byte[] { 0, 1, 1 })] this KeyValuePair pair, out TKey key, out TValue value) { key = pair.Key; value = pair.Value; } } internal interface IReadOnlyCollection<[Nullable(2)] T> : IEnumerable, IEnumerable { int Count { get; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IReadOnlyDictionaryNullable(2)] TValue> : IEnumerable>, IEnumerable, IReadOnlyCollection> { TValue this[TKey key] { get; } IEnumerable Keys { get; } IEnumerable Values { get; } bool ContainsKey(TKey key); bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value); } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] internal interface IReadOnlyList<[Nullable(2)] T> : IEnumerable, IEnumerable, IReadOnlyCollection { T this[int index] { get; } } } namespace System.Diagnostics.CodeAnalysis { [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [DebuggerNonUserCode] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [DebuggerNonUserCode] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] [DebuggerNonUserCode] internal sealed class MaybeNullAttribute : Attribute { } [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [Nullable(0)] 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; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [Nullable(0)] [DebuggerNonUserCode] 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; } } [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [DebuggerNonUserCode] [<3519a4e3-ad03-44db-a068-700588bcd149>NullableContext(1)] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] [Nullable(0)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [DebuggerNonUserCode] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [Microsoft.CodeAnalysis.Embedded] 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; } } [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } internal static class AnimationSpeedManager { public delegate double Handler(Character character, double speed); private static readonly Harmony harmony = new Harmony("AnimationSpeedManager"); private static bool hasMarkerPatch = false; private static readonly MethodInfo method = AccessTools.DeclaredMethod(typeof(CharacterAnimEvent), "CustomFixedUpdate", (Type[])null, (Type[])null); private static int index = 0; private static bool changed = false; private static Handler[][] handlers = Array.Empty(); private static readonly Dictionary> handlersPriorities = new Dictionary>(); [PublicAPI] public static void Add(Handler handler, int priority = 400) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown if (!hasMarkerPatch) { harmony.Patch((MethodBase)method, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(AnimationSpeedManager), "markerPatch", (Type[])null, (Type[])null)), (HarmonyMethod)null); hasMarkerPatch = true; } if (!handlersPriorities.TryGetValue(priority, out List value)) { handlersPriorities.Add(priority, value = new List()); harmony.Patch((MethodBase)method, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(AnimationSpeedManager), "wrapper", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } value.Add(handler); handlers = (from kv in handlersPriorities orderby kv.Key select kv.Value.ToArray()).ToArray(); } private static void wrapper(Character ___m_character, Animator ___m_animator) { Character ___m_character2 = ___m_character; double num = (double)___m_animator.speed * 10000000.0 % 100.0; if ((!(num > 10.0) || !(num < 30.0)) && !(___m_animator.speed <= 0.001f)) { double num2 = ___m_animator.speed; double num3 = handlers[index++].Aggregate(num2, (double current, Handler handler) => handler(___m_character2, current)); if (num3 != num2) { ___m_animator.speed = (float)(num3 - num3 % 1E-05); changed = true; } } } private static void markerPatch(Animator ___m_animator) { if (changed) { double num = (double)___m_animator.speed * 10000000.0 % 100.0; if ((num < 10.0 || num > 30.0) ? true : false) { ___m_animator.speed += 1.9E-06f; } changed = false; } index = 0; } }