Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of BetterStations v1.0.7
BetterStations.dll
Decompiled 7 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BetterStations.Functions; using HarmonyLib; using JetBrains.Annotations; using LocalizationManager; using Microsoft.CodeAnalysis; using PieceManager; using ServerSync; using TMPro; using UnityEngine; using UnityEngine.UI; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("BetterStations")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.7")] [assembly: AssemblyInformationalVersion("1.0.7")] [assembly: AssemblyProduct("BetterStations")] [assembly: AssemblyTitle("BetterStations")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.7.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } public class BetterFermenter : MonoBehaviour, Hoverable { [Serializable] public class ItemConversion { public ItemDrop m_from; public ItemDrop m_to; public int m_produceItems = 4; } public enum Status { Empty, Fermenting, Exposed, Ready } public const float updateDT = 2f; public string m_name = "Fermentation barrel"; public float m_fermentationDuration = 2400f; public GameObject m_fermentingObject; public GameObject m_readyObject; public GameObject m_topObject; public EffectList m_addedEffects = new EffectList(); public EffectList m_tapEffects = new EffectList(); public EffectList m_spawnEffects = new EffectList(); public float m_tapDelay = 1.5f; public Transform m_outputPoint; public Transform m_roofCheckPoint; private List<ItemConversion> m_conversion = new List<ItemConversion>(); private ZNetView m_nview; public Container m_container; private float m_updateCoverTimer; private bool m_exposed; private bool m_hasRoof; private string m_delayedTapItem = ""; public void Awake() { m_nview = ((Component)this).GetComponent<ZNetView>(); m_fermentingObject.SetActive(false); m_readyObject.SetActive(false); m_topObject.SetActive(true); if (!((Object)(object)m_nview == (Object)null) && m_nview.GetZDO() != null) { SetConversion(); m_nview.Register<string>("RPC_AddItem", (Action<long, string>)RPC_AddItem); m_nview.Register("RPC_Tap", (Action<long>)RPC_Tap); ((MonoBehaviour)this).InvokeRepeating("SlowUpdate", (GetStatus() == Status.Fermenting) ? 2f : 0f, 2f); WearNTear component = ((Component)this).GetComponent<WearNTear>(); if (Object.op_Implicit((Object)(object)component)) { component.m_onDestroyed = (Action)Delegate.Combine(component.m_onDestroyed, new Action(OnDestroyed)); } } } public void SetConversion() { m_conversion.Clear(); m_conversion.AddRange(new List<ItemConversion> { new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseHealthMinor").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadHealthMinor").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseHealthMedium").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadHealthMedium").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseStaminaMinor").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadStaminaMinor").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseStaminaMedium").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadStaminaMedium").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBasePoisonResist").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadPoisonResist").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseFrostResist").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadFrostResist").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("BarleyWineBase").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("BarleyWine").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseTasty").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadTasty").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseHealthMajor").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadHealthMajor").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseStaminaLingering").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadStaminaLingering").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseEitrMinor").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadEitrMinor").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseEitrLingering").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadEitrLingering").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseHealthLingering").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadHealthLingering").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseBzerker").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadBzerker").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseStrength").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadStrength").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseHasty").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadHasty").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseLightFoot").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadLightfoot").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseSwimmer").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadSwimmer").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseTamer").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadTamer").GetComponent<ItemDrop>(), m_produceItems = 6 }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("MeadBaseBugRepellent").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("MeadBugRepellent").GetComponent<ItemDrop>(), m_produceItems = 6 } }); } public void DropAllItems() { Status status = GetStatus(); string content = GetContent(); if (string.IsNullOrEmpty(content)) { return; } if (status == Status.Ready) { ItemConversion itemConversion = GetItemConversion(content); if (itemConversion != null) { for (int i = 0; i < itemConversion.m_produceItems; i++) { drop(itemConversion.m_to); } } } else { GameObject prefab = ZNetScene.instance.GetPrefab(content); if ((Object)(object)prefab != (Object)null) { ItemDrop component = prefab.GetComponent<ItemDrop>(); if (Object.op_Implicit((Object)(object)component)) { drop(component); } } } m_nview.GetZDO().Set(ZDOVars.s_content, ""); m_nview.GetZDO().Set(ZDOVars.s_startTime, 0, false); void drop(ItemDrop item) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_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_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) Vector3 val = ((Component)this).transform.position + Vector3.up + Random.insideUnitSphere * 0.3f; Quaternion val2 = Quaternion.Euler(0f, (float)Random.Range(0, 360), 0f); ItemDrop.OnCreateNew(Object.Instantiate<GameObject>(((Component)item).gameObject, val, val2)); } } public void OnDestroyed() { m_nview.IsOwner(); } public string GetHoverName() { return m_name; } public string GetHoverText() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (!PrivateArea.CheckAccess(((Component)this).transform.position, 0f, false, false)) { return Localization.instance.Localize(m_name + "\n$piece_noaccess"); } switch (GetStatus()) { case Status.Ready: { string contentName2 = GetContentName(); return Localization.instance.Localize(m_name + "\n( " + contentName2 + ", $piece_fermenter_ready )"); } case Status.Fermenting: { string contentName = GetContentName(); if (!m_hasRoof) { return Localization.instance.Localize(m_name + " ( $piece_fermenter_needroof )\n( " + contentName + " )"); } if (m_exposed) { return Localization.instance.Localize(m_name + " ( $piece_fermenter_exposed )\n( " + contentName + " )"); } if (!m_container.GetInventory().HaveEmptySlot()) { return Localization.instance.Localize(m_name + " ( $bbs_storagefull )\n( " + contentName + " )"); } return Localization.instance.Localize(m_name + " ( $piece_fermenter_fermenting )\n( " + contentName + " ) <color=orange>" + TimeLeft() + "</color>"); } case Status.Empty: { string text = "$bbs_standby"; if (!m_hasRoof) { text += ", $piece_fermenter_needroof"; } else if (m_exposed) { text += ", $piece_fermenter_exposed"; } else if (!m_container.GetInventory().HaveEmptySlot()) { text += ", $bbs_storagefull"; } return Localization.instance.Localize(m_name + " ( " + text + " )"); } default: return m_name; } } public void SlowUpdate() { UpdateCover(2f); switch (GetStatus()) { case Status.Empty: m_fermentingObject.SetActive(false); m_readyObject.SetActive(false); m_topObject.SetActive(false); if (!((Object)(object)m_nview == (Object)null) && m_nview.GetZDO().IsValid() && m_nview.GetZDO().IsOwner() && Object.op_Implicit((Object)(object)Player.m_localPlayer) && !m_readyObject.activeSelf && !m_fermentingObject.activeSelf && !m_topObject.activeSelf) { UpdateCover(0f); ItemData val = FindCookableItem(m_container.GetInventory()); int num = DeductItemFromContainer(val); if (val != null && num != 0 && m_container.GetInventory().HaveEmptySlot()) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(((Object)val.m_dropPrefab).name); m_nview.InvokeRPC("RPC_AddItem", new object[1] { ((Object)itemPrefab).name }); } } break; case Status.Fermenting: m_readyObject.SetActive(false); m_topObject.SetActive(true); m_fermentingObject.SetActive(!m_exposed && m_hasRoof && m_container.GetInventory().HaveEmptySlot()); break; case Status.Ready: m_fermentingObject.SetActive(false); m_readyObject.SetActive(true); m_topObject.SetActive(true); if (m_readyObject.activeSelf && m_topObject.activeSelf && !m_fermentingObject.activeSelf && m_container.GetInventory().HaveEmptySlot()) { UpdateCover(0f); m_nview.InvokeRPC("RPC_Tap", Array.Empty<object>()); } break; case Status.Exposed: break; } } private Status GetStatus() { if (string.IsNullOrEmpty(GetContent())) { return Status.Empty; } if (GetFermentationTime() > (double)m_fermentationDuration) { return Status.Ready; } return Status.Fermenting; } public void RPC_AddItem(long sender, string name) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) if (m_nview.IsOwner() && GetStatus() == Status.Empty) { if (!IsItemAllowed(name)) { ZLog.DevLog((object)"Item not allowed"); return; } m_addedEffects.Create(((Component)this).transform.position, ((Component)this).transform.rotation, (Transform)null, 1f, -1); m_nview.GetZDO().Set(ZDOVars.s_content, name); m_nview.GetZDO().Set(ZDOVars.s_startTime, ZNet.instance.GetTime().Ticks); } } public void RPC_Tap(long sender) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) if (m_nview.IsOwner() && GetStatus() == Status.Ready) { m_delayedTapItem = GetContent(); ((MonoBehaviour)this).Invoke("DelayedTap", m_tapDelay); m_tapEffects.Create(((Component)this).transform.position, ((Component)this).transform.rotation, (Transform)null, 1f, -1); m_nview.GetZDO().Set(ZDOVars.s_content, ""); m_nview.GetZDO().Set(ZDOVars.s_startTime, 0, false); } } public void DelayedTap() { //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_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_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: 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_0078: Unknown result type (might be due to invalid IL or missing references) m_spawnEffects.Create(((Component)m_outputPoint).transform.position, Quaternion.identity, (Transform)null, 1f, -1); ItemConversion itemConversion = GetItemConversion(m_delayedTapItem); if (itemConversion == null) { return; } for (int i = 0; i < itemConversion.m_produceItems; i++) { Vector3 val = m_outputPoint.position + Vector3.up * 0.3f; ZNetView.m_forceDisableInit = true; ItemDrop component = Object.Instantiate<GameObject>(((Component)itemConversion.m_to).gameObject, val, m_outputPoint.rotation).GetComponent<ItemDrop>(); ZNetView.m_forceDisableInit = false; if (m_container.GetInventory().AddItem(component.m_itemData)) { m_container.Save(); m_container.GetInventory().Changed(); Object.Destroy((Object)(object)((Component)component).gameObject); continue; } break; } } public void ResetFermentationTimer() { if (GetStatus() == Status.Fermenting) { m_nview.GetZDO().Set(ZDOVars.s_startTime, ZNet.instance.GetTime().Ticks); } } private double GetFermentationTime() { DateTime dateTime = new DateTime(m_nview.GetZDO().GetLong(ZDOVars.s_startTime, 0L)); if (dateTime.Ticks == 0L) { return -1.0; } return (ZNet.instance.GetTime() - dateTime).TotalSeconds; } private string GetContentName() { string content = GetContent(); if (string.IsNullOrEmpty(content)) { return ""; } ItemConversion itemConversion = GetItemConversion(content); if (itemConversion == null) { return "Invalid"; } return itemConversion.m_from.m_itemData.m_shared.m_name; } private string GetContent() { if (m_nview.GetZDO() != null) { return m_nview.GetZDO().GetString(ZDOVars.s_content, ""); } return ""; } public void UpdateCover(float dt, bool forceUpdate = false) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) m_updateCoverTimer -= dt; if (m_updateCoverTimer <= 0f || forceUpdate) { m_updateCoverTimer = 10f; float num = default(float); bool hasRoof = default(bool); Cover.GetCoverForPoint(m_roofCheckPoint.position, ref num, ref hasRoof, 0.5f); m_exposed = num < 0.7f; m_hasRoof = hasRoof; if ((m_exposed || !m_hasRoof) && m_nview.IsOwner() && !m_container.GetInventory().HaveEmptySlot()) { ResetFermentationTimer(); } } } public bool IsItemAllowed(ItemData item) { return IsItemAllowed(((Object)item.m_dropPrefab).name); } private bool IsItemAllowed(string itemName) { return Enumerable.Any(m_conversion, (ItemConversion item) => ((Object)((Component)item.m_from).gameObject).name == itemName); } private ItemData FindCookableItem(Inventory inventory) { return Enumerable.FirstOrDefault(Enumerable.Select(m_conversion, (ItemConversion item2) => inventory.GetItem(item2.m_from.m_itemData.m_shared.m_name, -1, false)), (Func<ItemData, bool>)((ItemData item) => item != null)); } private ItemConversion GetItemConversion(string itemName) { return Enumerable.FirstOrDefault(m_conversion, (ItemConversion item) => ((Object)((Component)item.m_from).gameObject).name == itemName); } private bool ContainerContainsItem(ItemData ItemData) { return Enumerable.Any(m_container.GetInventory().GetAllItems(), (ItemData item) => item != null && item.m_shared.m_name == ItemData?.m_shared.m_name); } private int DeductItemFromContainer(ItemData itemData, int amount = 1) { if (!ContainerContainsItem(itemData)) { return 0; } int num = 0; List<ItemData> allItems = m_container.GetInventory().GetAllItems(); foreach (ItemData item in Enumerable.Where(allItems, (ItemData item) => item != null && item.m_shared.m_name == itemData?.m_shared.m_name)) { int num2 = Mathf.Min(item.m_stack, amount); item.m_stack -= num2; amount -= num2; num += num2; if (amount <= 0) { break; } } if (num == 0) { return 0; } allItems.RemoveAll((ItemData x) => x.m_stack <= 0); m_container.m_inventory.m_inventory = allItems; m_container.Save(); m_container.GetInventory().Changed(); return num; } private string TimeLeft() { double num = (double)m_fermentationDuration - GetFermentationTime(); float num2 = Mathf.FloorToInt((float)((int)num / 60)); float num3 = Mathf.FloorToInt((float)((int)num % 60)); return $"[ {num2:00}:{num3:00} ]"; } } public class BetterSmelter : MonoBehaviour, Hoverable { [Serializable] public class ItemConversion { public ItemDrop m_from; public ItemDrop m_to; } public string m_name = "Better Smelter"; public Transform m_outputPoint; public Transform m_roofCheckPoint; public GameObject m_enabledObject; public GameObject m_disabledObject; public GameObject m_haveFuelObject; public GameObject m_haveOreObject; public GameObject m_noOreObject; public Animator[] m_animators; private ItemDrop m_fuelItem; public int m_maxOre = 10; public int m_maxFuel = 10; public int m_fuelPerProduct = 4; public float m_secPerProduct = 10f; public bool m_requiresRoof; public BetterWindmill m_windmill; public float m_addOreAnimationDuration; private readonly List<ItemConversion> m_conversion = new List<ItemConversion>(); public EffectList m_oreAddedEffects = new EffectList(); public EffectList m_fuelAddedEffects = new EffectList(); public EffectList m_produceEffects = new EffectList(); private ZNetView m_nview; public Container m_container; private bool m_haveRoof; private float m_addedOreTime = -1000f; private Piece m_piece; public void Awake() { m_nview = ((Component)this).GetComponent<ZNetView>(); m_piece = ((Component)this).GetComponent<Piece>(); if ((Object)(object)m_nview == (Object)null) { m_nview = ((Component)this).GetComponentInParent<ZNetView>(); } if (!((Object)(object)m_nview == (Object)null) && m_nview.GetZDO() != null) { SetConversion(); m_nview.Register<string>("RPC_AddOre", (Action<long, string>)RPC_AddOre); m_nview.Register("RPC_AddFuel", (Action<long>)RPC_AddFuel); m_nview.Register("RPC_EmptyProcessed", (Action<long>)RPC_EmptyProcessed); WearNTear component = ((Component)this).GetComponent<WearNTear>(); if (Object.op_Implicit((Object)(object)component)) { component.m_onDestroyed = (Action)Delegate.Combine(component.m_onDestroyed, new Action(OnDestroyed)); } ((MonoBehaviour)this).InvokeRepeating("UpdateSmelter", 1f, 1f); } } public void SetConversion() { if (((Object)((Component)this).gameObject).name.Contains("Kiln")) { m_conversion.Clear(); m_conversion.AddRange(new List<ItemConversion> { new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("Blackwood").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("Coal").GetComponent<ItemDrop>() }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("ElderBark").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("Coal").GetComponent<ItemDrop>() }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("FineWood").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("Coal").GetComponent<ItemDrop>() }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("RoundLog").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("Coal").GetComponent<ItemDrop>() }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("Wood").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("Coal").GetComponent<ItemDrop>() }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("YggdrasilWood").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("Coal").GetComponent<ItemDrop>() } }); } else if (((Object)((Component)this).gameObject).name.Contains("OreSmelter")) { m_fuelItem = ObjectDB.instance.GetItemPrefab("Coal").GetComponent<ItemDrop>(); m_conversion.Clear(); m_conversion.AddRange(new List<ItemConversion> { new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("CopperOre").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("Copper").GetComponent<ItemDrop>() }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("IronOre").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("Iron").GetComponent<ItemDrop>() }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("IronScrap").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("Iron").GetComponent<ItemDrop>() }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("BronzeScrap").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("Bronze").GetComponent<ItemDrop>() }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("TinOre").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("Tin").GetComponent<ItemDrop>() }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("SilverOre").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("Silver").GetComponent<ItemDrop>() }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("CopperScrap").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("Copper").GetComponent<ItemDrop>() }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("FlametalOreNew").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("FlametalNew").GetComponent<ItemDrop>() }, new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("BlackMetalScrap").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("BlackMetal").GetComponent<ItemDrop>() } }); } else if (((Object)((Component)this).gameObject).name.Contains("EitrRefinery")) { m_fuelItem = ObjectDB.instance.GetItemPrefab("Sap").GetComponent<ItemDrop>(); m_conversion.Clear(); m_conversion.Add(new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("Softtissue").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("Eitr").GetComponent<ItemDrop>() }); } else if (((Object)((Component)this).gameObject).name.Contains("SpinningWheel")) { m_conversion.Clear(); m_conversion.Add(new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("Flax").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("LinenThread").GetComponent<ItemDrop>() }); } else if (((Object)((Component)this).gameObject).name.Contains("Windmill")) { m_conversion.Clear(); m_conversion.Add(new ItemConversion { m_from = ObjectDB.instance.GetItemPrefab("Barley").GetComponent<ItemDrop>(), m_to = ObjectDB.instance.GetItemPrefab("BarleyFlour").GetComponent<ItemDrop>() }); } } public string GetHoverText() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (!PrivateArea.CheckAccess(((Component)this).transform.position, 0f, false, false)) { return Localization.instance.Localize(m_name + "\n$piece_noaccess"); } if (m_requiresRoof && !m_haveRoof) { return Localization.instance.Localize(m_name + "\n$bbs_needsroof"); } if (!m_container.GetInventory().HaveEmptySlot()) { return Localization.instance.Localize(m_name + "\n$bbs_storagefull"); } if (((Object)((Component)this).gameObject).name.Contains("Kiln") || ((Object)((Component)this).gameObject).name.Contains("SpinningWheel") || ((Object)((Component)this).gameObject).name.Contains("Windmill")) { if (GetQueueSize() > 0) { return Localization.instance.Localize($"{m_name}\n$bbs_processing ( <color=orange>{GetQueuedOre()}</color> x {GetQueueSize()} / {m_maxOre} ) <color=orange>[ {TimeLeft()} ]</color>"); } } else if (((Object)((Component)this).gameObject).name.Contains("OreSmelter") || ((Object)((Component)this).gameObject).name.Contains("EitrRefinery")) { string name = m_fuelItem.m_itemData.m_shared.m_name; if (GetQueueSize() > 0 || GetFuel() > 0f) { return Localization.instance.Localize($"{m_name}\n$bbs_processing\n( <color=orange>{GetQueuedOre()}</color> x {GetQueueSize()} / {m_maxOre} ) <color=orange>[ {TimeLeft()} ]</color>\n( <color=orange>{name}</color> x {Mathf.Ceil(GetFuel())} / {m_maxFuel} )"); } } return Localization.instance.Localize(m_name); } public string GetHoverName() { return m_name; } public void DropAllItems() { //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0069: 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_0073: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_009b: 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) SpawnProcessed(); if ((Object)(object)m_fuelItem != (Object)null) { float num = ((m_nview.GetZDO() == null) ? 0f : m_nview.GetZDO().GetFloat(ZDOVars.s_fuel, 0f)); for (int i = 0; i < (int)num; i++) { Vector3 val = ((Component)this).transform.position + Vector3.up + Random.insideUnitSphere * 0.3f; Quaternion val2 = Quaternion.Euler(0f, (float)Random.Range(0, 360), 0f); ItemDrop.OnCreateNew(Object.Instantiate<GameObject>(((Component)m_fuelItem).gameObject, val, val2)); } } while (GetQueueSize() > 0) { string queuedOre = GetQueuedOre(); RemoveOneOre(); ItemConversion itemConversion = GetItemConversion(queuedOre); if (itemConversion != null) { Vector3 val3 = ((Component)this).transform.position + Vector3.up + Random.insideUnitSphere * 0.3f; Quaternion val4 = Quaternion.Euler(0f, (float)Random.Range(0, 360), 0f); ItemDrop.OnCreateNew(Object.Instantiate<GameObject>(((Component)itemConversion.m_from).gameObject, val3, val4)); } } } public void OnDestroyed() { if (m_nview.IsOwner()) { DropAllItems(); } } public bool IsItemAllowed(ItemData item) { return IsItemAllowed(((Object)item.m_dropPrefab).name); } private bool IsItemAllowed(string itemName) { return Enumerable.Any(m_conversion, (ItemConversion item) => ((Object)((Component)item.m_from).gameObject).name == itemName); } public ItemData FindCookableItem(Inventory inventory) { return Enumerable.FirstOrDefault(Enumerable.Select(m_conversion, (ItemConversion item2) => inventory.GetItem(item2.m_from.m_itemData.m_shared.m_name, -1, false)), (Func<ItemData, bool>)((ItemData item) => item != null)); } private float GetBakeTimer() { if (m_nview.IsValid()) { return m_nview.GetZDO().GetFloat(ZDOVars.s_bakeTimer, 0f); } return 0f; } public void SetBakeTimer(float t) { if (m_nview.IsValid()) { m_nview.GetZDO().Set(ZDOVars.s_bakeTimer, t); } } private float GetFuel() { if (m_nview.IsValid()) { return m_nview.GetZDO().GetFloat(ZDOVars.s_fuel, 0f); } return 0f; } public void SetFuel(float fuel) { if (m_nview.IsValid()) { m_nview.GetZDO().Set(ZDOVars.s_fuel, fuel); } } private int GetQueueSize() { if (m_nview.IsValid()) { return m_nview.GetZDO().GetInt(ZDOVars.s_queued, 0); } return 0; } public void RPC_AddOre(long sender, string name) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) if (m_nview.IsOwner()) { if (!IsItemAllowed(name)) { ZLog.Log((object)("Item not allowed " + name)); return; } QueueOre(name); m_oreAddedEffects.Create(((Component)this).transform.position, ((Component)this).transform.rotation, (Transform)null, 1f, -1); ZLog.Log((object)("Added ore " + name)); } } public void QueueOre(string name) { int queueSize = GetQueueSize(); m_nview.GetZDO().Set("item" + queueSize, name); m_nview.GetZDO().Set(ZDOVars.s_queued, queueSize + 1, false); } private string GetQueuedOre() { if (GetQueueSize() != 0) { return m_nview.GetZDO().GetString(ZDOVars.s_item0, ""); } return ""; } public void RemoveOneOre() { int queueSize = GetQueueSize(); if (queueSize != 0) { for (int i = 0; i < queueSize; i++) { string @string = m_nview.GetZDO().GetString("item" + (i + 1), ""); m_nview.GetZDO().Set("item" + i, @string); } m_nview.GetZDO().Set(ZDOVars.s_queued, queueSize - 1, false); } } public void RPC_EmptyProcessed(long sender) { if (m_nview.IsOwner()) { SpawnProcessed(); } } public void RPC_AddFuel(long sender) { //IL_002e: 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) if (m_nview.IsOwner()) { float fuel = GetFuel(); SetFuel(fuel + 1f); m_fuelAddedEffects.Create(((Component)this).transform.position, ((Component)this).transform.rotation, ((Component)this).transform, 1f, -1); } } private double GetDeltaTime() { DateTime time = ZNet.instance.GetTime(); DateTime dateTime = new DateTime(m_nview.GetZDO().GetLong(ZDOVars.s_startTime, time.Ticks)); double totalSeconds = (time - dateTime).TotalSeconds; m_nview.GetZDO().Set(ZDOVars.s_startTime, time.Ticks); return totalSeconds; } private float GetAccumulator() { if (m_nview.IsValid()) { return m_nview.GetZDO().GetFloat(ZDOVars.s_accTime, 0f); } return 0f; } public void SetAccumulator(float t) { if (m_nview.IsValid()) { m_nview.GetZDO().Set(ZDOVars.s_accTime, t); } } public void UpdateRoof() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (m_requiresRoof) { m_haveRoof = Cover.IsUnderRoof(m_roofCheckPoint.position); } } public void UpdateSmelter() { if (!m_nview.IsValid()) { return; } UpdateRoof(); UpdateState(); if (!m_nview.IsOwner()) { return; } double deltaTime = GetDeltaTime(); float accumulator = GetAccumulator(); accumulator += (float)deltaTime; if (accumulator > 3600f) { accumulator = 3600f; } float num = (Object.op_Implicit((Object)(object)m_windmill) ? m_windmill.GetPowerOutput() : 1f); int num2 = m_maxOre - GetQueueSize(); if (m_maxFuel - (int)Math.Ceiling(GetFuel()) > 0) { ItemData itemData = m_fuelItem.m_itemData; int num3 = DeductItemFromContainer(itemData); for (int i = 0; i < num3; i++) { m_nview.InvokeRPC("RPC_AddFuel", Array.Empty<object>()); } } if (num2 > 0) { foreach (ItemConversion item in m_conversion) { ItemData itemData2 = item.m_from.m_itemData; int num4 = DeductItemFromContainer(itemData2); if (num4 > 0) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(((Object)((Component)item.m_from).gameObject).name); for (int j = 0; j < num4; j++) { m_nview.InvokeRPC("RPC_AddOre", new object[1] { ((Object)itemPrefab).name }); } num2 -= num4; } } } while (accumulator >= 1f) { accumulator -= 1f; float fuel = GetFuel(); string queuedOre = GetQueuedOre(); if ((m_maxFuel != 0 && !(fuel > 0f)) || (m_maxOre != 0 && queuedOre == "") || !(m_secPerProduct > 0f) || (m_requiresRoof && !m_haveRoof) || !m_container.GetInventory().HaveEmptySlot()) { continue; } float num5 = 1f * num; if (m_maxFuel > 0) { float num6 = m_secPerProduct / (float)m_fuelPerProduct; fuel -= num5 / num6; if (fuel < 0.0001f) { fuel = 0f; } SetFuel(fuel); } if (queuedOre != "") { float bakeTimer = GetBakeTimer(); bakeTimer += num5; SetBakeTimer(bakeTimer); if (bakeTimer >= m_secPerProduct) { SetBakeTimer(0f); RemoveOneOre(); QueueProcessed(queuedOre); } } } if (GetQueuedOre() == "" || ((float)m_maxFuel > 0f && GetFuel() == 0f)) { SpawnProcessed(); } SetAccumulator(accumulator); } public void QueueProcessed(string ore) { Spawn(ore, 1); } public void SpawnProcessed() { if (m_nview.IsValid()) { int @int = m_nview.GetZDO().GetInt(ZDOVars.s_spawnAmount, 0); if (@int > 0) { string @string = m_nview.GetZDO().GetString(ZDOVars.s_spawnOre, ""); Spawn(@string, @int); m_nview.GetZDO().Set(ZDOVars.s_spawnOre, ""); m_nview.GetZDO().Set(ZDOVars.s_spawnAmount, 0, false); } } } public int GetProcessedQueueSize() { if (m_nview.IsValid()) { return m_nview.GetZDO().GetInt(ZDOVars.s_spawnAmount, 0); } return 0; } public void Spawn(string ore, int stack) { //IL_0026: 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_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) ItemConversion itemConversion = GetItemConversion(ore); if (itemConversion != null && !((Object)(object)itemConversion.m_to == (Object)null)) { m_produceEffects.Create(((Component)this).transform.position, ((Component)this).transform.rotation, (Transform)null, 1f, -1); ZNetView.m_forceDisableInit = true; ItemDrop component = Object.Instantiate<GameObject>(((Component)itemConversion.m_to).gameObject, m_outputPoint.position, m_outputPoint.rotation).GetComponent<ItemDrop>(); ZNetView.m_forceDisableInit = false; component.m_itemData.m_stack = stack; if (m_container.GetInventory().AddItem(component.m_itemData)) { m_produceEffects.Create(((Component)this).transform.position, ((Component)this).transform.rotation, (Transform)null, 1f, -1); m_container.Save(); m_container.GetInventory().Changed(); Object.Destroy((Object)(object)((Component)component).gameObject); } } } private ItemConversion GetItemConversion(string itemName) { return Enumerable.FirstOrDefault(m_conversion, (ItemConversion item) => ((Object)((Component)item.m_from).gameObject).name == itemName); } public void UpdateState() { bool flag = IsActive(); m_enabledObject.SetActive(flag); if (Object.op_Implicit((Object)(object)m_disabledObject)) { m_disabledObject.SetActive(!flag); } if (Object.op_Implicit((Object)(object)m_haveFuelObject)) { m_haveFuelObject.SetActive(GetFuel() > 0f); } if (Object.op_Implicit((Object)(object)m_haveOreObject)) { m_haveOreObject.SetActive(GetQueueSize() > 0); } if (Object.op_Implicit((Object)(object)m_noOreObject)) { m_noOreObject.SetActive(GetQueueSize() == 0); } if (m_addOreAnimationDuration > 0f && Time.time - m_addedOreTime < m_addOreAnimationDuration) { flag = true; } SetAnimation(flag); } public void SetAnimation(bool active) { Animator[] animators = m_animators; foreach (Animator val in animators) { if (((Component)val).gameObject.activeInHierarchy) { val.SetBool("active", active); val.SetFloat("activef", active ? 1f : 0f); } } } public bool IsActive() { if ((m_maxFuel == 0 || GetFuel() > 0f) && (m_maxOre == 0 || GetQueueSize() > 0) && (!m_requiresRoof || m_haveRoof)) { return m_container.GetInventory().HaveEmptySlot(); } return false; } private bool ContainerContainsItem(ItemData itemData) { return Enumerable.Any(m_container.GetInventory().GetAllItems(), (ItemData item) => item.m_shared.m_name == itemData.m_shared.m_name); } private int DeductItemFromContainer(ItemData itemData, int amount = 1) { if (!ContainerContainsItem(itemData)) { return 0; } int num = 0; List<ItemData> allItems = m_container.GetInventory().GetAllItems(); foreach (ItemData item in Enumerable.Where(allItems, (ItemData item) => item.m_shared.m_name == itemData.m_shared.m_name)) { int num2 = Mathf.Min(item.m_stack, amount); item.m_stack -= num2; amount -= num2; num += num2; if (amount <= 0) { break; } } if (num == 0) { return 0; } allItems.RemoveAll((ItemData x) => x.m_stack <= 0); m_container.m_inventory.m_inventory = allItems; m_container.Save(); m_container.GetInventory().Changed(); return num; } private string TimeLeft() { string result = ""; if ((m_maxFuel != 0 && !(GetFuel() > 0f)) || (m_maxOre != 0 && GetQueuedOre() == "")) { return result; } if (!m_nview.IsValid() || !m_nview.IsOwner()) { return result; } float bakeTimer = GetBakeTimer(); float num = m_secPerProduct - bakeTimer; int num2 = Mathf.FloorToInt((float)((int)num / 60)); int num3 = Mathf.FloorToInt((float)((int)num % 60)); return $"{num2:00}:{num3:00}"; } } public class BetterWindmill : MonoBehaviour { public Transform m_propeller; public Transform m_grindstone; public Transform m_bom; public AudioSource[] m_sfxLoops; public GameObject m_propellerAOE; public float m_minAOEPropellerSpeed = 5f; public float m_bomRotationSpeed = 10f; public float m_propellerRotationSpeed = 10f; public float m_grindstoneRotationSpeed = 10f; public float m_minWindSpeed = 0.1f; public float m_minPitch = 1f; public float m_maxPitch = 1.5f; public float m_maxPitchVel = 10f; public float m_maxVol = 1f; public float m_maxVolVel = 10f; public float m_audioChangeSpeed = 2f; private float m_cover; private float m_propAngle; private float m_grindStoneAngle; private BetterSmelter m_smelter; public void Start() { m_smelter = ((Component)this).GetComponent<BetterSmelter>(); ((MonoBehaviour)this).InvokeRepeating("CheckCover", 0.1f, 5f); } public void Update() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_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_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_003c: 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_00cf: Unknown result type (might be due to invalid IL or missing references) Quaternion val = Quaternion.LookRotation(-EnvMan.instance.GetWindDir()); float powerOutput = GetPowerOutput(); m_bom.rotation = Quaternion.RotateTowards(m_bom.rotation, val, m_bomRotationSpeed * powerOutput * Time.deltaTime); float num = powerOutput * m_propellerRotationSpeed; m_propAngle += num * Time.deltaTime; m_propeller.localRotation = Quaternion.Euler(0f, 0f, m_propAngle); if ((Object)(object)m_smelter == (Object)null || m_smelter.IsActive()) { m_grindStoneAngle += powerOutput * m_grindstoneRotationSpeed * Time.deltaTime; } m_grindstone.localRotation = Quaternion.Euler(0f, m_grindStoneAngle, 0f); m_propellerAOE.SetActive(Mathf.Abs(num) > m_minAOEPropellerSpeed); UpdateAudio(Time.deltaTime); } public float GetPowerOutput() { float num = Utils.LerpStep(m_minWindSpeed, 1f, EnvMan.instance.GetWindIntensity()); return (1f - m_cover) * num; } public void CheckCover() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) bool flag = default(bool); Cover.GetCoverForPoint(((Component)m_propeller).transform.position, ref m_cover, ref flag, 0.5f); } public void UpdateAudio(float dt) { float powerOutput = GetPowerOutput(); float num = Mathf.Lerp(m_minPitch, m_maxPitch, Mathf.Clamp01(powerOutput / m_maxPitchVel)); float num2 = m_maxVol * Mathf.Clamp01(powerOutput / m_maxVolVel); AudioSource[] sfxLoops = m_sfxLoops; foreach (AudioSource obj in sfxLoops) { obj.volume = Mathf.MoveTowards(obj.volume, num2, m_audioChangeSpeed * dt); obj.pitch = Mathf.MoveTowards(obj.pitch, num, m_audioChangeSpeed * dt); } } } namespace BetterStations { [BepInPlugin("blacks7ar.BetterStations", "BetterStations", "1.0.7")] public class Plugin : BaseUnityPlugin { private enum Toggle { On = 1, Off = 0 } [HarmonyPatch(typeof(ZNetScene), "Awake")] public static class ZNetScenePatch { private static void Postfix(ZNetScene __instance) { if (!((Object)(object)__instance == (Object)null) && __instance.m_prefabs.Count > 0) { __instance.GetPrefab("BBS_EitrRefinery").GetComponent<Piece>().m_icon = Enumerable.FirstOrDefault((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>(), (Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "refinery")); __instance.GetPrefab("BBS_Kiln").GetComponent<Piece>().m_icon = Enumerable.FirstOrDefault((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>(), (Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "coal_kiln")); __instance.GetPrefab("BBS_OreSmelter").GetComponent<Piece>().m_icon = Enumerable.FirstOrDefault((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>(), (Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "blastfurnace")); __instance.GetPrefab("BBS_SpinningWheel").GetComponent<Piece>().m_icon = Enumerable.FirstOrDefault((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>(), (Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "spinningwheel")); __instance.GetPrefab("BBS_Windmill").GetComponent<Piece>().m_icon = Enumerable.FirstOrDefault((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>(), (Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "windmill")); __instance.GetPrefab("BBS_Fermenter").GetComponent<Piece>().m_icon = Enumerable.FirstOrDefault((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>(), (Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "fermenter")); } } } private const string modGUID = "blacks7ar.BetterStations"; public const string modName = "BetterStations"; public const string modAuthor = "blacks7ar"; public const string modVersion = "1.0.7"; public const string modLink = "https://thunderstore.io/c/valheim/p/blacks7ar/BetterStations/"; private static readonly Harmony _harmony = new Harmony("blacks7ar.BetterStations"); private static readonly ConfigSync _configSync = new ConfigSync("blacks7ar.BetterStations") { DisplayName = "BetterStations", CurrentVersion = "1.0.7", MinimumRequiredVersion = "1.0.7", ModRequired = true }; private static ConfigEntry<Toggle> _serverConfigLocked; private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description, bool _synchronizedConfig = 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 + (_synchronizedConfig ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry<T> val2 = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, val); _configSync.AddConfigEntry<T>(val2).SynchronizedConfig = _synchronizedConfig; return val2; } public void Awake() { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown Localizer.Load(); ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; _serverConfigLocked = config("1- ServerSync", "Lock Configuration", Toggle.On, new ConfigDescription("If On, the configuration is locked and can be changed by server admins only.", (AcceptableValueBase)null, Array.Empty<object>())); _configSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked); PrefabsSetup.Init(); ((BaseUnityPlugin)this).Config.SaveOnConfigSet = true; ((BaseUnityPlugin)this).Config.Save(); Assembly executingAssembly = Assembly.GetExecutingAssembly(); _harmony.PatchAll(executingAssembly); } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); } } } namespace BetterStations.Functions { public static class PrefabsSetup { private static AssetBundle _stationsBundle; private const string _category = "BetterStations"; public static void Init() { _stationsBundle = PiecePrefabManager.RegisterAssetBundle("stationbundle"); BuildPiece buildPiece = new BuildPiece(_stationsBundle, "BBS_Kiln"); buildPiece.Crafting.Set(CraftingTable.Workbench); buildPiece.Category.Set("BetterStations"); buildPiece.RequiredItems.Add("Stone", 20, recover: true); buildPiece.RequiredItems.Add("SurtlingCore", 5, recover: true); buildPiece.SpecialProperties = new SpecialProperties { AdminOnly = false, NoConfig = false }; ShaderReplacer.Replace(buildPiece.Prefab); BuildPiece buildPiece2 = new BuildPiece(_stationsBundle, "BBS_OreSmelter"); buildPiece2.Crafting.Set(CraftingTable.Workbench); buildPiece2.Category.Set("BetterStations"); buildPiece2.RequiredItems.Add("Stone", 35, recover: true); buildPiece2.RequiredItems.Add("SurtlingCore", 5, recover: true); buildPiece2.SpecialProperties = new SpecialProperties { AdminOnly = false, NoConfig = false }; ShaderReplacer.Replace(buildPiece2.Prefab); BuildPiece buildPiece3 = new BuildPiece(_stationsBundle, "BBS_EitrRefinery"); buildPiece3.Crafting.Set(CraftingTable.Workbench); buildPiece3.Category.Set("BetterStations"); buildPiece3.RequiredItems.Add("BlackMarble", 20, recover: true); buildPiece3.RequiredItems.Add("BlackMetal", 5, recover: true); buildPiece3.RequiredItems.Add("YggdrasilWood", 10, recover: true); buildPiece3.RequiredItems.Add("BlackCore", 5, recover: true); buildPiece3.RequiredItems.Add("Sap", 3, recover: true); buildPiece3.SpecialProperties = new SpecialProperties { AdminOnly = false, NoConfig = false }; ShaderReplacer.Replace(buildPiece3.Prefab); BuildPiece buildPiece4 = new BuildPiece(_stationsBundle, "BBS_SpinningWheel"); buildPiece4.Crafting.Set(CraftingTable.ArtisanTable); buildPiece4.Category.Set("BetterStations"); buildPiece4.RequiredItems.Add("FineWood", 20, recover: true); buildPiece4.RequiredItems.Add("IronNails", 10, recover: true); buildPiece4.RequiredItems.Add("LeatherScraps", 5, recover: true); buildPiece4.SpecialProperties = new SpecialProperties { AdminOnly = false, NoConfig = false }; ShaderReplacer.Replace(buildPiece4.Prefab); BuildPiece buildPiece5 = new BuildPiece(_stationsBundle, "BBS_Windmill"); buildPiece5.Crafting.Set(CraftingTable.ArtisanTable); buildPiece5.Category.Set("BetterStations"); buildPiece5.RequiredItems.Add("Stone", 20, recover: true); buildPiece5.RequiredItems.Add("Wood", 30, recover: true); buildPiece5.RequiredItems.Add("IronNails", 30, recover: true); buildPiece5.SpecialProperties = new SpecialProperties { AdminOnly = false, NoConfig = false }; ShaderReplacer.Replace(buildPiece5.Prefab); BuildPiece buildPiece6 = new BuildPiece(_stationsBundle, "BBS_Fermenter"); buildPiece6.Crafting.Set(CraftingTable.Forge); buildPiece6.Category.Set("BetterStations"); buildPiece6.RequiredItems.Add("FineWood", 30, recover: true); buildPiece6.RequiredItems.Add("Bronze", 5, recover: true); buildPiece6.RequiredItems.Add("Resin", 10, recover: true); buildPiece6.SpecialProperties = new SpecialProperties { AdminOnly = false, NoConfig = false }; ShaderReplacer.Replace(buildPiece6.Prefab); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_fx_blastfurnace_blast"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_fx_refinery_addfuel"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_fx_refinery_addtissue"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_fx_refinery_destroyed"); ShaderReplacer.Replace(PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_fx_refinery_produce")); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_fx_sw_addflax"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_fx_sw_produce"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_sfx_build_hammer_stone"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_sfx_build_hammer_wood"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_sfx_fermenter_add"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_sfx_fermenter_tap"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_sfx_kiln_addore"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_sfx_kiln_produce"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_sfx_lootspawn"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_sfx_mill_add"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_sfx_mill_produce"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_sfx_rock_destroyed"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_sfx_rock_hit"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_sfx_smelter_add"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_sfx_smelter_produce"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_sfx_wood_destroyed"); ShaderReplacer.Replace(PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_blastfurance_addfuel")); ShaderReplacer.Replace(PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_blastfurnace_addore")); ShaderReplacer.Replace(PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_blastfurnace_produce")); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_fermenter_add"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_fermenter_tap"); ShaderReplacer.Replace(PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_kiln_addore")); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_kiln_produce"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_lootspawn"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_mill_add"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_mill_produce"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_Place_charcoalkiln"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_Place_refinery"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_Place_smelter"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_Place_spinningwheel"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_Place_windmill"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_RockDestroyed"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_RockHit"); PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_SawDust"); ShaderReplacer.Replace(PiecePrefabManager.RegisterPrefab(_stationsBundle, "bbs_vfx_watersplash_bathtub")); } } public static class ShaderReplacer { private static readonly List<GameObject> GOToSwap; static ShaderReplacer() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown GOToSwap = new List<GameObject>(); new Harmony("blacks7ar.utilities.ShaderReplacer").Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(ShaderReplacer), "ReplaceShaderPatch", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static void Replace(GameObject gameObject) { GOToSwap.Add(gameObject); } [HarmonyPriority(700)] private static void ReplaceShaderPatch() { foreach (Material item in Enumerable.Select(Enumerable.Where(Enumerable.SelectMany(Enumerable.Where(Enumerable.SelectMany(Enumerable.Select(GOToSwap, (GameObject gameObject) => gameObject.GetComponentsInChildren<Renderer>(true)), (Renderer[] renderers) => renderers, (Renderer[] renderers, Renderer renderer) => new { renderers, renderer }), <>h__TransparentIdentifier0 => (Object)(object)<>h__TransparentIdentifier0.renderer != (Object)null), <>h__TransparentIdentifier0 => <>h__TransparentIdentifier0.renderer.sharedMaterials, (<>h__TransparentIdentifier0, Material material) => new { <>h__TransparentIdentifier0, material }), <>h__TransparentIdentifier1 => (Object)(object)<>h__TransparentIdentifier1.material != (Object)null), <>h__TransparentIdentifier1 => <>h__TransparentIdentifier1.material)) { Shader[] array = Resources.FindObjectsOfTypeAll<Shader>(); foreach (Shader val in array) { if (((Object)item.shader).name == ((Object)val).name) { item.shader = val; } } } } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<3e7cb476-3e99-4a0d-bd0e-ef440cfd11ed>Embedded] internal sealed class <3e7cb476-3e99-4a0d-bd0e-ef440cfd11ed>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)] [CompilerGenerated] [<3e7cb476-3e99-4a0d-bd0e-ef440cfd11ed>Embedded] internal sealed class <ebf027a2-2528-414f-83fa-a726e5347298>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <ebf027a2-2528-414f-83fa-a726e5347298>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <ebf027a2-2528-414f-83fa-a726e5347298>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [<3e7cb476-3e99-4a0d-bd0e-ef440cfd11ed>Embedded] [CompilerGenerated] internal sealed class <741d9a84-1b1d-43b5-b3b8-95103fa6550f>NullableContextAttribute : Attribute { public readonly byte Flag; public <741d9a84-1b1d-43b5-b3b8-95103fa6550f>NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace LocalizationManager { [PublicAPI] [<741d9a84-1b1d-43b5-b3b8-95103fa6550f>NullableContext(1)] [<ebf027a2-2528-414f-83fa-a726e5347298>Nullable(0)] internal class Localizer { private static readonly Dictionary<string, Dictionary<string, Func<string>>> PlaceholderProcessors; private static readonly Dictionary<string, Dictionary<string, string>> loadedTexts; private static readonly ConditionalWeakTable<Localization, string> localizationLanguage; private static readonly List<WeakReference<Localization>> localizationObjects; [<ebf027a2-2528-414f-83fa-a726e5347298>Nullable(2)] private static BaseUnityPlugin _plugin; private static readonly List<string> fileExtensions; private static BaseUnityPlugin plugin { get { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown if (_plugin == null) { IEnumerable<TypeInfo> source; try { source = Enumerable.ToList(Assembly.GetExecutingAssembly().DefinedTypes); } catch (ReflectionTypeLoadException ex) { source = Enumerable.Select(Enumerable.Where(ex.Types, [<741d9a84-1b1d-43b5-b3b8-95103fa6550f>NullableContext(0)] (Type t) => t != null), [<741d9a84-1b1d-43b5-b3b8-95103fa6550f>NullableContext(0)] (Type t) => t.GetTypeInfo()); } _plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)Enumerable.First(source, [<741d9a84-1b1d-43b5-b3b8-95103fa6550f>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); } return _plugin; } } private static void UpdatePlaceholderText(Localization localization, string key) { localizationLanguage.TryGetValue(localization, out var value); string text = loadedTexts[value][key]; if (PlaceholderProcessors.TryGetValue(key, out var value2)) { text = Enumerable.Aggregate(value2, text, [<741d9a84-1b1d-43b5-b3b8-95103fa6550f>NullableContext(0)] (string current, KeyValuePair<string, Func<string>> kv) => current.Replace("{" + kv.Key + "}", kv.Value())); } localization.AddWord(key, text); } public static void AddPlaceholder<T>(string key, string placeholder, ConfigEntry<T> config, [<ebf027a2-2528-414f-83fa-a726e5347298>Nullable(new byte[] { 2, 1, 1 })] Func<T, string> convertConfigValue = null) { if (convertConfigValue == null) { convertConfigValue = (T val) => val.ToString(); } if (!PlaceholderProcessors.ContainsKey(key)) { PlaceholderProcessors[key] = new Dictionary<string, Func<string>>(); } config.SettingChanged += [<741d9a84-1b1d-43b5-b3b8-95103fa6550f>NullableContext(0)] (object _, EventArgs _) => { UpdatePlaceholder(); }; if (loadedTexts.ContainsKey(Localization.instance.GetSelectedLanguage())) { UpdatePlaceholder(); } void UpdatePlaceholder() { PlaceholderProcessors[key][placeholder] = () => convertConfigValue(config.Value); UpdatePlaceholderText(Localization.instance, key); } } public static void AddText(string key, string text) { List<WeakReference<Localization>> list = new List<WeakReference<Localization>>(); foreach (WeakReference<Localization> localizationObject in localizationObjects) { if (localizationObject.TryGetTarget(out var target)) { Dictionary<string, string> dictionary = loadedTexts[localizationLanguage.GetOrCreateValue(target)]; if (!target.m_translations.ContainsKey(key)) { dictionary[key] = text; target.AddWord(key, text); } } else { list.Add(localizationObject); } } foreach (WeakReference<Localization> item in list) { localizationObjects.Remove(item); } } public static void Load() { _ = plugin; } public static void LoadLocalizationLater(Localization __instance) { LoadLocalization(Localization.instance, __instance.GetSelectedLanguage()); } private static void LoadLocalization(Localization __instance, string language) { if (!localizationLanguage.Remove(__instance)) { localizationObjects.Add(new WeakReference<Localization>(__instance)); } localizationLanguage.Add(__instance, language); Dictionary<string, string> dictionary = new Dictionary<string, string>(); foreach (string item in Enumerable.Where(Directory.GetFiles(Path.GetDirectoryName(Paths.PluginPath), plugin.Info.Metadata.Name + ".*", SearchOption.AllDirectories), [<741d9a84-1b1d-43b5-b3b8-95103fa6550f>NullableContext(0)] (string f) => fileExtensions.IndexOf(Path.GetExtension(f)) >= 0)) { string text = Path.GetFileNameWithoutExtension(item).Split(new char[1] { '.' })[1]; if (dictionary.ContainsKey(text)) { Debug.LogWarning((object)("Duplicate key " + text + " found for " + plugin.Info.Metadata.Name + ". The duplicate file found at " + item + " will be skipped.")); } else { dictionary[text] = item; } } byte[] array = LoadTranslationFromAssembly("English"); if (array == null) { throw new Exception("Found no English localizations in mod " + plugin.Info.Metadata.Name + ". Expected an embedded resource translations/English.json or translations/English.yml."); } Dictionary<string, string> dictionary2 = new DeserializerBuilder().IgnoreFields().Build().Deserialize<Dictionary<string, string>>(Encoding.UTF8.GetString(array)); if (dictionary2 == null) { throw new Exception("Localization for mod " + plugin.Info.Metadata.Name + " failed: Localization file was empty."); } string text2 = null; if (language != "English") { if (dictionary.TryGetValue(language, out var value)) { text2 = File.ReadAllText(value); } else { byte[] array2 = LoadTranslationFromAssembly(language); if (array2 != null) { text2 = Encoding.UTF8.GetString(array2); } } } if (text2 == null && dictionary.TryGetValue("English", out var value2)) { text2 = File.ReadAllText(value2); } if (text2 != null) { foreach (KeyValuePair<string, string> item2 in new DeserializerBuilder().IgnoreFields().Build().Deserialize<Dictionary<string, string>>(text2) ?? new Dictionary<string, string>()) { dictionary2[item2.Key] = item2.Value; } } loadedTexts[language] = dictionary2; foreach (KeyValuePair<string, string> item3 in dictionary2) { UpdatePlaceholderText(__instance, item3.Key); } } static Localizer() { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Expected O, but got Unknown PlaceholderProcessors = new Dictionary<string, Dictionary<string, Func<string>>>(); loadedTexts = new Dictionary<string, Dictionary<string, string>>(); localizationLanguage = new ConditionalWeakTable<Localization, string>(); localizationObjects = new List<WeakReference<Localization>>(); fileExtensions = new List<string> { ".json", ".yml" }; Harmony val = new Harmony("org.bepinex.helpers.LocalizationManager"); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Localizer), "LoadLocalization", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "SetupGui", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Localizer), "LoadLocalizationLater", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } [return: <ebf027a2-2528-414f-83fa-a726e5347298>Nullable(2)] private static byte[] LoadTranslationFromAssembly(string language) { foreach (string fileExtension in fileExtensions) { byte[] array = ReadEmbeddedFileBytes("translations." + language + fileExtension); if (array != null) { return array; } } return null; } [<741d9a84-1b1d-43b5-b3b8-95103fa6550f>NullableContext(2)] public static byte[] ReadEmbeddedFileBytes([<ebf027a2-2528-414f-83fa-a726e5347298>Nullable(1)] string resourceFileName, Assembly containingAssembly = null) { using MemoryStream memoryStream = new MemoryStream(); if ((object)containingAssembly == null) { containingAssembly = Assembly.GetCallingAssembly(); } string text = Enumerable.FirstOrDefault(containingAssembly.GetManifestResourceNames(), [<741d9a84-1b1d-43b5-b3b8-95103fa6550f>NullableContext(0)] (string str) => str.EndsWith(resourceFileName, StringComparison.Ordinal)); if (text != null) { containingAssembly.GetManifestResourceStream(text)?.CopyTo(memoryStream); } return (memoryStream.Length == 0L) ? null : memoryStream.ToArray(); } } } namespace System.Runtime.CompilerServices { [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [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] [Microsoft.CodeAnalysis.Embedded] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] 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)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } } namespace System.Collections.Generic { internal static class DeconstructionExtensions { public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> pair, out TKey key, out TValue value) { key = pair.Key; value = pair.Value; } } } namespace YamlDotNet { internal sealed class CultureInfoAdapter : CultureInfo { private readonly IFormatProvider provider; public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider) : base(baseCulture.LCID) { this.provider = provider; } public override object? GetFormat(Type? formatType) { return provider.GetFormat(formatType); } } internal static class ReflectionExtensions { private static readonly FieldInfo? RemoteStackTraceField = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic); public static Type? BaseType(this Type type) { return type.BaseType; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static bool IsGenericTypeDefinition(this Type type) { return type.IsGenericTypeDefinition; } public static bool IsInterface(this Type type) { return type.IsInterface; } public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsDbNull(this object value) { return value is DBNull; } public static bool HasDefaultConstructor(this Type type) { if (!type.IsValueType) { return type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null) != null; } return true; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static PropertyInfo? GetPublicProperty(this Type type, string name) { return type.GetProperty(name); } public static FieldInfo? GetPublicStaticField(this Type type, string name) { return type.GetField(name, BindingFlags.Static | BindingFlags.Public); } public static IEnumerable<PropertyInfo> 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 Enumerable.SelectMany(Enumerable.Concat(new Type[1] { type }, type.GetInterfaces()), (Type i) => i.GetProperties(bindingFlags)); } public static IEnumerable<PropertyInfo> GetPublicProperties(this Type type) { return type.GetProperties(includeNonPublic: false); } public static IEnumerable<FieldInfo> GetPublicFields(this Type type) { return type.GetFields(BindingFlags.Instance | BindingFlags.Public); } public static IEnumerable<MethodInfo> GetPublicStaticMethods(this Type type) { return type.GetMethods(BindingFlags.Static | BindingFlags.Public); } public static MethodInfo GetPrivateStaticMethod(this Type type, string name) { return type.GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic) ?? throw new MissingMethodException("Expected to find a method named '" + name + "' in '" + type.FullName + "'."); } public static MethodInfo? GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes) { return type.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, parameterTypes, null); } public static MethodInfo? GetPublicInstanceMethod(this Type type, string name) { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public); } public static Exception Unwrap(this TargetInvocationException ex) { Exception innerException = ex.InnerException; if (innerException == null) { return ex; } if (RemoteStackTraceField != null) { RemoteStackTraceField.SetValue(innerException, innerException.StackTrace + "\r\n"); } return innerException; } public static bool IsInstanceOf(this Type type, object o) { return type.IsInstanceOfType(o); } public static Attribute[] GetAllCustomAttributes<TAttribute>(this PropertyInfo property) { return Attribute.GetCustomAttributes(property, typeof(TAttribute)); } } internal static class PropertyInfoExtensions { public static object? ReadValue(this PropertyInfo property, object target) { return property.GetValue(target, null); } } internal static class StandardRegexOptions { public const RegexOptions Compiled = RegexOptions.Compiled; } } namespace YamlDotNet.Serialization { internal abstract class BuilderSkeleton<TBuilder> where TBuilder : BuilderSkeleton<TBuilder> { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal ITypeResolver typeResolver; internal readonly YamlAttributeOverrides overrides; internal readonly LazyComponentRegistrationList<Nothing, IYamlTypeConverter> typeConverterFactories; internal readonly LazyComponentRegistrationList<ITypeInspector, ITypeInspector> typeInspectorFactories; private bool ignoreFields; private bool includeNonPublicProperties; protected abstract TBuilder Self { get; } internal BuilderSkeleton(ITypeResolver typeResolver) { overrides = new YamlAttributeOverrides(); typeConverterFactories = new LazyComponentRegistrationList<Nothing, IYamlTypeConverter> { { typeof(YamlDotNet.Serialization.Converters.GuidConverter), (Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false) }, { typeof(SystemTypeConverter), (Nothing _) => new SystemTypeConverter() } }; typeInspectorFactories = new LazyComponentRegistrationList<ITypeInspector, ITypeInspector>(); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = new ReadablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector); } return typeInspectorFactories.BuildComponentChain(typeInspector); } public TBuilder IgnoreFields() { ignoreFields = true; return Self; } public TBuilder IncludeNonPublicProperties() { includeNonPublicProperties = 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<TClass>(Expression<Func<TClass, object>> 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<IYamlTypeConverter> w) { w.OnTop(); }); } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action<IRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where) { IYamlTypeConverter typeConverter2 = typeConverter; if (typeConverter2 == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter2.GetType(), (Nothing _) => typeConverter2)); return Self; } public TBuilder WithTypeConverter<TYamlTypeConverter>(WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where) where TYamlTypeConverter : IYamlTypeConverter { WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory2 = typeConverterFactory; if (typeConverterFactory2 == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory2(wrapped))); return Self; } public TBuilder WithoutTypeConverter<TYamlTypeConverter>() where TYamlTypeConverter : IYamlTypeConverter { return WithoutTypeConverter(typeof(TYamlTypeConverter)); } public TBuilder WithoutTypeConverter(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } typeConverterFactories.Remove(converterType); return Self; } public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> w) { w.OnTop(); }); } public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory, Action<IRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector { Func<ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory2(inner))); return Self; } public TBuilder WithTypeInspector<TTypeInspector>(WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector { WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory2(wrapped, inner))); return Self; } public TBuilder WithoutTypeInspector<TTypeInspector>() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if (inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } protected IEnumerable<IYamlTypeConverter> BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } internal delegate TComponent WrapperFactory<TComponentBase, TComponent>(TComponentBase wrapped) where TComponent : TComponentBase; internal delegate TComponent WrapperFactory<TArgument, TComponentBase, TComponent>(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase; [Flags] internal enum DefaultValuesHandling { Preserve = 0, OmitNull = 1, OmitDefaults = 2, OmitEmptyCollections = 4 } internal sealed class Deserializer : IDeserializer { private readonly IValueDeserializer valueDeserializer; public Deserializer() : this(new DeserializerBuilder().BuildValueDeserializer()) { } private Deserializer(IValueDeserializer valueDeserializer) { this.valueDeserializer = valueDeserializer ?? throw new ArgumentNullException("valueDeserializer"); } public static Deserializer FromValueDeserializer(IValueDeserializer valueDeserializer) { return new Deserializer(valueDeserializer); } public T Deserialize<T>(string input) { using StringReader input2 = new StringReader(input); return Deserialize<T>(input2); } public T Deserialize<T>(TextReader input) { return Deserialize<T>(new Parser(input)); } public object? Deserialize(TextReader input) { return Deserialize(input, typeof(object)); } public object? Deserialize(string input, Type type) { using StringReader input2 = new StringReader(input); return Deserialize(input2, type); } public object? Deserialize(TextReader input, Type type) { return Deserialize(new Parser(input), type); } public T Deserialize<T>(IParser parser) { return (T)Deserialize(parser, typeof(T)); } public object? Deserialize(IParser parser) { return Deserialize(parser, typeof(object)); } public object? Deserialize(IParser parser, Type type) { if (parser == null) { throw new ArgumentNullException("parser"); } if (type == null) { throw new ArgumentNullException("type"); } YamlDotNet.Core.Events.StreamStart @event; bool flag = parser.TryConsume<YamlDotNet.Core.Events.StreamStart>(out @event); YamlDotNet.Core.Events.DocumentStart event2; bool flag2 = parser.TryConsume<YamlDotNet.Core.Events.DocumentStart>(out event2); object result = null; if (!parser.Accept<YamlDotNet.Core.Events.DocumentEnd>(out var _) && !parser.Accept<YamlDotNet.Core.Events.StreamEnd>(out var _)) { using SerializerState serializerState = new SerializerState(); result = valueDeserializer.DeserializeValue(parser, type, serializerState, valueDeserializer); serializerState.OnDeserialization(); } if (flag2) { parser.Consume<YamlDotNet.Core.Events.DocumentEnd>(); } if (flag) { parser.Consume<YamlDotNet.Core.Events.StreamEnd>(); } return result; } } internal sealed class DeserializerBuilder : BuilderSkeleton<DeserializerBuilder> { private Lazy<IObjectFactory> objectFactory; private readonly LazyComponentRegistrationList<Nothing, INodeDeserializer> nodeDeserializerFactories; private readonly LazyComponentRegistrationList<Nothing, INodeTypeResolver> nodeTypeResolverFactories; private readonly Dictionary<TagName, Type> tagMappings; private readonly Dictionary<Type, Type> typeMappings; private bool ignoreUnmatched; protected override DeserializerBuilder Self => this; public DeserializerBuilder() : base((ITypeResolver)new StaticTypeResolver()) { typeMappings = new Dictionary<Type, Type>(); objectFactory = new Lazy<IObjectFactory>(() => new DefaultObjectFactory(typeMappings), isThreadSafe: true); tagMappings = new Dictionary<TagName, Type> { { FailsafeSchema.Tags.Map, typeof(Dictionary<object, object>) }, { 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<Nothing, INodeDeserializer> { { 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() }, { typeof(ArrayNodeDeserializer), (Nothing _) => new ArrayNodeDeserializer() }, { typeof(DictionaryNodeDeserializer), (Nothing _) => new DictionaryNodeDeserializer(objectFactory.Value) }, { typeof(CollectionNodeDeserializer), (Nothing _) => new CollectionNodeDeserializer(objectFactory.Value) }, { typeof(EnumerableNodeDeserializer), (Nothing _) => new EnumerableNodeDeserializer() }, { typeof(ObjectNodeDeserializer), (Nothing _) => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched) } }; nodeTypeResolverFactories = new LazyComponentRegistrationList<Nothing, INodeTypeResolver> { { 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() } }; } public DeserializerBuilder WithObjectFactory(IObjectFactory objectFactory) { IObjectFactory objectFactory2 = objectFactory; if (objectFactory2 == null) { throw new ArgumentNullException("objectFactory"); } this.objectFactory = new Lazy<IObjectFactory>(() => objectFactory2, isThreadSafe: true); return this; } public DeserializerBuilder WithObjectFactory(Func<Type, object> objectFactory) { if (objectFactory == null) { throw new ArgumentNullException("objectFactory"); } return WithObjectFactory(new LambdaObjectFactory(objectFactory)); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer) { return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax<INodeDeserializer> w) { w.OnTop(); }); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action<IRegistrationLocationSelectionSyntax<INodeDeserializer>> where) { INodeDeserializer nodeDeserializer2 = nodeDeserializer; if (nodeDeserializer2 == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer2.GetType(), (Nothing _) => nodeDeserializer2)); return this; } public DeserializerBuilder WithNodeDeserializer<TNodeDeserializer>(WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeDeserializer>> where) where TNodeDeserializer : INodeDeserializer { WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory2 = nodeDeserializerFactory; if (nodeDeserializerFactory2 == null) { throw new ArgumentNullException("nodeDeserializerFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory2(wrapped))); return this; } public DeserializerBuilder WithoutNodeDeserializer<TNodeDeserializer>() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public DeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if (nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax<INodeTypeResolver> w) { w.OnTop(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action<IRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) { INodeTypeResolver nodeTypeResolver2 = nodeTypeResolver; if (nodeTypeResolver2 == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver2.GetType(), (Nothing _) => nodeTypeResolver2)); return this; } public DeserializerBuilder WithNodeTypeResolver<TNodeTypeResolver>(WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) where TNodeTypeResolver : INodeTypeResolver { WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory2 = nodeTypeResolverFactory; if (nodeTypeResolverFactory2 == null) { throw new ArgumentNullException("nodeTypeResolverFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory2(wrapped))); return this; } public DeserializerBuilder WithoutNodeTypeResolver<TNodeTypeResolver>() where TNodeTypeResolver : INodeTypeResolver { return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); } public DeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) { if (nodeTypeResolverType == null) { throw new ArgumentNullException("nodeTypeResolverType"); } nodeTypeResolverFactories.Remove(nodeTypeResolverType); return this; } public override DeserializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(tag, out Type value)) { throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag"); } tagMappings.Add(tag, type); return this; } public DeserializerBuilder WithTypeMapping<TInterface, 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 IDeserializer Build() { return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public IValueDeserializer BuildValueDeserializer() { return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList())); } } internal sealed class EmissionPhaseObjectGraphVisitorArgs { private readonly IEnumerable<IObjectGraphVisitor<Nothing>> preProcessingPhaseVisitors; public IObjectGraphVisitor<IEmitter> InnerVisitor { get; private set; } public IEventEmitter EventEmitter { get; private set; } public ObjectSerializer NestedObjectSerializer { get; private set; } public IEnumerable<IYamlTypeConverter> TypeConverters { get; private set; } public EmissionPhaseObjectGraphVisitorArgs(IObjectGraphVisitor<IEmitter> innerVisitor, IEventEmitter eventEmitter, IEnumerable<IObjectGraphVisitor<Nothing>> preProcessingPhaseVisitors, IEnumerable<IYamlTypeConverter> 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<T>() where T : IObjectGraphVisitor<Nothing> { return Enumerable.Single(Enumerable.OfType<T>(preProcessingPhaseVisitors)); } } internal abstract class EventInfo { public IObjectDescriptor Source { get; } protected EventInfo(IObjectDescriptor source) { Source = source ?? throw new ArgumentNullException("source"); } } internal class AliasEventInfo : EventInfo { public AnchorName Alias { get; } public bool NeedsExpansion { get; set; } public AliasEventInfo(IObjectDescriptor source, AnchorName alias) : base(source) { if (alias.IsEmpty) { throw new ArgumentNullException("alias"); } Alias = alias; } } internal class ObjectEventInfo : EventInfo { public AnchorName Anchor { get; set; } public TagName Tag { get; set; } protected ObjectEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class ScalarEventInfo : ObjectEventInfo { public string RenderedValue { get; set; } public ScalarStyle Style { get; set; } public bool IsPlainImplicit { get; set; } public bool IsQuotedImplicit { get; set; } public ScalarEventInfo(IObjectDescriptor source) : base(source) { Style = source.ScalarStyle; RenderedValue = string.Empty; } } internal sealed class MappingStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public MappingStyle Style { get; set; } public MappingStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class MappingEndEventInfo : EventInfo { public MappingEndEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public SequenceStyle Style { get; set; } public SequenceStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceEndEventInfo : EventInfo { public SequenceEndEventInfo(IObjectDescriptor source) : base(source) { } } internal interface IAliasProvider { AnchorName GetAlias(object target); } internal interface IDeserializer { T Deserialize<T>(string input); T Deserialize<T>(TextReader input); object? Deserialize(TextReader input); object? Deserialize(string input, Type type); object? Deserialize(TextReader input, Type type); T Deserialize<T>(IParser parser); object? Deserialize(IParser parser); object? Deserialize(IParser parser, Type type); } internal interface IEventEmitter { void Emit(AliasEventInfo eventInfo, IEmitter emitter); void Emit(ScalarEventInfo eventInfo, IEmitter emitter); void Emit(MappingStartEventInfo eventInfo, IEmitter emitter); void Emit(MappingEndEventInfo eventInfo, IEmitter emitter); void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter); void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter); } internal interface INamingConvention { string Apply(string value); } internal interface INodeDeserializer { bool Deserialize(IParser reader, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer,