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 ValheimFortress v0.41.0
plugins/ValheimFortress.dll
Decompiled 2 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Json; using System.Runtime.Versioning; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Jotunn; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Extensions; using Jotunn.Managers; using Jotunn.Utils; using SimpleJson; using Splatform; using StarLevelSystem; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; using ValheimFortress.Challenge; using ValheimFortress.Common; using ValheimFortress.Data; using ValheimFortress.Defenses; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("ValheimFortress")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ValheimFortress")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("e3243d22-4307-4008-ba36-9f326008cde5")] [assembly: AssemblyFileVersion("0.41.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.41.0.0")] namespace StarLevelSystem { [PublicAPI] public static class API { private static readonly Type APIReciever; private static readonly MethodInfo UpdateCreatureLevel; private static readonly MethodInfo UpdateCreatureColorization; private static readonly MethodInfo GetBaseAttributeValue; private static readonly MethodInfo UpdateCreatureBaseAttributes; private static readonly MethodInfo GetAllBaseAttributeValues; private static readonly MethodInfo SetAllBaseAttributeValues; private static readonly MethodInfo GetPerLevelAttributeValue; private static readonly MethodInfo UpdateCreaturePerLevelAttributes; private static readonly MethodInfo GetAllPerLevelAttributeValues; private static readonly MethodInfo SetAllPerLevelAttributeValues; private static readonly MethodInfo GetCreatureDamageRecievedModifier; private static readonly MethodInfo UpdateCreatureDamageRecievedModifier; private static readonly MethodInfo GetAllDamageRecievedModifiers; private static readonly MethodInfo SetAllDamageRecievedModifiers; private static readonly MethodInfo GetCreatureDamageBonus; private static readonly MethodInfo UpdateCreatureDamageBonus; private static readonly MethodInfo GetAllDamageBonus; private static readonly MethodInfo SetAllDamageBonus; private static readonly MethodInfo ApplyUpdatesToCreature; private static readonly MethodInfo SetCreatureSpawnManagedMethod; private static readonly MethodInfo GetPossibleModifiersForType; private static readonly MethodInfo GetAllModifiersForCreature; private static readonly MethodInfo AddModifierToCreature; private static readonly MethodInfo AddNewModifierToSLS; private static readonly MethodInfo RegisterLocationResetTargetMethod; private static readonly MethodInfo UnregisterLocationResetTargetMethod; private static readonly MethodInfo GetRegisteredLocationResetTargetsMethod; private static readonly MethodInfo GetLocationResetTargetInfoMethod; private static readonly MethodInfo IsLocationResetReadyMethod; private static readonly MethodInfo GetLocationResetStatusMethod; private static readonly MethodInfo IsKnownResetTargetNameMethod; private static readonly MethodInfo GetLocationLastResetMethod; private static readonly MethodInfo GetSecondsUntilLocationResetMethod; private static readonly MethodInfo GetLocationResetInfoMethod; private static readonly MethodInfo GetChunkResetInfoMethod; private static readonly MethodInfo ResetNamedLocationMethod; private static readonly MethodInfo ResetLocationsInRadiusMethod; public static bool IsAvailable => APIReciever != null; public static bool SupportsLocationReset => ResetNamedLocationMethod != null; public static bool SupportsSpawnManaged => SetCreatureSpawnManagedMethod != null; static API() { APIReciever = Type.GetType("StarLevelSystem.modules.APIReciever, StarLevelSystem"); if (!(APIReciever == null)) { UpdateCreatureLevel = APIReciever.GetMethod("UpdateCreatureLevel", BindingFlags.Static | BindingFlags.Public); UpdateCreatureColorization = APIReciever.GetMethod("UpdateCreatureColorization", BindingFlags.Static | BindingFlags.Public); GetBaseAttributeValue = APIReciever.GetMethod("GetBaseAttributeValue", BindingFlags.Static | BindingFlags.Public); UpdateCreatureBaseAttributes = APIReciever.GetMethod("UpdateCreatureBaseAttributes", BindingFlags.Static | BindingFlags.Public); GetAllBaseAttributeValues = APIReciever.GetMethod("GetAllBaseAttributes", BindingFlags.Static | BindingFlags.Public); SetAllBaseAttributeValues = APIReciever.GetMethod("SetAllBaseAttributes", BindingFlags.Static | BindingFlags.Public); GetPerLevelAttributeValue = APIReciever.GetMethod("GetPerLevelAttributeValue", BindingFlags.Static | BindingFlags.Public); UpdateCreaturePerLevelAttributes = APIReciever.GetMethod("UpdateCreaturePerLevelAttributes", BindingFlags.Static | BindingFlags.Public); GetAllPerLevelAttributeValues = APIReciever.GetMethod("GetAllPerLevelAttributes", BindingFlags.Static | BindingFlags.Public); SetAllPerLevelAttributeValues = APIReciever.GetMethod("SetAllPerLevelAttributes", BindingFlags.Static | BindingFlags.Public); GetCreatureDamageRecievedModifier = APIReciever.GetMethod("GetCreatureDamageRecievedModifier", BindingFlags.Static | BindingFlags.Public); UpdateCreatureDamageRecievedModifier = APIReciever.GetMethod("UpdateCreatureDamageRecievedModifier", BindingFlags.Static | BindingFlags.Public); GetAllDamageRecievedModifiers = APIReciever.GetMethod("GetAllDamageRecievedModifiers", BindingFlags.Static | BindingFlags.Public); SetAllDamageRecievedModifiers = APIReciever.GetMethod("SetAllDamageRecievedModifiers", BindingFlags.Static | BindingFlags.Public); GetCreatureDamageBonus = APIReciever.GetMethod("GetCreatureDamageBonus", BindingFlags.Static | BindingFlags.Public); UpdateCreatureDamageBonus = APIReciever.GetMethod("UpdateCreatureDamageBonus", BindingFlags.Static | BindingFlags.Public); GetAllDamageBonus = APIReciever.GetMethod("GetAllDamageBonus", BindingFlags.Static | BindingFlags.Public); SetAllDamageBonus = APIReciever.GetMethod("SetAllDamageBonus", BindingFlags.Static | BindingFlags.Public); ApplyUpdatesToCreature = APIReciever.GetMethod("ApplyUpdatesToCreature", BindingFlags.Static | BindingFlags.Public); SetCreatureSpawnManagedMethod = APIReciever.GetMethod("SetCreatureSpawnManaged", BindingFlags.Static | BindingFlags.Public); GetPossibleModifiersForType = APIReciever.GetMethod("GetPossibleModifiersForType", BindingFlags.Static | BindingFlags.Public); GetAllModifiersForCreature = APIReciever.GetMethod("GetAllModifiersForCreature", BindingFlags.Static | BindingFlags.Public); AddModifierToCreature = APIReciever.GetMethod("AddModifierToCreature", BindingFlags.Static | BindingFlags.Public); AddNewModifierToSLS = APIReciever.GetMethod("AddNewModifierToSLS", BindingFlags.Static | BindingFlags.Public); RegisterLocationResetTargetMethod = APIReciever.GetMethod("RegisterLocationResetTarget", BindingFlags.Static | BindingFlags.Public); UnregisterLocationResetTargetMethod = APIReciever.GetMethod("UnregisterLocationResetTarget", BindingFlags.Static | BindingFlags.Public); GetRegisteredLocationResetTargetsMethod = APIReciever.GetMethod("GetRegisteredLocationResetTargets", BindingFlags.Static | BindingFlags.Public); GetLocationResetTargetInfoMethod = APIReciever.GetMethod("GetLocationResetTargetInfo", BindingFlags.Static | BindingFlags.Public); IsLocationResetReadyMethod = APIReciever.GetMethod("IsLocationResetReady", BindingFlags.Static | BindingFlags.Public); GetLocationResetStatusMethod = APIReciever.GetMethod("GetLocationResetStatus", BindingFlags.Static | BindingFlags.Public); IsKnownResetTargetNameMethod = APIReciever.GetMethod("IsKnownResetTargetName", BindingFlags.Static | BindingFlags.Public); GetLocationLastResetMethod = APIReciever.GetMethod("GetLocationLastReset", BindingFlags.Static | BindingFlags.Public); GetSecondsUntilLocationResetMethod = APIReciever.GetMethod("GetSecondsUntilLocationReset", BindingFlags.Static | BindingFlags.Public); GetLocationResetInfoMethod = APIReciever.GetMethod("GetLocationResetInfo", BindingFlags.Static | BindingFlags.Public); GetChunkResetInfoMethod = APIReciever.GetMethod("GetChunkResetInfo", BindingFlags.Static | BindingFlags.Public); ResetNamedLocationMethod = APIReciever.GetMethod("ResetNamedLocation", BindingFlags.Static | BindingFlags.Public); ResetLocationsInRadiusMethod = APIReciever.GetMethod("ResetLocationsInRadius", BindingFlags.Static | BindingFlags.Public); } } private static object Call(MethodInfo method, object fallback, params object[] args) { if (method == null) { return fallback; } return method.Invoke(null, args); } public static bool SetCreatureLevel(Character creatureId, int newLevel) { return (bool)UpdateCreatureLevel.Invoke(null, new object[2] { creatureId, newLevel }); } public static bool SetCreatureColorization(Character creatureId, float value, float hue, float sat, bool emission = false) { return (bool)UpdateCreatureColorization.Invoke(null, new object[5] { creatureId, value, hue, sat, emission }); } public static float GetCreatureBaseAttribute(Character creatureId, int attribute) { return (float)GetBaseAttributeValue.Invoke(null, new object[2] { creatureId, attribute }); } public static bool SetCreatureBaseAttribute(Character creatureId, int attribute, float value) { return (bool)UpdateCreatureBaseAttributes.Invoke(null, new object[3] { creatureId, attribute, value }); } public static Dictionary<int, float> GetAllCreatureBaseAttributes(Character creatureId) { return (Dictionary<int, float>)GetAllBaseAttributeValues.Invoke(null, new object[1] { creatureId }); } public static bool SetAllCreatureBaseAttributes(Character creatureId, Dictionary<int, float> attributes) { return (bool)SetAllBaseAttributeValues.Invoke(null, new object[2] { creatureId, attributes }); } public static float GetCreaturePerLevelAttribute(Character creatureId, int attribute) { return (float)GetPerLevelAttributeValue.Invoke(null, new object[2] { creatureId, attribute }); } public static bool SetCreaturePerLevelAttribute(Character creatureId, int attribute, float value) { return (bool)UpdateCreaturePerLevelAttributes.Invoke(null, new object[3] { creatureId, attribute, value }); } public static Dictionary<int, float> GetAllCreaturePerLevelAttributes(Character creatureId) { return (Dictionary<int, float>)GetAllPerLevelAttributeValues.Invoke(null, new object[1] { creatureId }); } public static bool SetAllCreaturePerLevelAttributes(Character creatureId, Dictionary<int, float> attributes) { return (bool)SetAllPerLevelAttributeValues.Invoke(null, new object[2] { creatureId, attributes }); } public static float GetCreatureDamageReceivedModifier(Character creatureId, int damageType) { return (float)GetCreatureDamageRecievedModifier.Invoke(null, new object[2] { creatureId, damageType }); } public static bool SetCreatureDamageReceivedModifier(Character creatureId, int damageType, float value) { return (bool)UpdateCreatureDamageRecievedModifier.Invoke(null, new object[3] { creatureId, damageType, value }); } public static Dictionary<int, float> GetAllCreatureDamageReceivedModifiers(Character creatureId) { return (Dictionary<int, float>)GetAllDamageRecievedModifiers.Invoke(null, new object[1] { creatureId }); } public static bool SetAllCreatureDamageReceivedModifiers(Character creatureId, Dictionary<int, float> attributes) { return (bool)SetAllDamageRecievedModifiers.Invoke(null, new object[2] { creatureId, attributes }); } public static float GetCreatureFlatDamageBonus(Character creatureId, int damageType) { return (float)GetCreatureDamageBonus.Invoke(null, new object[2] { creatureId, damageType }); } public static bool SetCreatureFlatDamageBonus(Character creatureId, int damageType, float value) { return (bool)UpdateCreatureDamageBonus.Invoke(null, new object[3] { creatureId, damageType, value }); } public static Dictionary<int, float> GetAllCreatureFlatDamageBonuses(Character creatureId) { return (Dictionary<int, float>)GetAllDamageBonus.Invoke(null, new object[1] { creatureId }); } public static bool SetAllCreatureFlatDamageBonuses(Character creatureId, Dictionary<int, float> attributes) { return (bool)SetAllDamageBonus.Invoke(null, new object[2] { creatureId, attributes }); } public static bool ApplyCreatureUpdates(Character creatureId) { return (bool)ApplyUpdatesToCreature.Invoke(null, new object[1] { creatureId }); } public static bool SetCreatureSpawnManaged(Character creatureId, bool managed = true) { return (bool)Call(SetCreatureSpawnManagedMethod, false, creatureId, managed); } public static List<string> GetPossibleModifiers(int modType = 0) { return (List<string>)GetPossibleModifiersForType.Invoke(null, new object[1] { modType }); } public static Dictionary<string, int> GetCreaturesModifiers(Character creatureId) { return (Dictionary<string, int>)GetAllModifiersForCreature.Invoke(null, new object[1] { creatureId }); } public static bool AddModifierToTargetCreature(Character creatureId, string modifierName, int modifierType, bool update = true) { return (bool)AddModifierToCreature.Invoke(null, new object[4] { creatureId, modifierName, modifierType, update }); } public static bool AddNewModifier(int modifierID, string modifier_name, Delegate setupMethod = null, float selectionWeight = 10f, float basepower = 0f, float perlevelpower = 0f, Dictionary<Biome, List<string>> biomeConfig = null, int namingStyle = 2, string name_suffixes = null, string name_prefixes = null, int visualStyle = 0, Sprite starIcon = null, GameObject visualEffect = null, List<string> allowed_creatures = null, List<string> unallowed_creatures = null, List<Biome> allowed_biomes = null) { return (bool)AddNewModifierToSLS.Invoke(null, new object[16] { modifierID, modifier_name, setupMethod, selectionWeight, basepower, perlevelpower, biomeConfig, namingStyle, name_suffixes, name_prefixes, visualStyle, starIcon, visualEffect, allowed_creatures, unallowed_creatures, allowed_biomes }); } public static bool RegisterLocationReset(string prefabName, string sourceId, float resetHours = 0f, string resetSchedule = null, bool enabled = true, int mode = 0, bool resetTerrain = false, float terrainRadius = 0f, float extraTerrainRadius = 0f, bool resetInterior = true, float minDistance = 0f, float maxDistance = 0f, Action<bool> onResult = null) { return (bool)Call(RegisterLocationResetTargetMethod, false, prefabName, sourceId, resetHours, resetSchedule, mode, resetTerrain, terrainRadius, extraTerrainRadius, resetInterior, minDistance, maxDistance, enabled, onResult); } public static bool UnregisterLocationReset(string prefabName, string sourceId, Action<bool> onResult = null) { return (bool)Call(UnregisterLocationResetTargetMethod, false, prefabName, sourceId, onResult); } public static bool GetRegisteredLocationResets(string sourceId, Action<List<string>> onResult) { return (bool)Call(GetRegisteredLocationResetTargetsMethod, false, sourceId, onResult); } public static bool GetLocationResetTargetInfo(string prefabName, Action<Dictionary<string, object>> onResult) { return (bool)Call(GetLocationResetTargetInfoMethod, false, prefabName, onResult); } public static bool IsLocationResetReady(Action<bool> onResult) { return (bool)Call(IsLocationResetReadyMethod, false, onResult); } public static bool GetLocationResetStatus(Action<Dictionary<string, object>> onResult) { return (bool)Call(GetLocationResetStatusMethod, false, onResult); } public static bool IsKnownLocationResetTarget(string prefabName, Action<bool> onResult) { return (bool)Call(IsKnownResetTargetNameMethod, false, prefabName, onResult); } public static bool GetLocationLastReset(string locationName, Vector3 center, float radius, Action<long> onResult) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) return (bool)Call(GetLocationLastResetMethod, false, locationName, center, radius, onResult); } public static bool GetSecondsUntilLocationReset(string locationName, Vector3 center, float radius, Action<double> onResult) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) return (bool)Call(GetSecondsUntilLocationResetMethod, false, locationName, center, radius, onResult); } public static bool GetLocationResetInfo(string locationName, Vector3 center, float radius, Action<Dictionary<string, object>> onResult) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) return (bool)Call(GetLocationResetInfoMethod, false, locationName, center, radius, onResult); } public static bool GetChunkResetInfo(Vector3 position, bool includePrefabs, Action<Dictionary<string, object>> onResult) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) return (bool)Call(GetChunkResetInfoMethod, false, position, includePrefabs, onResult); } public static bool ResetNamedLocation(string locationName, Vector3 center, float radius = 128f, int safety = 0, bool resetAllMatches = false, float safeWaitSeconds = 0f, bool includeDetail = false, Action<Dictionary<string, object>> onComplete = null) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) return (bool)Call(ResetNamedLocationMethod, false, locationName, center, radius, safety, resetAllMatches, safeWaitSeconds, includeDetail, onComplete); } public static bool ResetLocationsInRadius(Vector3 center, float radius = 128f, int safety = 0, float safeWaitSeconds = 0f, bool includeDetail = false, Action<Dictionary<string, object>> onComplete = null) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) return (bool)Call(ResetLocationsInRadiusMethod, false, center, radius, safety, safeWaitSeconds, includeDetail, onComplete); } } } namespace ValheimFortress { public static class API { private static readonly Type APIReceiver; private static readonly MethodInfo RunChallengeMethod; private static readonly MethodInfo GetSpawnableCreaturesMethod; private static readonly MethodInfo GetRewardItemsMethod; private static readonly MethodInfo GetWaveStylesMethod; private static readonly MethodInfo GetShrineChallengeDefinitionMethod; private static readonly MethodInfo GetShrineTributesMethod; private static readonly MethodInfo StartChallengeMethod; private static readonly MethodInfo GetChallengeStateMethod; private static readonly MethodInfo StopChallengeMethod; private static readonly MethodInfo GetApiSchemaVersionMethod; private static readonly MethodInfo ClaimChallengeMethod; private static readonly DataContractJsonSerializerSettings SerializerSettings; public static bool SupportsClaim => ClaimChallengeMethod != null; public static bool IsAvailable => APIReceiver != null; public static bool SupportsHandles { get { if (StartChallengeMethod != null && GetChallengeStateMethod != null) { return StopChallengeMethod != null; } return false; } } public static int InstalledSchemaVersion { get { if (APIReceiver == null) { return 0; } if (GetApiSchemaVersionMethod != null) { return (int)GetApiSchemaVersionMethod.Invoke(null, null); } if (!SupportsHandles) { return 3; } return 4; } } static API() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown SerializerSettings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true }; APIReceiver = Type.GetType("ValheimFortress.APIReceiver, ValheimFortress"); if (!(APIReceiver == null)) { RunChallengeMethod = APIReceiver.GetMethod("RunChallenge", BindingFlags.Static | BindingFlags.Public); GetSpawnableCreaturesMethod = APIReceiver.GetMethod("GetSpawnableCreatures", BindingFlags.Static | BindingFlags.Public); GetRewardItemsMethod = APIReceiver.GetMethod("GetRewardItems", BindingFlags.Static | BindingFlags.Public); GetWaveStylesMethod = APIReceiver.GetMethod("GetWaveStyles", BindingFlags.Static | BindingFlags.Public); GetShrineChallengeDefinitionMethod = APIReceiver.GetMethod("GetShrineChallengeDefinition", BindingFlags.Static | BindingFlags.Public); GetShrineTributesMethod = APIReceiver.GetMethod("GetShrineTributes", BindingFlags.Static | BindingFlags.Public); StartChallengeMethod = APIReceiver.GetMethod("StartChallenge", BindingFlags.Static | BindingFlags.Public); GetChallengeStateMethod = APIReceiver.GetMethod("GetChallengeState", BindingFlags.Static | BindingFlags.Public); StopChallengeMethod = APIReceiver.GetMethod("StopChallenge", BindingFlags.Static | BindingFlags.Public); GetApiSchemaVersionMethod = APIReceiver.GetMethod("GetApiSchemaVersion", BindingFlags.Static | BindingFlags.Public); ClaimChallengeMethod = APIReceiver.GetMethod("ClaimChallenge", BindingFlags.Static | BindingFlags.Public); } } public static bool RunChallenge(VFChallengeDefinition definition, Vector3[] spawnPoints, Vector3 rewardLocation) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) if (RunChallengeMethod == null || definition == null) { return false; } string text = Serialize(definition); if (text == null) { return false; } object obj = RunChallengeMethod.Invoke(null, new object[3] { text, spawnPoints, rewardLocation }); bool flag = default(bool); int num; if (obj is bool) { flag = (bool)obj; num = 1; } else { num = 0; } return (byte)((uint)num & (flag ? 1u : 0u)) != 0; } public static bool RunChallenge(VFChallengeDefinition definition, List<Vector3> spawnPoints, Vector3 rewardLocation) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) return RunChallenge(definition, spawnPoints?.ToArray(), rewardLocation); } public static string StartChallenge(VFChallengeDefinition definition, Vector3[] spawnPoints, Vector3 rewardLocation) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) if (StartChallengeMethod == null || definition == null) { return null; } string text = Serialize(definition); if (text == null) { return null; } return StartChallengeMethod.Invoke(null, new object[3] { text, spawnPoints, rewardLocation }) as string; } public static VFChallengeState GetChallengeState(string handle) { if (GetChallengeStateMethod == null || string.IsNullOrEmpty(handle)) { return null; } if (!(GetChallengeStateMethod.Invoke(null, new object[1] { handle }) is Dictionary<string, int> values)) { return null; } return VFChallengeState.From(values); } public static bool StopChallenge(string handle) { if (StopChallengeMethod == null || string.IsNullOrEmpty(handle)) { return false; } object obj = StopChallengeMethod.Invoke(null, new object[1] { handle }); bool flag = default(bool); int num; if (obj is bool) { flag = (bool)obj; num = 1; } else { num = 0; } return (byte)((uint)num & (flag ? 1u : 0u)) != 0; } public static bool ClaimChallenge(string handle) { if (ClaimChallengeMethod == null || string.IsNullOrEmpty(handle)) { return false; } object obj = ClaimChallengeMethod.Invoke(null, new object[1] { handle }); bool flag = default(bool); int num; if (obj is bool) { flag = (bool)obj; num = 1; } else { num = 0; } return (byte)((uint)num & (flag ? 1u : 0u)) != 0; } public static List<string> GetSpawnableCreatures() { if (GetSpawnableCreaturesMethod == null) { return new List<string>(); } return (List<string>)GetSpawnableCreaturesMethod.Invoke(null, null); } public static List<string> GetRewardItems() { if (GetRewardItemsMethod == null) { return new List<string>(); } return (List<string>)GetRewardItemsMethod.Invoke(null, null); } public static List<string> GetWaveStyles() { if (GetWaveStylesMethod == null) { return new List<string>(); } return (List<string>)GetWaveStylesMethod.Invoke(null, null); } public static VFChallengeDefinition GetShrineChallengeDefinition(string shrineName, string tributePrefab) { if (GetShrineChallengeDefinitionMethod == null || string.IsNullOrEmpty(shrineName) || string.IsNullOrEmpty(tributePrefab)) { return null; } return Deserialize(GetShrineChallengeDefinitionMethod.Invoke(null, new object[2] { shrineName, tributePrefab }) as string); } public static Dictionary<string, List<string>> GetShrineTributes() { if (GetShrineTributesMethod == null) { return new Dictionary<string, List<string>>(); } return (Dictionary<string, List<string>>)GetShrineTributesMethod.Invoke(null, null); } private static string Serialize(VFChallengeDefinition definition) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) try { using MemoryStream memoryStream = new MemoryStream(); ((XmlObjectSerializer)new DataContractJsonSerializer(typeof(VFChallengeDefinition), SerializerSettings)).WriteObject((Stream)memoryStream, (object)definition); return Encoding.UTF8.GetString(memoryStream.ToArray()); } catch { return null; } } private static VFChallengeDefinition Deserialize(string json) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(json)) { return null; } try { using MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(json)); return ((XmlObjectSerializer)new DataContractJsonSerializer(typeof(VFChallengeDefinition), SerializerSettings)).ReadObject((Stream)memoryStream) as VFChallengeDefinition; } catch { return null; } } } [DataContract] public class VFChallengeDefinition { public const int CurrentSchemaVersion = 5; [DataMember] public int SchemaVersion { get; set; } = 5; [DataMember(EmitDefaultValue = false, IsRequired = false)] public Biome Biome { get; set; } = (Biome)1; [DataMember(EmitDefaultValue = false, IsRequired = false)] public short Difficulty { get; set; } = 1; [DataMember(EmitDefaultValue = false, IsRequired = false)] public string WaveStyle { get; set; } = "Normal"; [DataMember(EmitDefaultValue = false, IsRequired = false)] public short NumPhases { get; set; } = 4; [DataMember(EmitDefaultValue = false, IsRequired = false)] public short MaxCreaturesPerPhase { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public List<string> OnlySelectMonsters { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public List<string> ExcludeSelectMonsters { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public VFSpawnModifiers CommonSpawnModifiers { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public VFSpawnModifiers RareSpawnModifiers { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public VFSpawnModifiers EliteSpawnModifiers { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public bool HardMode { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public bool BossMode { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public bool SiegeMode { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public bool EnableCreatureDrops { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public Dictionary<string, bool> CreatureDropOverrides { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public List<VFCreatureRule> CreatureRules { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public List<List<VFHoardEntry>> ExplicitPhases { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public List<VFHoardEntry> FinalPhase { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public List<VFHoardEntry> FirstPhase { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public int PhaseIntervalSeconds { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public int MaxAliveCreatures { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public bool LoopPhases { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public List<string> CompleteWhenDead { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public Dictionary<string, short> ScaledRewards { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public Dictionary<string, short> FixedRewards { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public string WaveStartMessage { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public string WaveEndMessage { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public List<string> BetweenWavePhrases { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public bool OrderedPhrases { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public bool SuppressAnnouncements { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public bool DrawMapOverlay { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public bool SpawnPortalVisuals { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public bool HoldRewardsUntilClaimed { get; set; } } public class VFChallengeState { public bool Exists { get; set; } public bool Starting { get; set; } public bool Active { get; set; } public int Phase { get; set; } public int Phases { get; set; } public int Alive { get; set; } public bool Completed { get; set; } public bool Stopped { get; set; } public int Expected { get; set; } public int Spawned { get; set; } public int Killed => Math.Max(0, Spawned - Alive); public bool Claimable { get; set; } public int Bosses { get; set; } public int BossesSpawned { get; set; } public int BossesAlive { get; set; } public bool BossesDead { get { if (Bosses > 0 && BossesSpawned >= Bosses) { return BossesAlive == 0; } return false; } } internal static VFChallengeState From(Dictionary<string, int> values) { return new VFChallengeState { Exists = (Value("exists") != 0), Starting = (Value("starting") != 0), Active = (Value("active") != 0), Phase = Value("phase"), Phases = Value("phases"), Alive = Value("alive"), Completed = (Value("completed") != 0), Stopped = (Value("stopped") != 0), Expected = Value("expected"), Spawned = Value("spawned"), Claimable = (Value("claimable") != 0), Bosses = Value("bosses"), BossesSpawned = Value("bosses_spawned"), BossesAlive = Value("bosses_alive") }; int Value(string key) { if (!values.TryGetValue(key, out var value)) { return 0; } return value; } } } [DataContract] public class VFHoardEntry { [DataMember(EmitDefaultValue = false, IsRequired = false)] public string Creature { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public short Amount { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public short Stars { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public VFModifierSet Modifiers { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public float? HealthMultiplier { get; set; } } [DataContract] public class VFCreatureRule { [DataMember(EmitDefaultValue = false, IsRequired = false)] public List<int> Waves { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public List<string> Creatures { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public List<string> SpawnTypes { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public int? MinStars { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public int? MaxStars { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public VFModifierSet Modifiers { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public float? HealthMultiplier { get; set; } } [DataContract] public class VFModifierSet { [DataMember(EmitDefaultValue = false, IsRequired = false)] public List<string> Major { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public List<string> Minor { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public List<string> Boss { get; set; } public VFModifierSet Overlay(VFModifierSet other) { return new VFModifierSet { Major = Copy(other?.Major ?? Major), Minor = Copy(other?.Minor ?? Minor), Boss = Copy(other?.Boss ?? Boss) }; } public bool IsEmpty() { if ((Major == null || Major.Count == 0) && (Minor == null || Minor.Count == 0)) { if (Boss != null) { return Boss.Count == 0; } return true; } return false; } private static List<string> Copy(List<string> names) { if (names != null) { return new List<string>(names); } return null; } } [DataContract] public class VFSpawnModifiers { [DataMember(EmitDefaultValue = false, IsRequired = false)] public bool LinearDecreaseRandomWaveAdjustment { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public bool LinearIncreaseRandomWaveAdjustment { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public bool PartialRandomWaveAdjustment { get; set; } [DataMember(EmitDefaultValue = false, IsRequired = false)] public bool OnlyGenerateInSecondHalf { get; set; } } public static class APIReceiver { private static readonly Biome[] supported_biomes; private static readonly DataContractJsonSerializerSettings SerializerSettings; public static bool RunChallenge(string definitionJson, Vector3[] spawnPoints, Vector3 rewardLocation) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return (Object)(object)Launch(definitionJson, spawnPoints, rewardLocation) != (Object)null; } public static string StartChallenge(string definitionJson, Vector3[] spawnPoints, Vector3 rewardLocation) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) ExternalShrine externalShrine = Launch(definitionJson, spawnPoints, rewardLocation); ZNetView val = (((Object)(object)externalShrine != (Object)null) ? ((Component)externalShrine).GetComponent<ZNetView>() : null); if ((Object)(object)val == (Object)null || val.GetZDO() == null) { return null; } ZDOID uid = val.GetZDO().m_uid; return $"{((ZDOID)(ref uid)).UserID}:{((ZDOID)(ref uid)).ID}"; } public static Dictionary<string, int> GetChallengeState(string handle) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (!TryParseHandle(handle, out var id)) { return null; } Dictionary<string, int> dictionary = new Dictionary<string, int>(); ZDOMan instance = ZDOMan.instance; ZDO val = ((instance != null) ? instance.GetZDO(id) : null); if (val == null) { dictionary["exists"] = 0; return dictionary; } dictionary["exists"] = 1; dictionary["starting"] = (val.GetBool("shrine_start_challenge", false) ? 1 : 0); dictionary["active"] = (val.GetBool("shrine_challenge_active", false) ? 1 : 0); dictionary["phase"] = val.GetInt("shrine_current_phase", 0); dictionary["phases"] = val.GetInt("api_total_phases", 0); dictionary["alive"] = val.GetInt("spawned_creatures", 0); dictionary["completed"] = (val.GetBool("api_completed", false) ? 1 : 0); dictionary["stopped"] = (val.GetBool("api_stopped", false) ? 1 : 0); dictionary["expected"] = val.GetInt("api_expected_total", 0); dictionary["spawned"] = val.GetInt("api_spawned_total", 0); dictionary["claimable"] = (val.GetBool("api_claimable", false) ? 1 : 0); dictionary["bosses"] = val.GetInt("api_bosses_planned", 0); dictionary["bosses_spawned"] = val.GetInt("api_bosses_spawned", 0); dictionary["bosses_alive"] = val.GetInt("api_bosses_alive", 0); return dictionary; } public static bool StopChallenge(string handle) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) if (!TryParseHandle(handle, out var id)) { return false; } ZDOMan instance = ZDOMan.instance; ZDO val = ((instance != null) ? instance.GetZDO(id) : null); if (val == null || ZRoutedRpc.instance == null) { return false; } long owner = val.GetOwner(); if (owner == 0L) { val.SetOwner(ZDOMan.GetSessionID()); val.Set("api_stop_requested", true); return true; } ZRoutedRpc.instance.InvokeRoutedRPC(owner, id, "VF_ApiStopChallenge", Array.Empty<object>()); return true; } public static bool ClaimChallenge(string handle) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) if (!TryParseHandle(handle, out var id)) { return false; } ZDOMan instance = ZDOMan.instance; ZDO val = ((instance != null) ? instance.GetZDO(id) : null); if (val == null || ZRoutedRpc.instance == null) { return false; } long owner = val.GetOwner(); if (owner == 0L) { val.SetOwner(ZDOMan.GetSessionID()); val.Set("api_claim_requested", true); return true; } ZRoutedRpc.instance.InvokeRoutedRPC(owner, id, "VF_ApiClaimChallenge", Array.Empty<object>()); return true; } private static bool TryParseHandle(string handle, out ZDOID id) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_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) id = ZDOID.None; if (string.IsNullOrEmpty(handle)) { return false; } string[] array = handle.Split(new char[1] { ':' }); if (array.Length != 2 || !long.TryParse(array[0], out var result) || !uint.TryParse(array[1], out var result2)) { return false; } id = new ZDOID(result, result2); return id != ZDOID.None; } private static ExternalShrine Launch(string definitionJson, Vector3[] spawnPoints, Vector3 rewardLocation) { //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNetScene.instance == (Object)null) { Logger.LogWarning((object)"VF-API: RunChallenge called with no world loaded (ZNetScene is null)."); return null; } if (spawnPoints == null || spawnPoints.Length == 0) { Logger.LogWarning((object)"VF-API: RunChallenge requires at least one spawn point."); return null; } VFChallengeDefinition vFChallengeDefinition = Deserialize(definitionJson); if (vFChallengeDefinition == null) { Logger.LogWarning((object)"VF-API: RunChallenge could not parse the supplied challenge definition."); return null; } WaveCreatureSettings.Validate(vFChallengeDefinition.CreatureRules, "VF-API:"); bool first_phase_added; PhasedWaveTemplate phasedWaveTemplate = BuildWaveTemplate(vFChallengeDefinition, out first_phase_added); if (phasedWaveTemplate == null || phasedWaveTemplate.hordePhases == null || phasedWaveTemplate.hordePhases.Count == 0) { Logger.LogWarning((object)"VF-API: RunChallenge produced an empty wave template; nothing to run."); return null; } GameObject prefab = PrefabManager.Instance.GetPrefab("VF_api_challenge_runner"); if ((Object)(object)prefab == (Object)null) { Logger.LogError((object)"VF-API: runner prefab 'VF_api_challenge_runner' was not found."); return null; } GameObject val = Object.Instantiate<GameObject>(prefab, rewardLocation, Quaternion.identity); ExternalShrine component = val.GetComponent<ExternalShrine>(); if ((Object)(object)component == (Object)null) { Logger.LogError((object)"VF-API: runner prefab is missing its ExternalShrine component."); Object.Destroy((Object)(object)val); return null; } Dictionary<string, short> creatureDropOverrides = BuildDropOverrides(vFChallengeDefinition.CreatureDropOverrides); component.BeginApiChallenge(phasedWaveTemplate, spawnPoints, rewardLocation, vFChallengeDefinition.ScaledRewards, vFChallengeDefinition.FixedRewards, vFChallengeDefinition.Difficulty, vFChallengeDefinition.HardMode, vFChallengeDefinition.BossMode, vFChallengeDefinition.SiegeMode, vFChallengeDefinition.EnableCreatureDrops, creatureDropOverrides, vFChallengeDefinition.WaveStartMessage, vFChallengeDefinition.WaveEndMessage, vFChallengeDefinition.DrawMapOverlay, vFChallengeDefinition.BetweenWavePhrases, vFChallengeDefinition.OrderedPhrases, vFChallengeDefinition.SpawnPortalVisuals, vFChallengeDefinition.HoldRewardsUntilClaimed, vFChallengeDefinition.SuppressAnnouncements); int loopFrom = ((!vFChallengeDefinition.LoopPhases) ? (-1) : ((first_phase_added && phasedWaveTemplate.hordePhases.Count > 1) ? 1 : 0)); component.SetTiming(vFChallengeDefinition.PhaseIntervalSeconds, vFChallengeDefinition.MaxAliveCreatures, loopFrom, ToPrefabNames(vFChallengeDefinition.CompleteWhenDead)); Logger.LogInfo((object)$"VF-API: started challenge with {phasedWaveTemplate.hordePhases.Count} phases at {rewardLocation}."); return component; } public static int GetApiSchemaVersion() { return 5; } public static List<string> GetSpawnableCreatures() { return Monsters.SpawnableCreatures.Keys.ToList(); } public static List<string> GetRewardItems() { return RewardsData.resourceRewards.Values.Select((RewardEntry entry) => entry.resourcePrefab).Distinct().ToList(); } public static List<string> GetWaveStyles() { return Enum.GetNames(typeof(WaveStyles.WaveStyleName)).ToList(); } public static string GetShrineChallengeDefinition(string shrineName, string tributePrefab) { if (string.IsNullOrEmpty(shrineName) || string.IsNullOrEmpty(tributePrefab)) { return null; } if (shrineName.EndsWith("(Clone)")) { shrineName = shrineName.Substring(0, shrineName.Length - 7); } WildShrineConfiguration wildShrineConfigurationForSpecificShrine = WildShrineData.GetWildShrineConfigurationForSpecificShrine(shrineName); if (wildShrineConfigurationForSpecificShrine == null) { Logger.LogWarning((object)("VF-API: no wild shrine named '" + shrineName + "'. Known shrines: " + string.Join(", ", GetShrineTributes().Keys) + ".")); return null; } WildShrineLevelConfiguration wildShrineLevelConfiguration = wildShrineConfigurationForSpecificShrine.wildShrineLevelsConfig?.FirstOrDefault((WildShrineLevelConfiguration entry) => entry != null && string.Equals(entry.tributeName, tributePrefab, StringComparison.OrdinalIgnoreCase)); if (wildShrineLevelConfiguration == null || wildShrineLevelConfiguration.wildLevelDefinition == null) { Logger.LogWarning((object)("VF-API: wild shrine '" + wildShrineConfigurationForSpecificShrine.definitionForWildShrine + "' does not accept tribute '" + tributePrefab + "'. Accepted: " + string.Join(", ", TributeNames(wildShrineConfigurationForSpecificShrine)) + ".")); return null; } return Serialize(BuildShrineDefinition(wildShrineLevelConfiguration)); } public static Dictionary<string, List<string>> GetShrineTributes() { Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>(); foreach (WildShrineConfiguration wildShrineDefinition in WildShrineData.GetWildShrineDefinitions()) { if (!string.IsNullOrEmpty(wildShrineDefinition?.definitionForWildShrine) && !dictionary.ContainsKey(wildShrineDefinition.definitionForWildShrine)) { dictionary[wildShrineDefinition.definitionForWildShrine] = TributeNames(wildShrineDefinition); } } return dictionary; } private static List<string> TributeNames(WildShrineConfiguration shrine) { if (shrine.wildShrineLevelsConfig == null) { return new List<string>(); } return (from entry in shrine.wildShrineLevelsConfig where !string.IsNullOrEmpty(entry?.tributeName) select entry.tributeName).ToList(); } private static VFChallengeDefinition BuildShrineDefinition(WildShrineLevelConfiguration level) { //IL_007b: Unknown result type (might be due to invalid IL or missing references) WildLevelDefinition wildLevelDefinition = level.wildLevelDefinition; Dictionary<string, bool> dictionary = Monsters.SpawnableCreatures.Where((KeyValuePair<string, CreatureValues> entry) => entry.Value != null && entry.Value.dropsEnabled).ToDictionary((KeyValuePair<string, CreatureValues> entry) => entry.Key, (KeyValuePair<string, CreatureValues> entry) => true); return new VFChallengeDefinition { Biome = wildLevelDefinition.biome, Difficulty = wildLevelDefinition.levelIndex, WaveStyle = wildLevelDefinition.waveFormat.ToString(), NumPhases = 4, MaxCreaturesPerPhase = wildLevelDefinition.maxCreaturesPerPhaseOverride, OnlySelectMonsters = wildLevelDefinition.onlySelectMonsters, ExcludeSelectMonsters = wildLevelDefinition.excludeSelectMonsters, CommonSpawnModifiers = wildLevelDefinition.commonSpawnModifiers?.ToApi(), RareSpawnModifiers = wildLevelDefinition.rareSpawnModifiers?.ToApi(), EliteSpawnModifiers = wildLevelDefinition.eliteSpawnModifiers?.ToApi(), CreatureRules = wildLevelDefinition.creatureRules, HardMode = level.hardMode, SiegeMode = level.siegeMode, BossMode = false, ScaledRewards = level.rewards, WaveStartMessage = level.wildshrine_wave_start_localization, WaveEndMessage = level.wildshrine_wave_end_localization, EnableCreatureDrops = false, CreatureDropOverrides = ((dictionary.Count > 0) ? dictionary : null), DrawMapOverlay = VFConfig.EnableShrineMapOverlay.Value }; } private static List<string> ToPrefabNames(List<string> creatures) { CreatureValues value; return (from name in creatures?.Where((string name) => !string.IsNullOrEmpty(name)) select (!Monsters.SpawnableCreatures.TryGetValue(name, out value) || value == null) ? name : value.prefabName).Distinct().ToList(); } private static PhasedWaveTemplate BuildWaveTemplate(VFChallengeDefinition def, out bool first_phase_added) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) first_phase_added = false; if (def.ExplicitPhases != null && def.ExplicitPhases.Count > 0) { return BuildExplicitTemplate(def.ExplicitPhases, def.CreatureRules); } if (!supported_biomes.Contains(def.Biome)) { Logger.LogWarning((object)string.Format("VF-API: biome '{0}' is not supported for generated waves. Supported: {1}.", def.Biome, string.Join(", ", supported_biomes))); return null; } WaveStyles.WaveStyleName result = WaveStyles.WaveStyleName.Normal; if (!string.IsNullOrEmpty(def.WaveStyle) && !Enum.TryParse<WaveStyles.WaveStyleName>(def.WaveStyle, out result)) { Logger.LogWarning((object)("VF-API: unknown wave style '" + def.WaveStyle + "', defaulting to Normal.")); result = WaveStyles.WaveStyleName.Normal; } short override_max_creatures = ((def.MaxCreaturesPerPhase > 0) ? def.MaxCreaturesPerPhase : VFConfig.ChallengeShrineMaxCreaturesPerWave.Value); PhasedWaveTemplate phasedWaveTemplate = Levels.generateRandomWaveWithOptions(new ChallengeLevelDefinition { levelName = "VF_API", levelIndex = def.Difficulty, numPhases = (short)((def.NumPhases > 0) ? def.NumPhases : 4), levelForShrineTypes = new Dictionary<ShrineType, bool> { { ShrineType.Wild, true } }, levelMenuLocalization = "", requiredGlobalKey = "NONE", biome = def.Biome, waveFormat = result, bossWaveFormat = result, maxCreatureFromPreviousBiomes = 0, levelWarningLocalization = "", bossLevelWarningLocalization = "", onlySelectMonsters = def.OnlySelectMonsters, excludeSelectMonsters = def.ExcludeSelectMonsters, commonSpawnModifiers = SpawnModifiers.FromApi(def.CommonSpawnModifiers), rareSpawnModifiers = SpawnModifiers.FromApi(def.RareSpawnModifiers), eliteSpawnModifiers = SpawnModifiers.FromApi(def.EliteSpawnModifiers), uniqueSpawnModifiers = new SpawnModifiers(), creatureRules = def.CreatureRules }, def.HardMode, def.BossMode, def.SiegeMode, override_max_creatures); if (phasedWaveTemplate?.hordePhases == null) { return phasedWaveTemplate; } List<KeyValuePair<HoardConfig, VFHoardEntry>> entry_settings = new List<KeyValuePair<HoardConfig, VFHoardEntry>>(); List<HoardConfig> list = BuildPhase(def.FinalPhase, entry_settings); List<HoardConfig> list2 = BuildPhase(def.FirstPhase, entry_settings); if (list.Count > 0) { phasedWaveTemplate.hordePhases.Add(list); } if (list2.Count > 0) { phasedWaveTemplate.hordePhases.Insert(0, list2); } if (list.Count > 0 || list2.Count > 0) { WaveCreatureSettings.ApplyRules(phasedWaveTemplate, def.CreatureRules); ApplyEntrySettings(entry_settings); } first_phase_added = list2.Count > 0; return phasedWaveTemplate; } private static PhasedWaveTemplate BuildExplicitTemplate(List<List<VFHoardEntry>> phases, List<VFCreatureRule> rules) { List<List<HoardConfig>> list = new List<List<HoardConfig>>(); List<KeyValuePair<HoardConfig, VFHoardEntry>> entry_settings = new List<KeyValuePair<HoardConfig, VFHoardEntry>>(); foreach (List<VFHoardEntry> phase in phases) { List<HoardConfig> list2 = BuildPhase(phase, entry_settings); if (list2.Count > 0) { list.Add(list2); } } if (list.Count == 0) { return null; } PhasedWaveTemplate obj = new PhasedWaveTemplate { hordePhases = list }; WaveCreatureSettings.ApplyRules(obj, rules); ApplyEntrySettings(entry_settings); return obj; } private static List<HoardConfig> BuildPhase(List<VFHoardEntry> phase, List<KeyValuePair<HoardConfig, VFHoardEntry>> entry_settings) { List<HoardConfig> list = new List<HoardConfig>(); if (phase == null) { return list; } foreach (VFHoardEntry item in phase) { if (item == null || string.IsNullOrEmpty(item.Creature) || item.Amount <= 0) { continue; } if (!Monsters.SpawnableCreatures.ContainsKey(item.Creature)) { Logger.LogWarning((object)("VF-API: explicit creature '" + item.Creature + "' is not a known VF creature, skipping. Use GetSpawnableCreatures() for valid names.")); continue; } HoardConfig hoardConfig = new HoardConfig { creature = item.Creature, prefab = Monsters.SpawnableCreatures[item.Creature].prefabName, amount = item.Amount, stars = item.Stars }; list.Add(hoardConfig); if (item.Modifiers != null || item.HealthMultiplier.HasValue) { entry_settings.Add(new KeyValuePair<HoardConfig, VFHoardEntry>(hoardConfig, item)); } } return list; } private static void ApplyEntrySettings(List<KeyValuePair<HoardConfig, VFHoardEntry>> entry_settings) { foreach (KeyValuePair<HoardConfig, VFHoardEntry> entry_setting in entry_settings) { WaveCreatureSettings.ApplyModifiers(entry_setting.Key, entry_setting.Value.Modifiers); if (entry_setting.Value.HealthMultiplier.HasValue) { entry_setting.Key.healthMultiplier = entry_setting.Value.HealthMultiplier.Value; } } } private static Dictionary<string, short> BuildDropOverrides(Dictionary<string, bool> overrides) { Dictionary<string, short> dictionary = new Dictionary<string, short>(); if (overrides == null) { return dictionary; } foreach (KeyValuePair<string, bool> @override in overrides) { if (!string.IsNullOrEmpty(@override.Key)) { if (!Monsters.SpawnableCreatures.ContainsKey(@override.Key)) { Logger.LogWarning((object)("VF-API: creature drop override '" + @override.Key + "' is not a known VF creature, skipping. Use GetSpawnableCreatures() for valid names.")); } else { dictionary[@override.Key] = (@override.Value ? ((short)1) : ((short)0)); } } } return dictionary; } private static string Serialize(VFChallengeDefinition def) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) try { using MemoryStream memoryStream = new MemoryStream(); ((XmlObjectSerializer)new DataContractJsonSerializer(typeof(VFChallengeDefinition), SerializerSettings)).WriteObject((Stream)memoryStream, (object)def); return Encoding.UTF8.GetString(memoryStream.ToArray()); } catch (Exception arg) { Logger.LogError((object)$"VF-API: failed to serialize challenge definition: {arg}"); return null; } } private static VFChallengeDefinition Deserialize(string json) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(json)) { return null; } try { using MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(json)); if (!(((XmlObjectSerializer)new DataContractJsonSerializer(typeof(VFChallengeDefinition), SerializerSettings)).ReadObject((Stream)memoryStream) is VFChallengeDefinition vFChallengeDefinition)) { Logger.LogError((object)"VF-API: challenge definition deserialized to null / an unexpected type."); return null; } if (vFChallengeDefinition.SchemaVersion > 5) { Logger.LogWarning((object)($"VF-API: challenge definition schema version mismatch (received {vFChallengeDefinition.SchemaVersion}, expected {5}). " + "The calling mod was built for a newer Valheim Fortress; settings this version does not know are ignored. Attempting to continue.")); } return vFChallengeDefinition; } catch (Exception arg) { Logger.LogError((object)$"VF-API: failed to deserialize challenge definition: {arg}"); return null; } } static APIReceiver() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown Biome[] array = new Biome[8]; RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); supported_biomes = (Biome[])(object)array; SerializerSettings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true }; } } internal static class Logger { public static LogLevel Level = (LogLevel)4; public static void enableDebugLogging() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (VFConfig.EnableDebugMode.Value) { Level = (LogLevel)32; } else { Level = (LogLevel)4; } } public static void toggleDebug(object s, EventArgs e) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (VFConfig.EnableDebugMode.Value) { Level = (LogLevel)32; } else { Level = (LogLevel)4; } } public static void LogDebug(string message) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 if ((int)Level >= 32) { ValheimFortress.Log.LogInfo((object)message); } } public static void LogInfo(string message) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 if ((int)Level >= 16) { ValheimFortress.Log.LogInfo((object)message); } } public static void LogWarning(string message) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 if ((int)Level >= 4) { ValheimFortress.Log.LogWarning((object)message); } } public static void LogError(string message) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 if ((int)Level >= 2) { ValheimFortress.Log.LogError((object)message); } } } internal class ValheimFortressPieces { private JotunnPieceLoader Loader = new JotunnPieceLoader(); public ValheimFortressPieces() { Logger.LogInfo("Loading Pieces."); LoadAlterOfChallenge(); LoadDefenses(); Loader.BatchSetup(ValheimFortress.EmbeddedResourceBundle); } private void LoadAlterOfChallenge() { PieceDefinition pieceDefinition = new PieceDefinition(); pieceDefinition.Name = "Alter of Challenge"; pieceDefinition.Category = PieceCategory.Misc; pieceDefinition.prefab = "VFshrine_of_challenge"; pieceDefinition.enabled = true; pieceDefinition.requiredWorkstation = "piece_workbench"; pieceDefinition.recipe = new PieceCostDefinition { recipeItems = new List<PieceIngredient> { new PieceIngredient { prefab = "Stone", amount = 34, refund = true }, new PieceIngredient { prefab = "Ruby", amount = 4, refund = true }, new PieceIngredient { prefab = "Coins", amount = 100, refund = false } } }; pieceDefinition.setupScripts = delegate(GameObject go) { go.AddComponent<ChallengeShrine>(); go.AddComponent<ChallengeShrineUI>(); go.AddComponent<Spawner>(); }; Loader.AddPiece(pieceDefinition); PieceDefinition pieceDefinition2 = new PieceDefinition(); pieceDefinition2.Name = "Alter of Arena"; pieceDefinition2.Category = PieceCategory.Misc; pieceDefinition2.prefab = "VFshine_of_gladiator"; pieceDefinition2.enabled = true; pieceDefinition2.requiredWorkstation = "piece_workbench"; pieceDefinition2.recipe = new PieceCostDefinition { recipeItems = new List<PieceIngredient> { new PieceIngredient { prefab = "Stone", amount = 23, refund = true }, new PieceIngredient { prefab = "Coins", amount = 100, refund = false } } }; pieceDefinition2.setupScripts = delegate(GameObject go) { go.AddComponent<ArenaShrine>(); go.AddComponent<ArenaShrineUI>(); go.AddComponent<Spawner>(); }; Loader.AddPiece(pieceDefinition2); } private void LoadDefenses() { PieceDefinition pieceDefinition = new PieceDefinition(); pieceDefinition.Name = "Stone Spikes"; pieceDefinition.Category = PieceCategory.Misc; pieceDefinition.prefab = "VFstone_stakes"; pieceDefinition.enabled = true; pieceDefinition.requiredWorkstation = "piece_stonecutter"; pieceDefinition.recipe = new PieceCostDefinition { recipeItems = new List<PieceIngredient> { new PieceIngredient { prefab = "Stone", amount = 30, refund = false }, new PieceIngredient { prefab = "Silver", amount = 2, refund = true } } }; Loader.AddPiece(pieceDefinition); PieceDefinition pieceDefinition2 = new PieceDefinition(); pieceDefinition2.Name = "Auto Ballista"; pieceDefinition2.Category = PieceCategory.Misc; pieceDefinition2.prefab = "VFpiece_turret"; pieceDefinition2.enabled = true; pieceDefinition2.requiredWorkstation = "piece_artisanstation"; pieceDefinition2.recipe = new PieceCostDefinition { recipeItems = new List<PieceIngredient> { new PieceIngredient { prefab = "BlackMetal", amount = 20, refund = true }, new PieceIngredient { prefab = "YggdrasilWood", amount = 20, refund = true }, new PieceIngredient { prefab = "MechanicalSpring", amount = 5, refund = true }, new PieceIngredient { prefab = "DragonTear", amount = 2, refund = true } } }; pieceDefinition2.setupScripts = delegate(GameObject go) { go.AddComponent<VFTurret>(); }; VFConfig.BallistaDamage.SettingChanged += BallistaOnChange.BallistaDamageChange; VFConfig.BallistaRange.SettingChanged += BallistaOnChange.BallistaRange_SettingChanged; VFConfig.BallistaAmmoAccuracyPenalty.SettingChanged += BallistaOnChange.BallistaAmmoAccuracyPenalty_SettingChanged; VFConfig.BallistaCooldownTime.SettingChanged += BallistaOnChange.BallistaCooldownTime_SettingChanged; Loader.AddPiece(pieceDefinition2); } } [BepInPlugin("MidnightsFX.ValheimFortress", "ValheimFortress", "0.41.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] internal class ValheimFortress : BaseUnityPlugin { public const string PluginGUID = "MidnightsFX.ValheimFortress"; public const string PluginName = "ValheimFortress"; public const string PluginVersion = "0.41.0"; public const string ApiChallengeRunnerPrefab = "VF_api_challenge_runner"; internal static Harmony Harmony = new Harmony("MidnightsFX.ValheimFortress"); public static AssetBundle EmbeddedResourceBundle; public VFConfig cfg; internal static CustomLocalization LocalizationInstance; public static ManualLogSource Log; public static GameObject spawnPortal; public static GameObject creatureNotifier; public static GameObject portalDestroyVFX; private static readonly Regex sWhitespace = new Regex("\\s+"); public void Awake() { cfg = new VFConfig(((BaseUnityPlugin)this).Config); Log = ((BaseUnityPlugin)this).Logger; cfg.SetupConfigRPCs(); EmbeddedResourceBundle = AssetUtils.LoadAssetBundleFromResources("ValheimFortress.AssetsEmbedded.vfbundle", typeof(ValheimFortress).Assembly); AddLocalizations(); new ValheimFortressPieces(); SetupVFXObjects(EmbeddedResourceBundle); SetupAPIRunnerPrefab(); new VFLocations(EmbeddedResourceBundle, cfg); VFConfig.GetYamlConfigFiles(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Valheim Fortress loaded."); Assembly executingAssembly = Assembly.GetExecutingAssembly(); Harmony.PatchAll(executingAssembly); } private void AddLocalizations() { LocalizationInstance = LocalizationManager.Instance.GetLocalization(); string text = Path.Combine(Paths.ConfigPath, "VFortress", "Localizations"); Directory.CreateDirectory(text); string[] manifestResourceNames = typeof(ValheimFortress).Assembly.GetManifestResourceNames(); foreach (string text2 in manifestResourceNames) { if (!text2.Contains("Localizations")) { continue; } string text3 = Regex.Replace(ReadEmbeddedResourceFile(text2), "\\/\\/.*", ""); Dictionary<string, string> internal_localization = SimpleJson.DeserializeObject<Dictionary<string, string>>(text3); string[] array = text2.Split(new char[1] { '.' }); if (File.Exists(text + "/" + array[2] + ".json")) { string text4 = File.ReadAllText(text + "/" + array[2] + ".json"); try { Dictionary<string, string> dictionary = SimpleJson.DeserializeObject<Dictionary<string, string>>(text4); UpdateLocalizationWithMissingKeys(internal_localization, dictionary); ((BaseUnityPlugin)this).Logger.LogDebug((object)("Reading " + text + "/" + array[2] + ".json")); File.WriteAllText(text + "/" + array[2] + ".json", SimpleJson.SerializeObject((object)dictionary)); string text5 = File.ReadAllText(text + "/" + array[2] + ".json"); LocalizationInstance.AddJsonFile(array[2], text5); } catch { File.WriteAllText(text + "/" + array[2] + ".json", text3); ((BaseUnityPlugin)this).Logger.LogDebug((object)("Reading " + text2)); LocalizationInstance.AddJsonFile(array[2], text3); } } else { File.WriteAllText(text + "/" + array[2] + ".json", text3); ((BaseUnityPlugin)this).Logger.LogDebug((object)("Reading " + text2)); LocalizationInstance.AddJsonFile(array[2], text3); } ((BaseUnityPlugin)this).Logger.LogDebug((object)("Added localization: '" + array[2] + "'")); } } private void UpdateLocalizationWithMissingKeys(Dictionary<string, string> internal_localization, Dictionary<string, string> cached_localization) { if (internal_localization.Keys.Count == cached_localization.Keys.Count) { return; } ((BaseUnityPlugin)this).Logger.LogDebug((object)"Cached localization was missing some entries. They will be added."); foreach (KeyValuePair<string, string> item in internal_localization) { if (!cached_localization.ContainsKey(item.Key)) { cached_localization.Add(item.Key, item.Value); } } } internal static GameObject getPortal() { return spawnPortal; } internal static GameObject getNotifier() { return creatureNotifier; } internal static GameObject getPortalDestroyVFX() { return portalDestroyVFX; } private static void SetupVFXObjects(AssetBundle EmbeddedResourceBundle) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown CustomPrefab val = new CustomPrefab(EmbeddedResourceBundle.LoadAsset<GameObject>("Assets/Custom/Pieces/VFortress/VF_portal.prefab"), false); PrefabManager.Instance.AddPrefab(val); spawnPortal = val.Prefab; CustomPrefab val2 = new CustomPrefab(EmbeddedResourceBundle.LoadAsset<GameObject>("Assets/Custom/Pieces/VFortress/VF_portal_destroy.prefab"), false); PrefabManager.Instance.AddPrefab(val2); portalDestroyVFX = val2.Prefab; CustomPrefab val3 = new CustomPrefab(EmbeddedResourceBundle.LoadAsset<GameObject>("Assets/Custom/Pieces/VFortress/VF_creature_notify.prefab"), false); PrefabManager.Instance.AddPrefab(val3); creatureNotifier = val3.Prefab; } private static void SetupAPIRunnerPrefab() { //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Expected O, but got Unknown GameObject val = PrefabManager.Instance.CreateEmptyPrefab("VF_api_challenge_runner", true); if (!((Object)(object)val == (Object)null)) { MeshRenderer[] componentsInChildren = val.GetComponentsInChildren<MeshRenderer>(true); for (int i = 0; i < componentsInChildren.Length; i++) { Object.DestroyImmediate((Object)(object)componentsInChildren[i]); } MeshFilter[] componentsInChildren2 = val.GetComponentsInChildren<MeshFilter>(true); for (int i = 0; i < componentsInChildren2.Length; i++) { Object.DestroyImmediate((Object)(object)componentsInChildren2[i]); } Collider[] componentsInChildren3 = val.GetComponentsInChildren<Collider>(true); for (int i = 0; i < componentsInChildren3.Length; i++) { Object.DestroyImmediate((Object)(object)componentsInChildren3[i]); } ZNetView component = val.GetComponent<ZNetView>(); if ((Object)(object)component != (Object)null) { component.m_persistent = true; } val.AddComponent<Spawner>(); val.AddComponent<ExternalShrine>(); PrefabManager.Instance.AddPrefab(new CustomPrefab(val, false)); } } public static string LocalizeOrDefault(string str_to_localize, string default_string) { string text = LocalizationInstance.TryTranslate(str_to_localize); if (text == "[" + str_to_localize.Replace("$", "") + "]") { Logger.LogDebug((object)(str_to_localize + " was not localized, returning the default: " + default_string)); return default_string; } return text; } internal static string ReadEmbeddedResourceFile(string filename) { using Stream stream = typeof(ValheimFortress).Assembly.GetManifestResourceStream(filename); using StreamReader streamReader = new StreamReader(stream); return streamReader.ReadToEnd(); } public static List<string> shuffleList(List<string> inputList) { int i = 0; int count = inputList.Count; int num = 0; string text = null; List<string> list = new List<string>(); list.AddRange(inputList); for (; i < count; i++) { num = Random.Range(i, list.Count); text = list[i]; list[i] = list[num]; list[num] = text; } return list; } public static string FormatJson(string json, string indent = " ") { int indentation = 0; int quoteCount = 0; int escapeCount = 0; return string.Concat((from ch in json ?? string.Empty let escaped = ((ch == '\\') ? escapeCount++ : ((escapeCount > 0) ? escapeCount-- : escapeCount)) > 0 let quotes = (ch == '"' && !escaped) ? quoteCount++ : quoteCount let unquoted = quotes % 2 == 0 let colon = (ch == ':' && unquoted) ? ": " : null let nospace = (char.IsWhiteSpace(ch) && unquoted) ? string.Empty : null let lineBreak = (ch == ',' && unquoted) ? string.Concat(ch.ToString(), Environment.NewLine, string.Concat(Enumerable.Repeat(indent, indentation))) : null let openChar = ((ch == '{' || ch == '[') && unquoted) ? string.Concat(ch.ToString(), Environment.NewLine, string.Concat(Enumerable.Repeat(indent, ++indentation))) : ch.ToString() select new { <>h__TransparentIdentifier6 = <>h__TransparentIdentifier6, closeChar = (((ch == '}' || ch == ']') && unquoted) ? string.Concat(Environment.NewLine, string.Concat(Enumerable.Repeat(indent, --indentation)), ch.ToString()) : ch.ToString()) }).Select(<>h__TransparentIdentifier7 => { string text = <>h__TransparentIdentifier7.<>h__TransparentIdentifier6.<>h__TransparentIdentifier5.<>h__TransparentIdentifier4.<>h__TransparentIdentifier3.colon; if (text == null) { text = <>h__TransparentIdentifier7.<>h__TransparentIdentifier6.<>h__TransparentIdentifier5.<>h__TransparentIdentifier4.nospace; if (text == null) { text = <>h__TransparentIdentifier7.<>h__TransparentIdentifier6.<>h__TransparentIdentifier5.lineBreak; if (text == null) { if (<>h__TransparentIdentifier7.<>h__TransparentIdentifier6.openChar.Length <= 1) { return <>h__TransparentIdentifier7.closeChar; } text = <>h__TransparentIdentifier7.<>h__TransparentIdentifier6.openChar; } } } return text; })); } public static string ReplaceWhitespace(string input, string replacement) { return sWhitespace.Replace(input, replacement); } } internal class VFConfig { public static ConfigFile cfg; public static ConfigEntry<bool> EnableDebugMode; public static ConfigEntry<bool> EnableTurretDebugMode; public static ConfigEntry<bool> BallistaTargetsPassives; public static ConfigEntry<float> BallistaDamage; public static ConfigEntry<float> BallistaRange; public static ConfigEntry<float> BallistaAmmoAccuracyPenalty; public static ConfigEntry<short> BallistaTargetUpdateCacheInterval; public static ConfigEntry<bool> BallistaEnableShotSafetyCheck; public static ConfigEntry<float> BallistaCooldownTime; public static ConfigEntry<short> MaxSpawnRange; public static ConfigEntry<short> NumberOfRemoteSpawnPoints; public static ConfigEntry<float> rewardsMultiplier; public static ConfigEntry<float> rewardsDifficultyScalar; public static ConfigEntry<bool> EnableBossModifier; public static ConfigEntry<bool> EnableHardModifier; public static ConfigEntry<bool> EnableSiegeModifer; public static ConfigEntry<bool> EnableRewardsEstimate; public static ConfigEntry<bool> EnableMapPings; public static ConfigEntry<bool> EnableShrineMapOverlay; public static ConfigEntry<short> MaxRewardsPerSecond; public static ConfigEntry<bool> ScaleRewardsFromWorldSetting; public static ConfigEntry<short> NotifyCreatureThreshold; public static ConfigEntry<short> TeleportCreatureThreshold; public static ConfigEntry<short> ShrineReconnectPauseBetweenAmount; public static ConfigEntry<float> ShrineStallTimeout; public static ConfigEntry<float> ShrineAnnouncementRange; public static ConfigEntry<float> DistanceBetweenShrines; public static ConfigEntry<float> ShrineReconnectRange; public static ConfigEntry<short> NumberOfEachWildShrine; public static ConfigEntry<short> ChallengeShrineMaxCreaturesPerWave; public static ConfigEntry<short> ArenaShrineMaxCreaturesPerWave; public static ConfigEntry<float> ShrineRewardPlayerBonus; public static ConfigEntry<bool> ServerConfigsLocked; public static ConfigEntry<short> BaseChallengePoints; public static ConfigEntry<short> MaxChallengePoints; public static ConfigEntry<float> ChallengeSlope; public static ConfigEntry<float> ChanceOfPreviousBiomeCreature; public static ConfigEntry<short> MaxCreatureStars; private static CustomRPC monsterSyncRPC; private static CustomRPC rewardSyncRPC; private static CustomRPC WavesSyncRPC; private static CustomRPC LevelsSyncRPC; private static CustomRPC WildShrineSyncRPC; private static string rewardFilePath = Path.Combine(Paths.ConfigPath, "VFortress", "Rewards.yaml"); private static string creatureFilePath = Path.Combine(Paths.ConfigPath, "VFortress", "SpawnableCreatures.yaml"); private static string waveStylesFilePath = Path.Combine(Paths.ConfigPath, "VFortress", "WaveStyles.yaml"); private static string levelDefinitionsFilePath = Path.Combine(Paths.ConfigPath, "VFortress", "Levels.yaml"); private static string wildShrineConfigurationFilePath = Path.Combine(Paths.ConfigPath, "VFortress", "WildShrines.yaml"); public VFConfig(ConfigFile Config) { cfg = Config; cfg.SaveOnConfigSet = true; CreateConfigValues(Config); Logger.enableDebugLogging(); string configPath = Paths.ConfigPath; FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(); fileSystemWatcher.Path = configPath; fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite; fileSystemWatcher.Filter = "MidnightsFX.ValheimFortress.cfg"; fileSystemWatcher.Changed += UpdateMainConfigFile; fileSystemWatcher.Created += UpdateMainConfigFile; fileSystemWatcher.Renamed += UpdateMainConfigFile; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; Logger.LogInfo((object)"Main config filewatcher initialized."); } public static void SaveOnSet(bool enabled) { cfg.SaveOnConfigSet = enabled; cfg.Save(); } public void SetupConfigRPCs() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown //IL_0027: Expected O, but got Unknown //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown //IL_0053: Expected O, but got Unknown //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown //IL_007f: Expected O, but got Unknown //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_00ab: Expected O, but got Unknown //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Expected O, but got Unknown //IL_00d7: Expected O, but got Unknown monsterSyncRPC = NetworkManager.Instance.AddRPC("monsteryaml_rpc", new CoroutineHandler(OnServerRecieveConfigs), new CoroutineHandler(OnClientReceiveCreatureConfigs)); rewardSyncRPC = NetworkManager.Instance.AddRPC("rewardsyaml_rpc", new CoroutineHandler(OnServerRecieveConfigs), new CoroutineHandler(OnClientReceiveRewardsConfigs)); WavesSyncRPC = NetworkManager.Instance.AddRPC("wavestyleyaml_rpc", new CoroutineHandler(OnServerRecieveConfigs), new CoroutineHandler(OnClientReceiveWaveConfigs)); LevelsSyncRPC = NetworkManager.Instance.AddRPC("levelsyaml_rpc", new CoroutineHandler(OnServerRecieveConfigs), new CoroutineHandler(OnClientReceiveLevelConfigs)); WildShrineSyncRPC = NetworkManager.Instance.AddRPC("wildshrineyaml_rpc", new CoroutineHandler(OnServerRecieveConfigs), new CoroutineHandler(OnClientReceiveWildShrineConfigs)); SynchronizationManager.Instance.AddInitialSynchronization(monsterSyncRPC, (Func<ZPackage>)SendCreatureConfigs); SynchronizationManager.Instance.AddInitialSynchronization(rewardSyncRPC, (Func<ZPackage>)SendRewardsConfigs); SynchronizationManager.Instance.AddInitialSynchronization(WavesSyncRPC, (Func<ZPackage>)SendWavesConfigs); SynchronizationManager.Instance.AddInitialSynchronization(LevelsSyncRPC, (Func<ZPackage>)SendLevelsConfigs); SynchronizationManager.Instance.AddInitialSynchronization(WildShrineSyncRPC, (Func<ZPackage>)SendWildShrineConfigs); } public static string GetSecondaryConfigDirectoryPath() { return Directory.CreateDirectory(Path.Combine(Paths.ConfigPath, "VFortress")).FullName; } public static void GetYamlConfigFiles() { string secondaryConfigDirectoryPath = GetSecondaryConfigDirectoryPath(); bool flag = false; bool flag2 = false; bool flag3 = false; bool flag4 = false; bool flag5 = false; string[] files = Directory.GetFiles(secondaryConfigDirectoryPath); foreach (string text in files) { Logger.LogInfo((object)("Config file found: " + text)); if (text.Contains("Rewards.yaml")) { Logger.LogInfo((object)("Found rewards configuration: " + text)); rewardFilePath = text; flag = true; } if (text.Contains("SpawnableCreatures.yaml")) { Logger.LogInfo((object)("Found Creature configuration: " + text)); creatureFilePath = text; flag2 = true; } if (text.Contains("WaveStyles.yaml")) { Logger.LogInfo((object)("Found WaveStyles configuration: " + text)); waveStylesFilePath = text; flag3 = true; } if (text.Contains("Levels.yaml")) { Logger.LogInfo((object)("Found Levels configuration: " + text)); levelDefinitionsFilePath = text; flag4 = true; } if (text.Contains("WildShrines.yaml")) { Logger.LogInfo((object)("Found WildShrine configuration: " + text)); wildShrineConfigurationFilePath = text; flag5 = true; } } if (!flag) { Logger.LogInfo((object)"Rewards file missing, recreating."); using StreamWriter streamWriter = new StreamWriter(rewardFilePath); string value = "#################################################\n# Shrine of Challenge Rewards Configuration\n#################################################\n# Rewards configurations have a number of key values\n# Coin: |- The name of the reward, this will be the diplayed name if there is no localization for this reward, which is likely the case for any custom entries.\n# enabled: true |- Whether or not the reward is enabled, you can use this to disable any vanilla rewards you do not want. At least 1 reward must be available at ALL times.\n# resourceCost: 5 |- This is the cost to gain 1 of the particular reward. Points are generated based on how many monsters are spawned.\n# resourcePrefab: \"Coins\" |- This is the unity prefab name for a resource, you will often see mods list the prefabs they have added. Prefabs are also listed on the valheim wiki.\n# requiredBoss: \"None\" |- This must be one of the following values: \"None\" \"Eikythr\" \"TheElder\" \"BoneMass\" \"Moder\" \"Yagluth\" \"TheQueen\"\n"; streamWriter.WriteLine(value); streamWriter.WriteLine(RewardsData.YamlRewardsDefinition()); } if (!flag3) { Logger.LogInfo((object)"WaveStyles file missing, recreating."); using StreamWriter streamWriter2 = new StreamWriter(waveStylesFilePath); string value2 = "#################################################\n# Shrine of Challenge WaveStyles Configuration\n#################################################\n# WaveStyles configurations have a number of key values\n# Easy: |- This is the key used to lookup this wave definition\n# WaveConfig |- The wave configuration for each segment of the wave\n# - type: COMMON |- This is the catagory of creature that will be selected\n# percent: 30 |- This is the percentage of the waves total point pool that will be used for this spawn"; streamWriter2.WriteLine(value2); streamWriter2.WriteLine(WaveStyles.YamlWaveDefinition()); } if (!flag4) { Logger.LogInfo((object)"LevelsConfig file missing, recreating."); using StreamWriter streamWriter3 = new StreamWriter(levelDefinitionsFilePath); string value3 = "#################################################\n# Shrines of Challenge Levels Configuration\n#################################################\n# levels:\n# - levelIndex: 1 |- LevelIndex is the difficulty this wave is set at, valid values are 1+\n# creatureRules: |- Optional stars and Star Level System (SLS) modifiers. Rules apply top to bottom; each matching rule overwrites what it sets\n# - minStars: 1 |- A rule with no waves, creatures or spawnTypes matches every creature in every wave\n# maxStars: 3 |- 0 forces no stars. Both override the global star cap; when they conflict the later rule wins\n# modifiers: {minor: [Fast]} |- Guaranteed SLS modifiers by type (major, minor, boss); a list replaces only its own type, [] clears it\n# - creatures: [Troll] |- Creature names from SpawnableCreatures.yaml, case-insensitive\n# minStars: 4\n# modifiers: {major: [Fire]} |- Trolls end up with Fast and Fire\n# - waves: [-1] |- 1-based wave numbers in spawn order (siege mode doubles the count); negative counts from the end, -1 is the boss wave\n# spawnTypes: [unique] |- common, rare, elite or unique\n# modifiers: {boss: [BossSummoner]} |- Needs SLS. Creatures given modifiers skip SLS's random ones, and SLS keeps one modifier per star by default\n# numPhases: 4 |- The number of phases in this level, enemies will be distributed among the phases\n# levelForShrineTypes: |- What shrines will host this level, multiple definitions can be applied\n# challenge: true |- Shrine of challenge will host this level\n# arena: true |- Shrine of the arena will host this level\n# levelMenuLocalization: $shrine_menu_meadow |- This is the localization that will be displayed when selecting the level, if no key matches the $lookup the literal string will be used\n# requiredGlobalKey: NONE |- This is the global key required to unlock this level more available here (https://valheim.fandom.com/wiki/Global_Keys)\n# biome: Meadows |- This is the biome used for this level. This determines what creatures are considered\n# waveFormat: Tutorial |- This is the format of the wave, formates are defined in WaveStyles.yaml, it determines how many creatures, what catagory and percentage of total points they use\n# bossWaveFormat: TutorialBoss |- This is the format if the wave is modified to be a boss wave\n# maxCreatureFromPreviousBiomes: 0 |- This is the maximum number of creatures that can be selected from prior biomes\n# previousBiomeSearchRange: 1 |- How many previous biomes to look back for potential creatures\n# chancePreviousBiomeCreatureSelected: 0.05 |- Chance that a creature will be selected from a previous biome, if it can be\n# previousBiomeCreaturesAddedStarPerBiome: true |- Automatically upgrades creatures from a previous biome, one star per biome difference (up to max defined stars)\n# levelWarningLocalization: $shrine_warning_meadows |- This is the announcement text that plays when the challenge starts as a normal wave, uses literal value if the localization does not exist\n# bossLevelWarningLocalization: $shrine_warning_meadows_boss |- This is the announcement text that plays when the challenge starts as a boss wave, localizations are available here https://github.com/MidnightsFX/Valheim_Fortress/blob/master/JotunnModStub/Localizations/English.json\n# onlySelectMonsters: [] |- This is an array of monsters that are the only valid targets for this wave\n# excludeSelectMonsters: [] |- This is an array of monsters that are to be avoided for the wave\n# levelRewardOptionsLimitedTo: |- When set, only the available rewards can be selected for this level, rewards still have their normal global key requirements\n# - Coin |- The rewards entry name of rewards that should be available for this level\n# commonSpawnModifiers: |- Spawn modifiers are functions applied to each part of the wave, they can be different per catagory of monster\n# linearIncreaseRandomWaveAdjustment: true |- In general, it is best to only use one type of spawn modifier per creature type\n# linearDecreaseRandomWaveAdjustment: false |- Linear Decrease/Increase will frontload or backload this creature in the various phase of the wave, meaning more of it will appear earlier or later depending on the modifier\n# partialRandomWaveAdjustment: false |- Partial random adjustment will add more significant random variance to the number of creatures that will spawn\n# onlyGenerateInSecondHalf: false |- Only generate in second half will prevent this type of creature from spawning in the earlier waves, this is useful for Elites/Rares when LinearDecrease is set for commons\n# rareSpawnModifiers: |- The start of the wave will have many commons, and they will taper off till the end, while elites would come into play only on the second half of the wave\n# linearIncreaseRandomWaveAdjustment: true\n# linearDecreaseRandomWaveAdjustment: false\n# partialRandomWaveAdjustment: false\n# onlyGenerateInSecondHalf: false\n# eliteSpawnModifiers:\n# linearIncreaseRandomWaveAdjustment: true\n# linearDecreaseRandomWaveAdjustment: false\n# partialRandomWaveAdjustment: false\n# onlyGenerateInSecondHalf: false\n# uniqueSpawnModifiers: "; streamWriter3.WriteLine(value3); streamWriter3.WriteLine(ChallengeLevels.YamlLevelsDefinition()); } if (!flag2) { Logger.LogInfo((object)"CreatureConfig file missing, recreating."); using StreamWriter streamWriter4 = new StreamWriter(creatureFilePath); string value4 = "#################################################\n# Shrine of Challenge Creature Configuration\n#################################################\n# Creature configurations have a number of key values\n# Neck: |- This is the name of the creature being added, it is primarily used for display purposes and lookups\n# spawnCost: 5 |- This is how many points from the wave pool it costs to spawn one creature, smaller values allow many more spawns.\n# prefab: \"Neck\" |- This is the creatures prefab, which will be used to spawn it.\n# spawnType: \"common\" |- This can either be: \"common\" or \"rare\" or \"elite\" or \"unique\", uniques are \"bosses\", most of the wave will be made up of more common enemies\n# enabled: true |- This controls if this creature will be included in wave-generation.\n# dropsEnabled: false |- This controls if this particular monster should drop loot. Disabled by default for everything.\n# biome: \"Meadows\" |- This must be one of the following values: \"Meadows\", \"BlackForest\", \"Swamp\", \"Mountain\", \"Plains\", \"Mistlands\". The biome determines the levels that will recieve this spawn, and how the spawn might be adjusted to\n# fit higher difficulty waves. eg: a greydwarf spawning into a swamp level wave will recieve 1 bonus star, since it is from the black forest, which is 1 biome behind the swamp."; streamWriter4.WriteLine(value4); streamWriter4.WriteLine(Monsters.YamlCreatureDefinition()); } if (!flag5) { Logger.LogInfo((object)"WildShrineConfig file missing, recreating."); using StreamWriter streamWriter5 = new StreamWriter(wildShrineConfigurationFilePath); string value5 = "###################################################################################################################################################\n# Wild Shrine Configuration\n###################################################################################################################################################\n# wildShrines:\n# - definitionForWildShrine: VF_wild_shrine_green1 |- The prefab that this set of configuration will be applied to\n# wildShrineNameLocalization: $wild_shrine_green |- The localization for the prefabs name (when hovered over) this uses a lookup value but defaults to its literal value\n# wildShrineRequestLocalization: $wild_shrine_green_request |- What the shrine says when you interact with it\n# shrineUnacceptedTributeLocalization: $wild_shrine_not_interested |- What the shrine says when you offer an incorrect tribute\n# shrineLargerTributeRequiredLocalization: $wild_shrine_hungry |- What the shrine says when you do not offer enough tribute\n# wildShrineLevelsConfig: |- Level configurations related to this shrine\n# - tributeName: TrophyBoar |- The prefab name of the tribute required to activate this level\n# tributeAmount: 4 |- Amount of the tribute required to activate this level\n# rewards: |- Rewards for this level in the format of Prefab: cost eg: RawMeat: 14.\n# LeatherScraps: 14\n# RawMeat: 12\n# hardMode: false |- If hardmode should be enabled for this level (doubles the spawn point pool and gives 50% more rewards)\n# siegeMode: false |- If siege mode should be enabled for this level (double the number of waves 4->8 and gives 50% more rewards)\n# wildshrineWaveStartLocalization: $wild_boars_attack |- Localization text to display when this wave starts\n# wildshrineWaveEndLocalization: $wild_boars_defeated |- Localization text to display when this wave is finished\n# wildLevelDefinition:\n# levelIndex: 2 |- The difficulty level for this wave, valid values are 1+ (Refer to the readme for a breakdown of this equation)\n# creatureRules: |- Optional stars and SLS modifiers, same format as creatureRules in Levels.yaml\n# - minStars: 1 |- Rules apply top to bottom; each matching rule overwrites what it sets\n# modifiers: {minor: [Fast]} |- Needs SLS; creatures given modifiers skip SLS's random ones\n# - creatures: [Greyling] |- Optional selectors: waves (1-based, -1 = last), creatures, spawnTypes\n# maxStars: 0\n# modifiers: {minor: []} |- [] clears the Fast modifier for Greylings\n# biome: Meadows |- The biome this wave is for, this impacts creature selection\n# waveFormat: Tutorial |- The wavestyle this uses (from wavestyles.yml), this governs which catagories and the percentage makeup of the wave\n# levelWarningLocalization: $meadows_warning_wilderness |- Localization for a between phase warning (often not used)\n# maxCreaturesPerPhaseOverride: 15 |- Overrides the max creatures per wave to be this value (overrides the global config)\n# onlySelectMonsters: |- Set of monsters that can be selected (From monsters.yml)\n# - Boar\n# - Greyling\n# excludeSelectMonsters: |- Set of monsters that can't be selected (from monsters.yml) best used when OnlySelected is not set.\n# commonSpawnModifiers: |- Spawn modifiers for common creatures\n# linearIncreaseRandomWaveAdjustment: true\n# rareSpawnModifiers: |- Spawn modifiers for rare creatures\n# eliteSpawnModifiers: |- Spawn modifiers for elite creatures\n"; streamWriter5.WriteLine(value5); streamWriter5.WriteLine(WildShrineData.YamlWildShrineDefinition()); } string text2 = File.ReadAllText(creatureFilePath); string text3 = File.ReadAllText(rewardFilePath); string text4 = File.ReadAllText(waveStylesFilePath); string text5 = File.ReadAllText(levelDefinitionsFilePath); string text6 = File.ReadAllText(wildShrineConfigurationFilePath); try { WaveStyles.UpdateWaveDefinition(CONST.yamldeserializer.Deserialize<WaveFormatCollection>(text4)); } catch (Exception arg) { Logger.LogWarning((object)$"There was an error updating the waveStyle values, defaults will be used. Exception: {arg}"); } try { Monsters.UpdateSpawnableCreatures(CONST.yamldeserializer.Deserialize<SpawnableCreatureCollection>(text2)); } catch (Exception arg2) { Logger.LogWarning((object)$"There was an error updating the creature values, defaults will be used. Exception: {arg2}"); } try { RewardsData.UpdateRewardsEntries(CONST.yamldeserializer.Deserialize<RewardEntryCollection>(text3)); } catch (Exception arg3) { Logger.LogWarning((object)$"There was an error updating the rewards values, defaults will be used. Exception: {arg3}"); } try { ChallengeLevels.UpdateLevelsDefinition(CONST.yamldeserializer.Deserialize<ChallengeLevelDefinitionCollection>(text5)); } catch (Exception arg4) { Logger.LogWarning((object)$"There was an error updating the levelDefinitions values, defaults will be used. Exception: {arg4}"); } try { WildShrineData.UpdateWildShrineDefinition(CONST.yamldeserializer.Deserialize<WildShrineConfigurationCollection>(text6)); } catch (Exception arg5) { Logger.LogWarning((object)$"There was an error updating the WildShrine values, defaults will be used. Exception: {arg5}"); } FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(); fileSystemWatcher.Path = secondaryConfigDirectoryPath; fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite; fileSystemWatcher.Filter = "Levels.yaml"; fileSystemWatcher.Changed += UpdateLevelsConfigFileOnChange; fileSystemWatcher.Created += UpdateLevelsConfigFileOnChange; fileSystemWatcher.Renamed += UpdateLevelsConfigFileOnChange; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; FileSystemWatcher fileSystemWatcher2 = new FileSystemWatcher(); fileSystemWatcher2.Path = secondaryConfigDirectoryPath; fileSystemWatcher2.NotifyFilter = NotifyFilters.LastWrite; fileSystemWatcher2.Filter = "WaveStyles.yaml"; fileSystemWatcher2.Changed += UpdateWavesConfigFileOnChange; fileSystemWatcher2.Created += UpdateWavesConfigFileOnChange; fileSystemWatcher2.Renamed += UpdateWavesConfigFileOnChange; fileSystemWatcher2.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher2.EnableRaisingEvents = true; FileSystemWatcher fileSystemWatcher3 = new FileSystemWatcher(); fileSystemWatcher3.Path = secondaryConfigDirectoryPath; fileSystemWatcher3.NotifyFilter = NotifyFilters.LastWrite; fileSystemWatcher3.Filter = "SpawnableCreatures.yaml"; fileSystemWatcher3.Changed += UpdateCreatureConfigFileOnChange; fileSystemWatcher3.Created += UpdateCreatureConfigFileOnChange; fileSystemWatcher3.Renamed += UpdateCreatureConfigFileOnChange; fileSystemWatcher3.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher3.EnableRaisingEvents = true; FileSystemWatcher fileSystemWatcher4 = new FileSystemWatcher(); fileSystemWatcher4.Path = secondaryConfigDirectoryPath; fileSystemWatcher4.NotifyFilter = NotifyFilters.LastWrite; fileSystemWatcher4.Filter = "Rewards.yaml"; fileSystemWatcher4.Changed += UpdateRewardsConfigFileOnChange; fileSystemWatcher4.Created += UpdateRewardsConfigFileOnChange; fileSystemWatcher4.Renamed += UpdateRewardsConfigFileOnChange; fileSystemWatcher4.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher4.EnableRaisingEvents = true; FileSystemWatcher fileSystemWatcher5 = new FileSystemWatcher(); fileSystemWatcher5.Path = secondaryConfigDirectoryPath; fileSystemWatcher5.NotifyFilter = NotifyFilters.LastWrite; fileSystemWatcher5.Filter = "WildShrines.yaml"; fileSystemWatcher5.Changed += UpdateWildShrineConfigFileOnChange; fileSystemWatcher5.Created += UpdateWildShrineConfigFileOnChange; fileSystemWatcher5.Renamed += UpdateWildShrineConfigFileOnChange; fileSystemWatcher5.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher5.EnableRaisingEvents = true; } public static IEnumerator O