Decompiled source of Eldritch v1.0.0
plugins\Eldritch.Core.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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.RegularExpressions; using Eldritch.Core; using Eldritch.Core.Abilities; using Eldritch.Core.Nav; using Eldritch.Valheim; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.Audio; using Zolantris.Shared; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } [ExecuteAlways] public class RuntimeLinkVisualizer : MonoBehaviour { public PathfindingAgentType agent = PathfindingAgentType.HumanoidBig; [Header("Sampling")] public float ringRadius = 40f; public float ringStep = 0.8f; public float angleStep = 15f; public float navSnap = 0.6f; [Header("Body")] public float bodyRadius = 0.5f; public float chestHeight = 1.2f; [Header("Mantle")] public float minLedge = 0.35f; public float maxLedge = 3f; public float mantleUp = 2f; public float stepOver = 0.35f; [Header("Ingress (hole)")] public float dropMin = 1f; public float dropMax = 6f; public float holeRimOffset = 0.35f; public float holeProbeLift = 2.5f; public float holeClearAbove = 0.3f; [Header("Layers")] public LayerMask solid; [Header("Debug Draw")] public bool drawProbes; public bool drawHits = true; public readonly List<(Vector3 from, Vector3 to, bool isMantle)> links = new List<(Vector3, Vector3, bool)>(); public int samplesTried; public int onNav; public int wallHits; public int mantlesAccepted; public int holeCandidates; public int holesAccepted; public void ScanFrom(Vector3 center) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) ScanFrom(center, ringRadius); } public void ScanFrom(Vector3 center, float radius) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009f: 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_015c: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: 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_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_02c6: Unknown result type (might be due to invalid IL or missing references) //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02cf: Unknown result type (might be due to invalid IL or missing references) //IL_02d4: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_02db: Unknown result type (might be due to invalid IL or missing references) //IL_02e2: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_0315: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Unknown result type (might be due to invalid IL or missing references) //IL_0209: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Unknown result type (might be due to invalid IL or missing references) //IL_0370: Unknown result type (might be due to invalid IL or missing references) //IL_0380: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Unknown result type (might be due to invalid IL or missing references) //IL_03ee: Unknown result type (might be due to invalid IL or missing references) //IL_03f3: Unknown result type (might be due to invalid IL or missing references) //IL_03f7: Unknown result type (might be due to invalid IL or missing references) //IL_03fc: Unknown result type (might be due to invalid IL or missing references) //IL_0400: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Unknown result type (might be due to invalid IL or missing references) //IL_0286: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_029d: Unknown result type (might be due to invalid IL or missing references) //IL_02a2: Unknown result type (might be due to invalid IL or missing references) //IL_02ac: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: Unknown result type (might be due to invalid IL or missing references) //IL_03af: Unknown result type (might be due to invalid IL or missing references) //IL_041e: Unknown result type (might be due to invalid IL or missing references) //IL_0420: Unknown result type (might be due to invalid IL or missing references) //IL_0414: Unknown result type (might be due to invalid IL or missing references) //IL_0416: Unknown result type (might be due to invalid IL or missing references) //IL_03c6: Unknown result type (might be due to invalid IL or missing references) //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_0445: Unknown result type (might be due to invalid IL or missing references) //IL_0447: Unknown result type (might be due to invalid IL or missing references) //IL_0457: Unknown result type (might be due to invalid IL or missing references) //IL_0459: Unknown result type (might be due to invalid IL or missing references) //IL_0463: Unknown result type (might be due to invalid IL or missing references) //IL_0468: Unknown result type (might be due to invalid IL or missing references) links.Clear(); samplesTried = (onNav = (wallHits = (mantlesAccepted = (holeCandidates = (holesAccepted = 0))))); if (!Pathfinding.TrySnapToNav(center, (int)agent, out var snapped)) { return; } RaycastHit val2 = default(RaycastHit); for (float num = 0f; num < 360f; num += angleStep) { Vector3 val = Quaternion.Euler(0f, num, 0f) * Vector3.forward; for (float num2 = ringStep; num2 <= radius; num2 += ringStep) { samplesTried++; Vector3 snapped2 = snapped + val * num2; if (!Pathfinding.TrySnapToNav(snapped2, (int)agent, out snapped2)) { continue; } onNav++; if (drawProbes) { Debug.DrawLine(snapped + new Vector3(ringRadius, 0f, 0f), snapped + new Vector3(0f - ringRadius, 0f, 0f), Color.gray, 0f, false); Debug.DrawLine(snapped + new Vector3(0f, 0f, ringRadius), snapped + new Vector3(0f, 0f, 0f - ringRadius), Color.gray, 0f, false); } if (Physics.SphereCast(snapped2 + Vector3.up * chestHeight, bodyRadius * 0.9f, val, ref val2, 1.2f, LayerMask.op_Implicit(solid), (QueryTriggerInteraction)1)) { wallHits++; float num3 = ((RaycastHit)(ref val2)).point.y - snapped2.y; if (num3 >= minLedge && num3 <= maxLedge) { Vector3 val3 = ((RaycastHit)(ref val2)).point + Vector3.up * mantleUp + ((RaycastHit)(ref val2)).normal * stepOver; if (RaycastDown(val3 + Vector3.up * 0.25f, out var hit) && ((RaycastHit)(ref hit)).point.y > snapped2.y + minLedge) { links.Add((snapped2, ((RaycastHit)(ref hit)).point, true)); mantlesAccepted++; if (drawHits) { Debug.DrawLine(snapped2, ((RaycastHit)(ref hit)).point, Color.yellow, 0f, false); Debug.DrawRay(((RaycastHit)(ref hit)).point, Vector3.up * 0.2f, Color.yellow, 0f, false); } break; } } } Vector3 val4 = snapped2 + val * holeRimOffset; RaycastHit[] array = Physics.RaycastAll(new Vector3(val4.x, val4.y + holeProbeLift, val4.z), Vector3.down, holeProbeLift + dropMax + 2f, LayerMask.op_Implicit(solid), (QueryTriggerInteraction)1); if (array.Length == 0) { continue; } Array.Sort(array, (RaycastHit a, RaycastHit b) => ((RaycastHit)(ref a)).distance.CompareTo(((RaycastHit)(ref b)).distance)); holeCandidates++; RaycastHit? val5 = null; for (int i = 0; i < array.Length; i++) { float num4 = snapped2.y - ((RaycastHit)(ref array[i])).point.y; if (num4 >= dropMin && num4 <= dropMax && Vector3.Angle(((RaycastHit)(ref array[i])).normal, Vector3.up) <= 45f) { val5 = array[i]; break; } } if (val5.HasValue) { RaycastHit value = val5.Value; Vector3 val6 = ((RaycastHit)(ref value)).point; if (Pathfinding.FindValidPoint(out var point, val6, 1f, (int)agent)) { val6 = point; } links.Add((snapped2, val6, false)); holesAccepted++; if (drawHits) { Debug.DrawLine(snapped2, val6, Color.magenta, 0f, false); Debug.DrawRay(val6, Vector3.up * 0.25f, Color.magenta, 0f, false); } break; } } } } private bool RaycastDown(Vector3 from, out RaycastHit hit) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) if (Physics.Raycast(from, Vector3.down, ref hit, dropMax + 4f, LayerMask.op_Implicit(solid), (QueryTriggerInteraction)1) && Vector3.Angle(((RaycastHit)(ref hit)).normal, Vector3.up) <= 45f) { return true; } return false; } private void OnDrawGizmosSelected() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) foreach (var link in links) { Gizmos.color = (link.isMantle ? Color.yellow : Color.magenta); Gizmos.DrawLine(link.from, link.to); Gizmos.DrawSphere(link.from, 0.08f); Gizmos.DrawSphere(link.to, 0.08f); } } } namespace ValheimVehicles.SharedScripts { internal static class BuildInfo { public const string Version = "1.0.0"; public const string AssemblyVersion = "1.0.0.0"; public const string FileVersion = "1.0.0.0"; public const string PackageVersion = "1.0.0"; } } namespace Eldritch.Valheim { public enum XenoHitboxType { Tail, Arm, Blood } [RequireComponent(typeof(Collider))] public sealed class XenoAttackHitbox : MonoBehaviour { [SerializeField] private XenoHitboxType type; [SerializeField] private XenoDroneAI controller; [SerializeField] private LayerMask hittableLayers; [SerializeField] private bool useAttackWindow = true; private Collider _col; private void Awake() { _col = ((Component)this).GetComponent<Collider>(); _col.isTrigger = true; if (!Object.op_Implicit((Object)(object)controller)) { controller = ((Component)this).GetComponentInParent<XenoDroneAI>(); } } private void OnTriggerEnter(Collider other) { if (((Behaviour)this).enabled && !((Object)(object)controller == (Object)null) && ((1 << ((Component)other).gameObject.layer) & ((LayerMask)(ref hittableLayers)).value) != 0 && (!useAttackWindow || controller.IsAttackWindowOpen(type))) { controller.HandleHit(type, this, other); } } } } namespace Eldritch.Core { public class AbilityManager : MonoBehaviour, IAbilityManager { public DodgeAbilityConfig dodgeAbilityConfig = new DodgeAbilityConfig { forwardDistance = 6.5f, backwardDistance = 5f, sideDistance = 5f, jumpHeight = 1f, dodgeDuration = 0.18f, cooldown = 1f }; public CamouflageAbilityConfig camouflageAbilityConfig = new CamouflageAbilityConfig { cooldown = 10f, duration = 5f }; public static Material camouflageMat_Static; public Material camouflageMat; public XenoAIMovementController movementController; public XenoAnimationController animationController; public XenoDroneAI AI; public Rigidbody _rb; public CamouflageAbility camouflageAbility { get; private set; } public DodgeAbility dodgeAbility { get; private set; } public TailAttackAbility tailAttackAbility { get; private set; } public bool IsDodging => dodgeAbility.IsDodging; public bool IsTailAttacking => tailAttackAbility.IsAttacking; private void Awake() { _rb = ((Component)this).GetComponent<Rigidbody>(); AI = ((Component)this).GetComponent<XenoDroneAI>(); movementController = ((Component)this).GetComponent<XenoAIMovementController>(); if (!Object.op_Implicit((Object)(object)animationController)) { animationController = ((Component)this).GetComponentInChildren<XenoAnimationController>(); } InitAbilities(); } private void OnEnable() { InitAbilities(); } public bool RequestLeapTowardEnemy(float minGapOverride = -0.1f) { if (tailAttackAbility.IsAttacking) { return false; } if (!dodgeAbility.CanDodge || (Object)(object)AI == (Object)null || !Object.op_Implicit((Object)(object)AI.PrimaryTarget)) { return false; } if (AI.IsAttacking()) { animationController.StopAttack(); } Transform primaryTarget = AI.PrimaryTarget; Rigidbody val = (Rigidbody)(Object.op_Implicit((Object)(object)AI.PrimaryTargetRB) ? ((object)AI.PrimaryTargetRB) : ((object)((Component)primaryTarget).GetComponentInChildren<Rigidbody>())); if (!Object.op_Implicit((Object)(object)val)) { (from x in ((Component)primaryTarget).GetComponentsInChildren<Collider>() where Object.op_Implicit((Object)(object)x) && !x.isTrigger select x).ToArray(); } if (animationController.allColliders == null || animationController.allColliders.Count <= 0) { ((Component)this).GetComponentsInChildren<Collider>()?.Where((Collider x) => Object.op_Implicit((Object)(object)x) && !x.isTrigger); } else { new List<Collider>(animationController.allColliders).Where((Collider x) => Object.op_Implicit((Object)(object)x) && !x.isTrigger).ToArray(); } if (!dodgeAbility.TryLeapAt(val, _rb)) { return false; } List<string> skipTransformNames = new List<string> { "Tail" }; animationController.PlayJump(skipTransformNames); RequestAttack(1, isSingle: true, 2f, Mathf.Max(0f, dodgeAbilityConfig.dodgeDuration - 1f)); return true; } public void RequestDodge(Vector2 dir) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) if (tailAttackAbility.IsAttacking || !dodgeAbility.CanDodge) { return; } if (AI.IsAttacking()) { animationController.StopAttack(); } if (dodgeAbility.TryDodge(dir)) { List<string> skipTransformNames = new List<string> { "Tail" }; animationController.PlayJump(skipTransformNames); if (IsForwardDodge(Vector2.op_Implicit(dir))) { RequestAttack(1, isSingle: true, 2f, Mathf.Max(0f, dodgeAbilityConfig.dodgeDuration - 1f)); } } } public void RequestAttack(int attackType = 0, bool isSingle = true, float attackSpeed = 1f, float delay = 0f) { if (attackType == 1) { if (camouflageAbility.IsActive) { camouflageAbility.Deactivate(); } tailAttackAbility.StartAttack(attackType, isSingle, attackSpeed, delay); } } [ContextMenu("Dodge (Default dir)")] public void RequestDodge() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) RequestDodge(dodgeAbilityConfig.defaultDodgeDirection); } private void InitAbilities() { if (!Object.op_Implicit((Object)(object)animationController)) { animationController = ((Component)this).GetComponentInChildren<XenoAnimationController>(); } if (!Object.op_Implicit((Object)(object)camouflageMat) && Object.op_Implicit((Object)(object)camouflageMat_Static)) { camouflageMat = camouflageMat_Static; } if (!Object.op_Implicit((Object)(object)_rb)) { _rb = ((Component)this).GetComponent<Rigidbody>(); } if (!Object.op_Implicit((Object)(object)AI)) { AI = ((Component)this).GetComponent<XenoDroneAI>(); } DodgeAbility dodgeAbility2; if (this.dodgeAbility == null) { dodgeAbility2 = (this.dodgeAbility = new DodgeAbility((MonoBehaviour)(object)this, dodgeAbilityConfig, ((Component)this).transform, _rb)); } dodgeAbility2 = this.dodgeAbility; if (dodgeAbility2.config == null) { dodgeAbility2.config = dodgeAbilityConfig; } if (this.tailAttackAbility == null) { TailAttackAbility tailAttackAbility2 = (this.tailAttackAbility = new TailAttackAbility((MonoBehaviour)(object)this, AI, animationController)); } CamouflageAbility camouflageAbility2; if (this.camouflageAbility == null) { camouflageAbility2 = (this.camouflageAbility = new CamouflageAbility((MonoBehaviour)(object)this, camouflageAbilityConfig, camouflageMat, animationController)); } camouflageAbility2 = this.camouflageAbility; if (camouflageAbility2.config == null) { camouflageAbility2.config = camouflageAbilityConfig; } } private bool IsForwardDodge(Vector3 dir) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (dir.x < dir.y) { return dir.y > 0f; } return false; } } public class AIEnemyRegistryTester : MonoBehaviour { public List<GameObject> enemiesTracker = new List<GameObject>(); private void Awake() { GetAllEnemies(); } private List<GameObject> GetChildGameObjects(Transform parent) { List<GameObject> list = new List<GameObject>(); for (int i = 0; i < parent.childCount; i++) { list.Add(((Component)parent.GetChild(i)).gameObject); } return list; } [ContextMenu("Update all enemies")] public void GetAllEnemies() { enemiesTracker = GetChildGameObjects(((Component)this).transform); EnemyRegistry.ActiveEnemies = enemiesTracker.ToHashSet(); } } public static class AnimatorStateIdUtil { public readonly struct StateId { public readonly int Short; public readonly int Full; public StateId(int shortHash, int fullHash) { Short = shortHash; Full = fullHash; } public static StateId FromShort(string shortName) { return new StateId(SafeHash(shortName), 0); } public static StateId FromFull(string fullPath) { return new StateId(0, SafeHash(fullPath)); } public static StateId FromBoth(string shortName, string fullPath) { return new StateId(SafeHash(shortName), SafeHash(fullPath)); } public static StateId From(string nameOrPath) { int num = SafeHash(nameOrPath); if (!LooksLikePath(nameOrPath)) { return new StateId(num, 0); } return new StateId(0, num); } } public static StateId[] Build(params string[] namesOrPaths) { if (namesOrPaths == null || namesOrPaths.Length == 0) { return Array.Empty<StateId>(); } List<StateId> list = new List<StateId>(namesOrPaths.Length); foreach (string text in namesOrPaths) { if (!string.IsNullOrEmpty(text)) { list.Add(StateId.From(text)); } } return list.ToArray(); } public static bool IsPlaying(Animator a, int layer, in StateId id, bool includeNext = true) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)a) || layer < 0 || layer >= a.layerCount) { return false; } AnimatorStateInfo s = a.GetCurrentAnimatorStateInfo(layer); if (Matches(in s, in id)) { return true; } if (includeNext && a.IsInTransition(layer)) { AnimatorStateInfo s2 = a.GetNextAnimatorStateInfo(layer); if (Matches(in s2, in id)) { return true; } } return false; } public static bool IsPlayingAny(Animator a, int layer, StateId[] ids, bool includeNext = true) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)a) || ids == null || ids.Length == 0 || layer < 0 || layer >= a.layerCount) { return false; } AnimatorStateInfo s = a.GetCurrentAnimatorStateInfo(layer); for (int i = 0; i < ids.Length; i++) { if (Matches(in s, in ids[i])) { return true; } } if (includeNext && a.IsInTransition(layer)) { AnimatorStateInfo s2 = a.GetNextAnimatorStateInfo(layer); for (int j = 0; j < ids.Length; j++) { if (Matches(in s2, in ids[j])) { return true; } } } return false; } public static float NormalizedTime01(in AnimatorStateInfo info) { //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) AnimatorStateInfo val = info; float normalizedTime = ((AnimatorStateInfo)(ref val)).normalizedTime; if (!float.IsFinite(normalizedTime)) { return 0f; } return normalizedTime - Mathf.Floor(normalizedTime); } private static bool Matches(in AnimatorStateInfo s, in StateId id) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) AnimatorStateInfo val; if (id.Short != 0) { val = s; if (((AnimatorStateInfo)(ref val)).shortNameHash == id.Short) { return true; } } if (id.Full != 0) { val = s; if (((AnimatorStateInfo)(ref val)).fullPathHash == id.Full) { return true; } } return false; } private static int SafeHash(string s) { if (!string.IsNullOrEmpty(s)) { return Animator.StringToHash(s); } return 0; } private static bool LooksLikePath(string s) { if (!string.IsNullOrEmpty(s)) { if (s.IndexOf('.') < 0) { return s.IndexOf('/') >= 0; } return true; } return false; } } public class CollisionDelegate : MonoBehaviour { public XenoDroneAI ownerAI; public void SetOwnerAI(XenoDroneAI ai) { ownerAI = ai; } private void OnCollisionEnter(Collision other) { if (Object.op_Implicit((Object)(object)ownerAI)) { ownerAI.OnCollisionEnter(other); } } private void OnCollisionStay(Collision other) { if (Object.op_Implicit((Object)(object)ownerAI)) { ownerAI.OnCollisionStay(other); } } } public class ComponentAITest : MonoBehaviour { public void Update() { Hello(); } public void Hello() { LoggerProvider.LogDebugDebounced("hello world", 5f, "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Core\\AI\\ComponentAITest.cs", 14); } } public static class EnemyRegistry { public static HashSet<GameObject> ActiveEnemies = new HashSet<GameObject>(); public static bool TryGetClosestEnemy(Transform self, float maxDistance, [NotNullWhen(true)] out Transform? target) { //IL_003d: 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) bool flag = false; target = null; float num = maxDistance; foreach (GameObject activeEnemy in ActiveEnemies) { if ((Object)(object)activeEnemy == (Object)null) { flag = true; } else if (!((Object)(object)activeEnemy.transform == (Object)(object)self)) { float num2 = Vector3.Distance(activeEnemy.transform.position, self.position); if (num2 < num) { target = activeEnemy.transform; num = num2; } } } if (flag) { ActiveEnemies.RemoveWhere((GameObject x) => (Object)(object)x == (Object)null); } if (num >= maxDistance || (Object)(object)target == (Object)null) { return false; } return true; } } public struct MotionSampleState { public Vector3 PrevPos; public Quaternion PrevRot; public bool HasPrev; public float FwdEma; } public static class MotionSpeedSampler { public static float SampleNormalizedMoveSpeed(Transform motionRoot, ref MotionSampleState state, float dt, out bool turningInPlace, out float yawDegPerSec, float maxForwardSpeed = 6f, float deadzoneSpeed = 0.05f, float smoothingTau = 0.08f, float teleportDist = 2f) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) turningInPlace = false; yawDegPerSec = 0f; if (!Object.op_Implicit((Object)(object)motionRoot) || dt <= 0f) { return 0f; } Vector3 position = motionRoot.position; Quaternion rotation = motionRoot.rotation; if (!state.HasPrev) { state.PrevPos = position; state.PrevRot = rotation; state.HasPrev = true; state.FwdEma = 0f; return 0f; } Vector3 val = position - state.PrevPos; if (((Vector3)(ref val)).sqrMagnitude > teleportDist * teleportDist) { state.PrevPos = position; state.PrevRot = rotation; state.FwdEma = 0f; return 0f; } Vector3 val2 = Quaternion.Inverse(state.PrevRot) * val; val2.y = 0f; float num = val2.z / dt; if (Mathf.Abs(num) < deadzoneSpeed) { num = 0f; } Quaternion val3 = rotation * Quaternion.Inverse(state.PrevRot); float num2 = default(float); Vector3 val4 = default(Vector3); ((Quaternion)(ref val3)).ToAngleAxis(ref num2, ref val4); if (num2 > 180f) { num2 -= 360f; } float num3 = Mathf.Sign(Vector3.Dot(val4, Vector3.up)); yawDegPerSec = num2 * num3 / dt; float num4 = 1f - Mathf.Exp((0f - dt) / Mathf.Max(0.0001f, smoothingTau)); state.FwdEma = Mathf.Lerp(state.FwdEma, num, num4); state.PrevPos = position; state.PrevRot = rotation; return Mathf.Clamp(state.FwdEma / Mathf.Max(0.01f, maxForwardSpeed), -1f, 1f); } } internal interface IBehaviorState { float DecisionTimer { get; set; } } public interface IBehaviorSharedState { Transform PrimaryTarget { get; set; } Transform Self { get; set; } float DeltaPrimaryTarget { get; set; } } public struct BehaviorStateSync : IBehaviorSharedState { public Transform PrimaryTarget { get; set; } public Transform Self { get; set; } public float DeltaPrimaryTarget { get; set; } } public class SleepAnimation { [CompilerGenerated] private sealed class <MoveHeadLeftRight>d__12 : IEnumerator<object>, IEnumerator, IDisposable { private int <>1__state; private object <>2__current; public SleepAnimation <>4__this; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <MoveHeadLeftRight>d__12(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown int num = <>1__state; SleepAnimation sleepAnimation = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; if (!sleepAnimation.isSetup) { return false; } break; case 1: <>1__state = -1; sleepAnimation.LateUpdate_MoveHeadAround(); break; } if (((Behaviour)sleepAnimation.monoBehaviour).isActiveAndEnabled && sleepAnimation.IsSleeping) { <>2__current = (object)new WaitForEndOfFrame(); <>1__state = 1; return true; } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } public Vector3 angleA = new Vector3(0f, -45f, 45f); public Vector3 angleB = new Vector3(0f, 45f, 60f); private bool isSetup; private bool IsSleeping; private MonoBehaviour monoBehaviour; private CoroutineHandle NeckRoutine; private Transform neckTransform; public float speed = 1f; private float t; private bool toB = true; public void Setup(MonoBehaviour monoBehaviour, Transform neckTransform) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown this.neckTransform = neckTransform; this.monoBehaviour = monoBehaviour; NeckRoutine = new CoroutineHandle(monoBehaviour); isSetup = true; } public void SetIsSleeping(bool val) { IsSleeping = val; } [IteratorStateMachine(typeof(<MoveHeadLeftRight>d__12))] private IEnumerator MoveHeadLeftRight() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <MoveHeadLeftRight>d__12(0) { <>4__this = this }; } public void StartTurningHead() { if (!NeckRoutine.IsRunning) { NeckRoutine.Start(MoveHeadLeftRight(), true); } } public void StopTurningHead() { if (NeckRoutine.IsRunning) { NeckRoutine.Stop(); IsSleeping = false; } } private void LateUpdate_MoveHeadAround() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) if (isSetup) { Quaternion localRotation = neckTransform.localRotation; float num = 1f; Quaternion identity = Quaternion.identity; neckTransform.localRotation = Quaternion.Slerp(localRotation, identity, num); t += Time.deltaTime / speed; if (t > 1f) { t = 0f; toB = !toB; } Vector3 val = (toB ? angleA : angleB); Vector3 val2 = (toB ? angleB : angleA); neckTransform.localRotation = Quaternion.Euler(Vector3.Lerp(val, val2, t)); } } } [Serializable] public class SurfaceClimbingState { private struct Portal { public Vector3 from; public Vector3 to; public PortalType type; } private enum PortalType { Mantle, Ingress } private sealed class Node { public int id; public Vector3 p; public PortalType? via; public Node(int id, Vector3 p, PortalType? via = null) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) this.id = id; this.p = p; this.via = via; } } private sealed class PlannedPath { public bool ok; public readonly List<(Vector3 a, Vector3 b, Color c, bool isWalk, List<Vector3> corners)> segs = new List<(Vector3, Vector3, Color, bool, List<Vector3>)>(); } private sealed class DuplicateKeyComparer<T> : IComparer<T> where T : IComparable<T> { public int Compare(T x, T y) { int num = x.CompareTo(y); if (num != 0) { return num; } return 1; } } [Header("Debug")] [SerializeField] private bool drawDebug = true; [SerializeField] private float replanCooldown = 0.5f; [Header("Body")] [SerializeField] private float bodyRadius = 0.35f; [SerializeField] private float bodyHeight = 1.8f; [Header("Mantle")] [SerializeField] private float minLedge = 0.35f; [SerializeField] private float maxLedge = 3f; [SerializeField] private float stepOver = 0.3f; [SerializeField] private float minAscent = 0.25f; [Header("Ingress (floor opening)")] [SerializeField] private float ingressSearchRadius = 10f; [SerializeField] private float ingressMinDrop = 1f; [SerializeField] private float ingressMaxDrop = 6f; [SerializeField] private int ingressSamples = 14; [Header("Queries")] [SerializeField] private LayerMask solidMask = LayerMask.op_Implicit(0); [SerializeField] private float sameFloorEps = 0.9f; private Transform _tr; private float _nextPlanAt; private PlannedPath _cached; private readonly List<Portal> _tmpPortals = new List<Portal>(12); private readonly Dictionary<(int, int), List<Vector3>> _walkCorners = new Dictionary<(int, int), List<Vector3>>(); private readonly List<Vector3> _cornersPool = new List<Vector3>(32); private static readonly Color WalkCol = new Color(0.2f, 1f, 1f); private static readonly Color MantleCol = new Color(1f, 1f, 0.2f); private static readonly Color IngressCol = new Color(1f, 0f, 1f); public void Init(MonoBehaviour _, Rigidbody __, Transform root) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) _tr = root; if (((LayerMask)(ref solidMask)).value == 0) { solidMask = LayerHelpers.GroundLayers; } RecalcBodyFromColliders(); } public void DebugPlanTo(Vector3 target) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) if (drawDebug) { if (Time.time >= _nextPlanAt) { _cached = Plan(_tr.position, target); _nextPlanAt = Time.time + replanCooldown; } Draw(_cached); } } private PlannedPath Plan(Vector3 from, Vector3 to) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Unknown result type (might be due to invalid IL or missing references) //IL_02c4: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_03e1: Unknown result type (might be due to invalid IL or missing references) //IL_03e6: Unknown result type (might be due to invalid IL or missing references) //IL_03fb: Unknown result type (might be due to invalid IL or missing references) //IL_0400: Unknown result type (might be due to invalid IL or missing references) //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_042d: Unknown result type (might be due to invalid IL or missing references) //IL_0448: Unknown result type (might be due to invalid IL or missing references) //IL_0450: Unknown result type (might be due to invalid IL or missing references) //IL_0452: Unknown result type (might be due to invalid IL or missing references) //IL_0454: Unknown result type (might be due to invalid IL or missing references) PlannedPath plannedPath = new PlannedPath(); List<Node> list = new List<Node>(12); Dictionary<(int, int), (float, bool, PortalType?)> dictionary = new Dictionary<(int, int), (float, bool, PortalType?)>(); Node node = new Node(0, GroundSnap(from)); Node node2 = new Node(1, GroundSnap(to)); list.Add(node); list.Add(node2); if (SameFloor(node.p, node2.p) && TryGetNavCorners(node.p, node2.p, out List<Vector3> corners)) { AddWalkSeg(plannedPath, corners); plannedPath.ok = true; return plannedPath; } List<Portal> tmpPortals = _tmpPortals; tmpPortals.Clear(); FindMantlePortalsAround(node.p, node2.p, tmpPortals, 6); FindIngressPortals(node.p, node2.p, tmpPortals, 6); for (int i = 0; i < tmpPortals.Count; i++) { int num = 2 + i * 2; list.Add(new Node(num, tmpPortals[i].from)); list.Add(new Node(num + 1, tmpPortals[i].to, tmpPortals[i].type)); } for (int j = 0; j < list.Count; j++) { for (int k = j + 1; k < list.Count; k++) { if (SameFloor(list[j].p, list[k].p) && TryGetNavCorners(list[j].p, list[k].p, out List<Vector3> corners2)) { float item = CornersLength(corners2); dictionary[(list[j].id, list[k].id)] = (item, true, null); dictionary[(list[k].id, list[j].id)] = (item, true, null); _walkCorners[(list[j].id, list[k].id)] = corners2; _walkCorners[(list[k].id, list[j].id)] = _revTmp(corners2); } } } for (int l = 0; l < tmpPortals.Count; l++) { int num2 = 2 + l * 2; int num3 = num2 + 1; float num4 = Vector3.Distance(list[num2].p, list[num3].p); float num5 = ((tmpPortals[l].type == PortalType.Mantle) ? 2.5f : 1.5f); dictionary[(num2, num3)] = (num4 + num5, false, tmpPortals[l].type); } if (!AStar(list, dictionary, node.id, node2.id, out List<int> route)) { plannedPath.ok = false; return plannedPath; } for (int m = 0; m < route.Count - 1; m++) { int a = route[m]; int b = route[m + 1]; (int, int) key = (a, b); (float, bool, PortalType?) tuple = dictionary[key]; bool item2 = tuple.Item2; PortalType? item3 = tuple.Item3; if (item2) { List<Vector3> corners3 = _walkCorners[key]; AddWalkSeg(plannedPath, corners3); continue; } Vector3 p = list.Find((Node n) => n.id == a).p; Vector3 p2 = list.Find((Node n) => n.id == b).p; Color item4 = ((item3 == PortalType.Mantle) ? new Color(1f, 1f, 0.2f) : new Color(1f, 0f, 1f)); plannedPath.segs.Add((p, p2, item4, false, null)); } plannedPath.ok = true; return plannedPath; } private bool SameFloor(Vector3 a, Vector3 b) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) return Mathf.Abs(a.y - b.y) <= sameFloorEps; } private Vector3 GroundSnap(Vector3 p) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) RaycastHit val = default(RaycastHit); if (Physics.Raycast(p + Vector3.up * 2f, Vector3.down, ref val, 6f, LayerMask.op_Implicit(solidMask), (QueryTriggerInteraction)1)) { return ((RaycastHit)(ref val)).point; } return p; } private void FindMantlePortalsAround(Vector3 from, Vector3 to, List<Portal> outList, int maxCount) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) Vector3 val = to - from; val.y = 0f; if (((Vector3)(ref val)).sqrMagnitude < 0.01f) { val = (Object.op_Implicit((Object)(object)_tr) ? _tr.forward : Vector3.forward); } ((Vector3)(ref val)).Normalize(); float[] array = new float[5] { -35f, -15f, 0f, 15f, 35f }; float num = 0.9f; float num2 = 5f; RaycastHit val4 = default(RaycastHit); RaycastHit val5 = default(RaycastHit); for (int i = 0; i < array.Length; i++) { if (outList.Count >= maxCount) { break; } Vector3 val2 = Quaternion.Euler(0f, array[i], 0f) * val; for (float num3 = num; num3 <= num2; num3 += num) { if (outList.Count >= maxCount) { break; } Vector3 val3 = from + val2 * num3 + Vector3.up * Mathf.Max(1f, bodyRadius * 3f); if (Physics.SphereCast(val3, bodyRadius * 0.9f, val2, ref val4, 0.4f, LayerMask.op_Implicit(solidMask))) { Vector3 normal = ((RaycastHit)(ref val4)).normal; float y = from.y; float num4 = ((RaycastHit)(ref val4)).point.y - y; if (!(num4 < minLedge) && !(num4 > maxLedge) && Physics.Raycast(((RaycastHit)(ref val4)).point + Vector3.up * Mathf.Min(maxLedge, num4 + 0.8f) + normal * stepOver + Vector3.up * 0.25f, Vector3.down, ref val5, 4f, LayerMask.op_Implicit(solidMask)) && !(((RaycastHit)(ref val5)).point.y < y + minAscent)) { outList.Add(new Portal { from = GroundSnap(val3 - val2 * 0.35f), to = ((RaycastHit)(ref val5)).point, type = PortalType.Mantle }); } break; } } } } private void FindIngressPortals(Vector3 from, Vector3 target, List<Portal> outList, int maxCount) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) List<(Portal, float)> list = new List<(Portal, float)>(maxCount); RaycastHit val2 = default(RaycastHit); RaycastHit val3 = default(RaycastHit); for (int i = 0; i < ingressSamples; i++) { float num = 360f * ((float)i / (float)ingressSamples); Vector3 val = Quaternion.Euler(0f, num, 0f) * Vector3.forward; for (float num2 = 1f; num2 <= ingressSearchRadius; num2 += 1f) { if (!Physics.Raycast(from + val * num2 + Vector3.up * 1.5f, Vector3.down, ref val2, 4f, LayerMask.op_Implicit(solidMask)) || !Physics.Raycast(((RaycastHit)(ref val2)).point + Vector3.up * 0.2f, Vector3.down, ref val3, ingressMaxDrop + 0.6f, LayerMask.op_Implicit(solidMask))) { continue; } float num3 = ((RaycastHit)(ref val2)).point.y - ((RaycastHit)(ref val3)).point.y; if (num3 < ingressMinDrop || num3 > ingressMaxDrop || Vector3.Angle(((RaycastHit)(ref val3)).normal, Vector3.up) > 45f) { continue; } float num4 = Mathf.Abs(from.y - target.y); float num5 = Mathf.Abs(((RaycastHit)(ref val3)).point.y - target.y); float num6 = num4 - num5; float num7 = Vector2.Distance(new Vector2(((RaycastHit)(ref val2)).point.x, ((RaycastHit)(ref val2)).point.z), new Vector2(target.x, target.z)); float num8 = Vector3.Distance(from, ((RaycastHit)(ref val2)).point); float num9 = num6 * 2f - num7 * 0.12f - num8 * 0.05f; Portal portal = default(Portal); portal.from = ((RaycastHit)(ref val2)).point; portal.to = ((RaycastHit)(ref val3)).point; portal.type = PortalType.Ingress; Portal item = portal; if (list.Count < maxCount) { list.Add((item, num9)); continue; } int index = 0; float item2 = list[0].Item2; for (int j = 1; j < list.Count; j++) { if (list[j].Item2 < item2) { item2 = list[j].Item2; index = j; } } if (num9 > item2) { list[index] = (item, num9); } } } foreach (var item3 in list) { outList.Add(item3.Item1); } } private bool TryGetNavCorners(Vector3 a, Vector3 b, out List<Vector3> corners) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) corners = _cornersPool; corners.Clear(); if (!Pathfinding.GetPath(a, b, corners, 1)) { return false; } if (corners.Count < 2) { return false; } return true; } private static float CornersLength(List<Vector3> cs) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) float num = 0f; for (int i = 1; i < cs.Count; i++) { num += Vector3.Distance(cs[i - 1], cs[i]); } return num; } private static List<Vector3> _revTmp(List<Vector3> src) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) List<Vector3> list = new List<Vector3>(src.Count); for (int num = src.Count - 1; num >= 0; num--) { list.Add(src[num]); } return list; } private void RecalcBodyFromColliders() { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) float num = float.PositiveInfinity; float num2 = float.NegativeInfinity; float num3 = 0.3f; bool flag = false; Collider[] componentsInChildren = ((Component)_tr).GetComponentsInChildren<Collider>(); foreach (Collider val in componentsInChildren) { if (val.enabled) { float num4 = num; Bounds bounds = val.bounds; num = Mathf.Min(num4, ((Bounds)(ref bounds)).min.y); float num5 = num2; bounds = val.bounds; num2 = Mathf.Max(num5, ((Bounds)(ref bounds)).max.y); bounds = val.bounds; Vector3 extents = ((Bounds)(ref bounds)).extents; num3 = (flag ? Mathf.Max(num3, Mathf.Min(extents.x, extents.z) * 0.65f) : (Mathf.Min(extents.x, extents.z) * 0.65f)); flag = true; } } if (flag) { bodyHeight = Mathf.Clamp(num2 - num, 1f, 3.2f); bodyRadius = Mathf.Clamp(num3, 0.2f, 0.7f); } } private static bool AStar(List<Node> nodes, Dictionary<(int, int), (float, bool, PortalType?)> edges, int start, int goal, out List<int> route) { route = null; SortedList<float, int> sortedList = new SortedList<float, int>(new DuplicateKeyComparer<float>()); Dictionary<int, float> dictionary = new Dictionary<int, float>(); Dictionary<int, float> dictionary2 = new Dictionary<int, float>(); Dictionary<int, int> dictionary3 = new Dictionary<int, int>(); foreach (Node node in nodes) { dictionary[node.id] = float.PositiveInfinity; dictionary2[node.id] = float.PositiveInfinity; } dictionary[start] = 0f; dictionary2[start] = Heur(nodes, start, goal); sortedList.Add(dictionary2[start], start); while (sortedList.Count > 0) { int num = sortedList.Values[0]; sortedList.RemoveAt(0); if (num == goal) { List<int> list = new List<int>(); int num2 = goal; list.Add(num2); int value; while (dictionary3.TryGetValue(num2, out value)) { num2 = value; list.Add(num2); } list.Reverse(); route = list; return true; } foreach (KeyValuePair<(int, int), (float, bool, PortalType?)> edge in edges) { if (edge.Key.Item1 == num) { int item = edge.Key.Item2; float item2 = edge.Value.Item1; float num3 = dictionary[num] + item2; if (num3 < dictionary[item]) { dictionary[item] = num3; dictionary2[item] = num3 + Heur(nodes, item, goal); dictionary3[item] = num; sortedList.Add(dictionary2[item], item); } } } } return false; } private static float Heur(List<Node> nodes, int a, int b) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) Vector3 p = nodes.Find((Node n) => n.id == a).p; Vector3 p2 = nodes.Find((Node n) => n.id == b).p; float num = Vector2.Distance(new Vector2(p.x, p.z), new Vector2(p2.x, p2.z)); float num2 = Mathf.Abs(p.y - p2.y) * 0.6f; return num + num2; } private void AddWalkSeg(PlannedPath path, List<Vector3> corners) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) for (int i = 1; i < corners.Count; i++) { path.segs.Add((corners[i - 1], corners[i], WalkCol, true, null)); } } private void Draw(PlannedPath plan) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) if (plan == null) { return; } foreach (var seg in plan.segs) { Debug.DrawLine(seg.a + Vector3.up * 0.05f, seg.b + Vector3.up * 0.05f, seg.c, 0f, false); if (!seg.isWalk) { Debug.DrawRay(seg.b, Vector3.up * 0.2f, seg.c, 0f, false); } } } } public class ValheimZoneSystemStub { public static ValheimZoneSystemStub instance = new ValheimZoneSystemStub(); public bool GetGroundHeight(Vector3 p, out float height) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) height = -9999f; RaycastHit val = default(RaycastHit); if (!Physics.Raycast(p + Vector3.up * 500f, Vector3.down, ref val, 5000f, LayerMask.GetMask(new string[1] { "terrain" }))) { return false; } height = ((RaycastHit)(ref val)).point.y; return true; } } public class XenoAIMovementController : MonoBehaviour { private enum OrbitState { Orbit, Detour } [Header("References")] [SerializeField] private Rigidbody _rb; [SerializeField] private Rigidbody _animationRb; public Collider HeadCollider; public Transform HeadColliderTransform; public XenoDroneAI OwnerAI; [Header("Movement Tuning")] public float distanceMoveSpeed = 1f; public float closeMoveSpeed = 5f; public float distantAccelForce = 90f; public float closeAccelForce = 90f; public float closeRange = 2f; public float distantTurnSpeed = 500f; public float closeTurnSpeed = 500f; public float wanderSpeed = 15f; public float maxJumpDistance = 4f; public float maxJumpHeightArc = 2.5f; public Vector3 maxRunRange = new Vector3(20f, 0f, 20f); public float wanderRadius = 60f; public float wanderCooldown = 5f; public float wanderMinDistance = 3f; public Vector3 currentWanderTarget; public Vector3 GroundPoint = Vector3.zero; [SerializeField] public float CounterGravity = 0.1f; public AbilityManager abilityManager; public float arrivalThreshold = 5f; public readonly HashSet<Collider> GroundContacts = new HashSet<Collider>(); private XenoAnimationController animationController; private float dodgeElapsed; private Vector3 dodgeStart; private Vector3 dodgeEnd; private bool hasArrivedAtWanderPoint; private float lastDodgeTime = float.NegativeInfinity; private float nextWanderTime; public bool HasMovedInFrame; [SerializeField] private SurfaceClimbingState climbingState = new SurfaceClimbingState(); public RuntimeLinkVisualizer portalScanner; public float rescanInterval = 2f; private float _nextScanTime; private float _smoothedAnimSpeed; [SerializeField] private float animatedMovementLerpSpeed = 12f; private readonly List<Vector3> _orbitTmpPath = new List<Vector3>(); [SerializeField] private float orbitAheadDegrees = 45f; [SerializeField] private float orbitProbeLen = 2f; [SerializeField] private float orbitClearance = 0.35f; [SerializeField] private float orbitRejoinAheadDeg = 35f; [SerializeField] private float orbitRejoinLoS = 6f; [SerializeField] private float orbitRadiusSlack = 0.6f; [SerializeField] private float detourMaxSeconds = 2f; private OrbitState _orbitState; private Vector3 _detourLastNormal; private float _detourTimer; public Rigidbody Rb => _rb; public float moveLerpVel { get; private set; } public bool HasRoamTarget => currentWanderTarget != Vector3.zero; public bool IsGrounded => GroundContacts.Count > 0; public void Awake() { if (!Object.op_Implicit((Object)(object)portalScanner)) { portalScanner = ((Component)this).gameObject.AddComponent<RuntimeLinkVisualizer>(); } if (!Object.op_Implicit((Object)(object)animationController)) { animationController = ((Component)this).GetComponentInChildren<XenoAnimationController>(); } if (!Object.op_Implicit((Object)(object)abilityManager)) { abilityManager = ((Component)this).GetComponent<AbilityManager>(); } climbingState.Init((MonoBehaviour)(object)this, _rb, ((Component)this).transform); } public void Start() { if (!Object.op_Implicit((Object)(object)_rb)) { _rb = ((Component)((Component)this).transform).GetComponent<Rigidbody>(); if (!Object.op_Implicit((Object)(object)_rb)) { _rb = ((Component)this).GetComponent<Rigidbody>(); } } if (!Object.op_Implicit((Object)(object)_animationRb)) { _animationRb = ((Component)((Component)this).transform.Find("Visual")).GetComponent<Rigidbody>(); } if (Object.op_Implicit((Object)(object)_rb)) { _rb.interpolation = (RigidbodyInterpolation)1; _rb.collisionDetectionMode = (CollisionDetectionMode)1; _rb.constraints = (RigidbodyConstraints)80; } } public void FixedUpdate() { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)OwnerAI) && Object.op_Implicit((Object)(object)Rb)) { if (Object.op_Implicit((Object)(object)animationController)) { _ = (Object)(object)((Component)_rb).transform != (Object)(object)((Component)this).transform; } _ = _rb.linearVelocity; if (OwnerAI.IsManualControlling) { _rb.useGravity = !IsGrounded; } if (!Rb.isKinematic) { float y = ((Component)this).transform.eulerAngles.y; Rb.MoveRotation(Quaternion.Euler(0f, y, 0f)); } UpdateGroundPoint(); } } public void OnTriggerEnter(Collider other) { if (((Component)other).gameObject.layer == LayerHelpers.TerrainLayer) { GroundContacts.Add(other); } } public void OnTriggerExit(Collider other) { if (((Component)other).gameObject.layer == LayerHelpers.TerrainLayer) { GroundContacts.Remove(other); } } private float GetMoveSpeedParam(float localForwardSpeed) { if (localForwardSpeed < -0.1f) { return Mathf.Lerp(localForwardSpeed, -1f, Time.fixedDeltaTime); } if (Mathf.Abs(localForwardSpeed) < 0.1f) { return Mathf.Lerp(localForwardSpeed, 0f, Time.fixedDeltaTime); } return Mathf.Clamp(localForwardSpeed, -1f, 2f); } public void SyncVelocityWithMovementSpeed(Vector3 velocity) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) if (!Rb.isKinematic) { Vector3 val = new Vector3(velocity.x, 0f, velocity.z); Vector3 forward = ((Component)this).transform.forward; forward.y = 0f; ((Vector3)(ref forward)).Normalize(); float num = Vector3.Dot(val, forward); if (Mathf.Abs(num) < 0.15f) { num = 0f; } _smoothedAnimSpeed = Mathf.Lerp(_smoothedAnimSpeed, num, animatedMovementLerpSpeed * Time.fixedDeltaTime); float moveSpeedParam = GetMoveSpeedParam(_smoothedAnimSpeed); animationController.SetMoveSpeed(moveSpeedParam); HasMovedInFrame = false; } } public void UpdateGroundPoint() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)OwnerAI)) { RaycastHit val = default(RaycastHit); if (Physics.Raycast(OwnerAI.xenoRoot.position, -OwnerAI.xenoRoot.up, ref val, 40f, LayerMask.op_Implicit(LayerHelpers.GroundLayers))) { GroundPoint = ((RaycastHit)(ref val)).point; } else { GroundPoint = Vector3.negativeInfinity; } } } public void MoveTowardsTarget(Vector3 targetPos, float speed, float accel, float? turnSpeed) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) float valueOrDefault = turnSpeed.GetValueOrDefault(); if (!turnSpeed.HasValue) { valueOrDefault = GetTurnSpeed(); turnSpeed = valueOrDefault; } Vector3 dir = targetPos - ((Component)this).transform.position; RotateTowardsDirection(dir, turnSpeed.Value); moveLerpVel = Mathf.MoveTowards(moveLerpVel, speed, accel * Time.fixedDeltaTime); Rb.AddForce(((Component)this).transform.forward * moveLerpVel, (ForceMode)5); HasMovedInFrame = true; } public void MoveInDirection(Vector3 direction, float speed, float lerpRate, float turnSpeed) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) direction.y = 0f; if (!(direction == Vector3.zero)) { RotateTowardsDirection(direction, turnSpeed); float num = Vector3.Dot(Rb.linearVelocity, ((Component)this).transform.forward); float num2 = Mathf.MoveTowards(num, speed, lerpRate * Time.fixedDeltaTime); Rb.AddForce(((Component)this).transform.forward * (num2 - num), (ForceMode)2); HasMovedInFrame = true; } } public void MoveAwayFromTarget(Vector3 awayFrom, float speed, float accel, float? turnRate) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) float valueOrDefault = turnRate.GetValueOrDefault(); if (!turnRate.HasValue) { valueOrDefault = distantTurnSpeed; turnRate = valueOrDefault; } Vector3 moveDir = ((Component)this).transform.position - awayFrom; moveDir.y = 0f; if (!(((Vector3)(ref moveDir)).sqrMagnitude < 0.0001f)) { MoveAlongDirectionWhileFacing(moveDir, awayFrom, speed, accel, turnRate.Value); } } public float GetTurnSpeed() { if (!(OwnerAI.DeltaPrimaryTarget > closeRange)) { return closeTurnSpeed; } return distantTurnSpeed; } public float GetMoveSpeed() { if (!(OwnerAI.DeltaPrimaryTarget > closeRange)) { return closeMoveSpeed; } return distanceMoveSpeed; } public float GetAccelForce() { if (!(OwnerAI.DeltaPrimaryTarget > closeRange)) { return closeAccelForce; } return distantAccelForce; } public void MoveChaseTarget(Vector3 targetPos, Vector3? targetVelocity, float turnRate) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) Vector3 val = targetPos + (Vector3)(((??)targetVelocity) ?? Vector3.zero) * 0.5f - ((Component)this).transform.position; float magnitude = ((Vector3)(ref val)).magnitude; float num = 6f; float num2 = Mathf.Clamp01(magnitude / num); float num3 = Mathf.Lerp(closeMoveSpeed, distanceMoveSpeed, num2); float num4 = Mathf.Lerp(closeAccelForce, distantAccelForce, num2); Vector3 val2 = default(Vector3); ((Vector3)(ref val2))..ctor(Rb.linearVelocity.x, 0f, Rb.linearVelocity.z); if (num3 <= closeMoveSpeed * 1.15f) { Vector3 dir = ((((Vector3)(ref val2)).sqrMagnitude > 0.01f) ? val2 : val); RotateTowardsDirection(dir, turnRate); Vector3 forward = ((Component)this).transform.forward; Vector3 val3 = ((Vector3)(ref forward)).normalized * num3 - val2; val3 = Vector3.ClampMagnitude(val3, num4 * Time.fixedDeltaTime); Rb.AddForce(val3, (ForceMode)2); HasMovedInFrame = true; } else { RotateTowardsDirection(val, turnRate); if (!(Mathf.Abs(Vector3.SignedAngle(((Component)this).transform.forward, val, Vector3.up)) < 120f)) { moveLerpVel = Mathf.MoveTowards(moveLerpVel, 0f, num4 * 2f * Time.fixedDeltaTime); return; } moveLerpVel = Mathf.MoveTowards(moveLerpVel, num3, num4 * Time.fixedDeltaTime); Rb.AddForce(((Component)this).transform.forward * moveLerpVel, (ForceMode)5); HasMovedInFrame = true; } } public void MoveAwayFromEnemies(HashSet<GameObject> enemySet, float maxRange) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) List<Vector3> list = new List<Vector3>(); foreach (GameObject item in enemySet) { if (!((Object)(object)item == (Object)null) && !((Object)(object)item == (Object)(object)((Component)this).gameObject) && !(Vector3.Distance(((Component)this).transform.position, item.transform.position) > maxRange)) { list.Add(item.transform.position); } } if (list.Count == 0) { return; } float num = float.MinValue; Vector3 val = Vector3.zero; int num2 = 12; for (int i = 0; i < num2; i++) { float num3 = 360f / (float)num2 * (float)i; Vector3 val2 = Quaternion.Euler(0f, num3, 0f) * Vector3.forward; Vector3 val3 = ((Component)this).transform.position + val2 * 5f; if (!IsGroundBelow(val3, 1.5f)) { continue; } float num4 = 0f; foreach (Vector3 item2 in list) { num4 += Vector3.Distance(val3, item2); } Vector3 val4 = val3 - ((Component)this).transform.position; if (Mathf.Abs(val4.x) > maxRunRange.x || Mathf.Abs(val4.z) > maxRunRange.z) { num4 -= 10000f; } if (num4 > num) { num = num4; val = val2; } } if (!(val == Vector3.zero)) { MoveTowardsTarget(((Component)this).transform.position + val * 4f, distanceMoveSpeed, distantAccelForce, distantTurnSpeed); } } public void MoveFleeWithAllyBias(XenoDroneAI friendly, HashSet<GameObject> enemies) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) List<Vector3> list = new List<Vector3>(); foreach (GameObject enemy in enemies) { if (!((Object)(object)enemy == (Object)null) && !((Object)(object)enemy == (Object)(object)((Component)this).gameObject)) { list.Add(enemy.transform.position); } } Vector3 val = Vector3.zero; float num = float.MinValue; int num2 = 12; for (int i = 0; i < num2; i++) { float num3 = 360f / (float)num2 * (float)i; Vector3 val2 = Quaternion.Euler(0f, num3, 0f) * Vector3.forward; float num4 = 0f; if ((Object)(object)friendly != (Object)null) { Vector3 val3 = ((Component)friendly).transform.position - ((Component)this).transform.position; Vector3 normalized = ((Vector3)(ref val3)).normalized; num4 = Vector3.Dot(val2, normalized) * 8f; } Vector3 val4 = ((Component)this).transform.position + val2 * 5f; float num5 = 0f; foreach (Vector3 item in list) { float num6 = Vector3.Distance(val4, item); num5 -= 1f / Mathf.Max(num6, 0.1f); } if (IsGroundBelow(val4, 1.5f)) { float num7 = num4 + num5; if (num7 > num) { num = num7; val = val2; } } } if (val == Vector3.zero) { MoveAwayFromEnemies(enemies, 40f); } else { MoveTowardsTarget(((Component)this).transform.position + val * 4f, distanceMoveSpeed * 1.25f, distantAccelForce * 1.1f, distantTurnSpeed); } } private float GetXZDistance(Vector3 a, Vector3 b) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) return Vector2.Distance(new Vector2(a.x, a.z), new Vector2(b.x, b.z)); } public void MoveWander() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) if (Time.time < nextWanderTime) { return; } float num = (HasRoamTarget ? GetXZDistance(((Component)this).transform.position, currentWanderTarget) : float.PositiveInfinity); if (!HasRoamTarget || num < arrivalThreshold || hasArrivedAtWanderPoint) { if (!hasArrivedAtWanderPoint) { BrakeHard(); moveLerpVel = 0f; hasArrivedAtWanderPoint = true; } if (Time.time >= nextWanderTime) { if (TryPickRandomWanderTarget(out currentWanderTarget)) { nextWanderTime = Time.time + wanderCooldown; hasArrivedAtWanderPoint = false; } else { nextWanderTime = Time.time + 2f; } } return; } Vector3 dir = currentWanderTarget - ((Component)this).transform.position; if (!(num > arrivalThreshold)) { return; } RotateTowardsDirection(dir, distantTurnSpeed); if (num > 2f && IsGapAhead(1f, 3f, 5f)) { if (FindJumpableLanding(out var landingPoint)) { JumpTo(landingPoint); } else { BrakeHard(); } return; } float num2 = 5f; float num3 = Mathf.Clamp01(num / num2); float num4 = Mathf.Lerp(0f, wanderSpeed, num3); float num5 = Mathf.Lerp(0f, distantAccelForce * 0.5f, num3); moveLerpVel = Mathf.MoveTowards(moveLerpVel, num4, num5 * Time.fixedDeltaTime); Rb.AddForce(((Component)this).transform.forward * moveLerpVel, (ForceMode)5); HasMovedInFrame = true; } public void BrakeHard() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) Vector3 linearVelocity = Rb.linearVelocity; linearVelocity.x = 0f; linearVelocity.z = 0f; Rb.linearVelocity = linearVelocity; Rb.angularVelocity = Vector3.zero; HasMovedInFrame = false; } public bool IsGapAhead(float distance = 1f, float maxStepHeight = 2f, float maxDrop = 3f) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)OwnerAI == (Object)null || !OwnerAI.CanJump || !OwnerAI.IsGrounded()) { return false; } Vector3 val = ((Component)this).transform.position + ((Component)this).transform.forward * distance; RaycastHit val2 = default(RaycastHit); if (Physics.Raycast(val + Vector3.up, Vector3.down, ref val2, maxDrop + 1.2f, LayerMask.GetMask(new string[2] { "Default", "terrain" })) && val.y - ((RaycastHit)(ref val2)).point.y < maxStepHeight) { return false; } return true; } public bool IsGroundBelow(Vector3 position, float maxDrop) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) RaycastHit val = default(RaycastHit); return Physics.Raycast(new Ray(position + Vector3.up * 0.5f, Vector3.down), ref val, maxDrop + 0.5f, LayerMask.GetMask(new string[2] { "Default", "terrain" })); } private bool FindJumpableLanding(out Vector3 landingPoint, float maxDrop = 2.5f, float fanAngle = 60f, int numChecks = 7) { //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_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references)
plugins\Eldritch.Valheim.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.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using Eldritch.Core; using Eldritch.Core.Nav; using HarmonyLib; using Jotunn; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Managers; using Microsoft.CodeAnalysis; using ServerSync; using UnityEngine; using UnityEngine.U2D; using Zolantris.Shared; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ValheimVehicles.SharedScripts { internal static class BuildInfo { public const string Version = "1.0.0"; public const string AssemblyVersion = "1.0.0.0"; public const string FileVersion = "1.0.0.0"; public const string PackageVersion = "1.0.0"; } } namespace Eldritch.Valheim { public struct EditableSpawnConfig { public Biome Biome; public float SpawnChance; public int MinGroupSize; public int MaxGroupSize; public float SpawnInterval; public bool SpawnAtDay; public bool SpawnAtNight; public float MaxAltitude; public float MinAltitude; public bool HuntPlayer; public int MaxLevel; public EditableSpawnConfig() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) Biome = (Biome)2; SpawnChance = 100f; MinGroupSize = 1; MaxGroupSize = 3; SpawnInterval = 200f; SpawnAtDay = true; SpawnAtNight = true; MaxAltitude = 1000f; MinAltitude = 0f; HuntPlayer = true; MaxLevel = 10; } public SpawnConfig ToSpawnConfig() { //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_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Expected O, but got Unknown return new SpawnConfig { Name = "Xenomorph Drone", Biome = Biome, SpawnChance = SpawnChance, MinGroupSize = MinGroupSize, MaxGroupSize = MaxGroupSize, SpawnInterval = SpawnInterval, SpawnAtDay = SpawnAtDay, SpawnAtNight = SpawnAtNight, MaxAltitude = MaxAltitude, MinAltitude = MinAltitude, HuntPlayer = HuntPlayer, MaxLevel = MaxLevel }; } } public class EldritchBepinExXenoDroneConfig : BepInExBaseConfig<EldritchBepinExXenoDroneConfig> { public static ConfigEntry<bool> Enabled; public static string prefabNameKey = "Xeno Drone"; public static string sectionKey_spawnConfig = "xenoDrone - SpawnConfig"; public static string sectionKey_characterConfig = "xenoDrone - CharacterConfig"; public static ConfigEntry<float> XenoHealth; public static ConfigEntry<float> attackDamageTailAcid; public static ConfigEntry<float> attackDamageTailPierce; public static ConfigEntry<float> attackDamageTailSlash; public static ConfigEntry<float> attackDamageArmsAcid; public static ConfigEntry<float> attackDamageArmsPierce; public static ConfigEntry<float> attackDamageArmsSlash; public static ConfigEntry<float> attackDamageBloodAcid; public static ConfigEntry<float> XenoHealthMultiplier; public static ConfigEntry<bool> IsTameable; public static ConfigEntry<float> Speed; public static ConfigEntry<float> XenoSwimSpeed; public static ConfigEntry<float> RunSpeed; public static ConfigEntry<string> XenoSpawnConfig; public static ConfigEntry<Biome> BiomeSpawn; public static ConfigEntry<Biome> BiomesAlwaysSpawn; public static ConfigEntry<GlobalKeys> GlobalKeysConditionalSpawn; public static ConfigEntry<float> SpawnChance; public static ConfigEntry<int> MinGroupSize; public static ConfigEntry<int> MaxGroupSize; public static ConfigEntry<float> SpawnInterval; public static ConfigEntry<bool> SpawnAtDay; public static ConfigEntry<bool> SpawnAtNight; public static ConfigEntry<float> MaxAltitude; public static ConfigEntry<float> MinAltitude; public static ConfigEntry<bool> HuntPlayer; public static ConfigEntry<int> MaxLevel; public static void BindCharacterConfig(string prefabName, ConfigFile config) { XenoHealth = BepInExConfigUtils.BindUnique<float>(config, sectionKey_characterConfig, "maxHealth", 200f, ConfigHelpers.CreateConfigDescription("Configuration for Xeno Drone max base health", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 101); Speed = BepInExConfigUtils.BindUnique<float>(config, sectionKey_characterConfig, "Speed", 15f, ConfigHelpers.CreateConfigDescription("Base speed.", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 102); XenoSwimSpeed = BepInExConfigUtils.BindUnique<float>(config, sectionKey_characterConfig, "XenoSwimSpeed", 5f, ConfigHelpers.CreateConfigDescription("Swim speed.", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 103); RunSpeed = BepInExConfigUtils.BindUnique<float>(config, sectionKey_characterConfig, "RunSpeed", 20f, ConfigHelpers.CreateConfigDescription("Run speed (might not apply for creatures)", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 104); XenoHealthMultiplier = BepInExConfigUtils.BindUnique<float>(config, sectionKey_characterConfig, "healthMultiplier", 1f, ConfigHelpers.CreateConfigDescription("Health multiplier for the Xeno Drone per level", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 105); IsTameable = BepInExConfigUtils.BindUnique<bool>(config, sectionKey_characterConfig, "IsTameable", false, ConfigHelpers.CreateConfigDescription("Xenos can be tamed if true. They like meats RawMeat, NeckTail, LoxMeat, SerpentMeat.", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 106); attackDamageTailAcid = BepInExConfigUtils.BindUnique<float>(config, sectionKey_characterConfig, "attackDamageTailAcid", 12f, ConfigHelpers.CreateConfigDescription("Tail acid attack damage", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 108); attackDamageTailPierce = BepInExConfigUtils.BindUnique<float>(config, sectionKey_characterConfig, "attackDamageTailPierce", 18f, ConfigHelpers.CreateConfigDescription("Tail pierce attack damage", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 109); attackDamageTailSlash = BepInExConfigUtils.BindUnique<float>(config, sectionKey_characterConfig, "attackDamageTailSlash", 18f, ConfigHelpers.CreateConfigDescription("Tail slash attack damage", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 110); attackDamageArmsAcid = BepInExConfigUtils.BindUnique<float>(config, sectionKey_characterConfig, "attackDamageArmsAcid", 8f, ConfigHelpers.CreateConfigDescription("Arms acid attack damage", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 112); attackDamageArmsPierce = BepInExConfigUtils.BindUnique<float>(config, sectionKey_characterConfig, "attackDamageArmsPierce", 10f, ConfigHelpers.CreateConfigDescription("Arms pierce attack damage", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 113); attackDamageArmsSlash = BepInExConfigUtils.BindUnique<float>(config, sectionKey_characterConfig, "attackDamageArmsSlash", 10f, ConfigHelpers.CreateConfigDescription("Arms slash attack damage", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 114); attackDamageBloodAcid = BepInExConfigUtils.BindUnique<float>(config, sectionKey_characterConfig, "attackDamageBloodAcid", 6f, ConfigHelpers.CreateConfigDescription("Acid damage applied to blood/dot effects", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 119); } public static void BindSpawnConfig(string prefabName, ConfigFile config) { //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) Enabled = BepInExConfigUtils.BindUnique<bool>(config, sectionKey_spawnConfig, "Enabled", true, ConfigHelpers.CreateConfigDescription("Enable the " + prefabName + " for spawn", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 124); XenoSpawnConfig = BepInExConfigUtils.BindJson<EditableSpawnConfig>(config, sectionKey_spawnConfig, "xenoSpawnConfig", new EditableSpawnConfig(), "Configuration for Xeno spawning"); BiomeSpawn = BepInExConfigUtils.BindUnique<Biome>(config, sectionKey_spawnConfig, "BiomeSpawn", EldritchPrefabRegistry.DefaultBiomesAfterGlobalKey, ConfigHelpers.CreateConfigDescription("Enable Xenos for specific Biomes, multiple biomes can be used. This will allow spawning in all Biomes. However Xenos spawns will only occur if GlobalKey conditions are met (or none are set)", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 128); BiomesAlwaysSpawn = BepInExConfigUtils.BindUnique<Biome>(config, sectionKey_spawnConfig, "BiomesAlwaysSpawn", EldritchPrefabRegistry.DefaultAlwaysSpawnInBiomes, ConfigHelpers.CreateConfigDescription("Enable " + prefabName + " for specific Biomes without World Modifier requirements, multiple biomes can be used. This will allow spawning in these Biomes regardless of World Modifier conditions.", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 130); GlobalKeysConditionalSpawn = BepInExConfigUtils.BindUnique<GlobalKeys>(config, sectionKey_spawnConfig, "GlobalKeysConditionalSpawn", (GlobalKeys)35, ConfigHelpers.CreateConfigDescription("Conditionally enable spawning based on all global modifiers being active. This means all of them must be fulfilled. For more info on keys go here. https://valheimcheats.com/global-key", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 132); SpawnChance = BepInExConfigUtils.BindUnique<float>(config, sectionKey_spawnConfig, "SpawnChance", 5f, ConfigHelpers.CreateConfigDescription("Chance to spawn each spawn interval (0-100)", true, false, (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 134); MinGroupSize = BepInExConfigUtils.BindUnique<int>(config, sectionKey_spawnConfig, "MinGroupSize", 1, ConfigHelpers.CreateConfigDescription("Min Group Size Spawned", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 136); MaxGroupSize = BepInExConfigUtils.BindUnique<int>(config, sectionKey_spawnConfig, "MaxGroupSize", 3, ConfigHelpers.CreateConfigDescription("Max Group Size Spawned", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 138); SpawnInterval = BepInExConfigUtils.BindUnique<float>(config, sectionKey_spawnConfig, "SpawnInterval", 600f, ConfigHelpers.CreateConfigDescription("Spawning interval of the prefab", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 140); SpawnAtDay = BepInExConfigUtils.BindUnique<bool>(config, sectionKey_spawnConfig, "SpawnAtDay", true, ConfigHelpers.CreateConfigDescription("Enable spawning during the day.", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 142); SpawnAtNight = BepInExConfigUtils.BindUnique<bool>(config, sectionKey_spawnConfig, "SpawnAtNight", true, ConfigHelpers.CreateConfigDescription("Enable spawning at night.", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 144); MaxAltitude = BepInExConfigUtils.BindUnique<float>(config, sectionKey_spawnConfig, "MaxAltitude", 1000f, ConfigHelpers.CreateConfigDescription("Allow spawning below this altitude.", true, false, (AcceptableValueBase)(object)new AcceptableValueRange<float>(20f, 10000f), (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 146); MinAltitude = BepInExConfigUtils.BindUnique<float>(config, sectionKey_spawnConfig, "MinAltitude", 0f, ConfigHelpers.CreateConfigDescription("Allow spawning above this altitude", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 148); HuntPlayer = BepInExConfigUtils.BindUnique<bool>(config, sectionKey_spawnConfig, "HuntPlayer", true, ConfigHelpers.CreateConfigDescription("Allow hunting players", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 150); MaxLevel = BepInExConfigUtils.BindUnique<int>(config, sectionKey_spawnConfig, "MaxLevel", 10, ConfigHelpers.CreateConfigDescription("Sets the max level of spawns", true, false, (AcceptableValueBase)null, (string)null, (int?)null, (bool?)null, (bool?)null, (string)null), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchBepinExXenoDroneConfig.cs", 152); } public override void OnBindConfig(ConfigFile config) { BindSpawnConfig(prefabNameKey, config); BindCharacterConfig(prefabNameKey, config); } } public static class EldritchPrefabRegistry { public static AssetBundle assetBundle; public static SpriteAtlas Sprites; public const string droneAssetName = "xenomorph-drone-v1"; public const string droneConfigName = "Xenomorph Drone"; private const string XenoAdultName = "Eldritch_XenoAdult_Creature"; public static Biome DefaultAlwaysSpawnInBiomes = (Biome)608; public static Biome DefaultBiomesAfterGlobalKey = (Biome)10; public static SpawnConfig xenoGlobalModifierSpawnConfig = new SpawnConfig { Name = "Xenomorph Drone", Biome = DefaultBiomesAfterGlobalKey, SpawnChance = 5f, MinGroupSize = 1, MaxGroupSize = 3, RequiredGlobalKey = "defeated_goblinking", SpawnInterval = 600f, SpawnAtDay = true, SpawnAtNight = true, MaxAltitude = 1000f, MinAltitude = 0f, HuntPlayer = true, MaxLevel = 10 }; public static SpawnConfig xenoNoModifierSpawnConfig = new SpawnConfig { Name = "Xenomorph Drone", Biome = DefaultAlwaysSpawnInBiomes, SpawnChance = 5f, MinGroupSize = 1, MaxGroupSize = 5, SpawnInterval = 600f, SpawnAtDay = true, SpawnAtNight = true, MaxAltitude = 10000f, MinAltitude = 0f, HuntPlayer = true, MaxLevel = 10 }; public static DamageTypes XenoDroneArmDamage = new DamageTypes { m_slash = 30f, m_pierce = 10f }; public static DamageTypes XenoDroneBloodDamage = new DamageTypes { m_poison = 50f }; public static DamageTypes XenoDroneTailDamage = new DamageTypes { m_slash = 25f, m_pierce = 50f }; public static void UpdateSpawnConfig() { //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_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Expected O, but got Unknown //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Expected O, but got Unknown xenoGlobalModifierSpawnConfig = new SpawnConfig { Name = "Xenomorph Drone", Biome = EldritchBepinExXenoDroneConfig.BiomeSpawn.Value, SpawnChance = EldritchBepinExXenoDroneConfig.SpawnChance.Value, MinGroupSize = EldritchBepinExXenoDroneConfig.MinGroupSize.Value, MaxGroupSize = EldritchBepinExXenoDroneConfig.MaxGroupSize.Value, SpawnInterval = EldritchBepinExXenoDroneConfig.SpawnInterval.Value, SpawnAtDay = EldritchBepinExXenoDroneConfig.SpawnAtDay.Value, SpawnAtNight = EldritchBepinExXenoDroneConfig.SpawnAtNight.Value, MaxAltitude = EldritchBepinExXenoDroneConfig.MaxAltitude.Value, MinAltitude = EldritchBepinExXenoDroneConfig.MinAltitude.Value, HuntPlayer = EldritchBepinExXenoDroneConfig.HuntPlayer.Value, MaxLevel = EldritchBepinExXenoDroneConfig.MaxLevel.Value }; xenoNoModifierSpawnConfig = new SpawnConfig { Name = "Xenomorph Drone", Biome = EldritchBepinExXenoDroneConfig.BiomesAlwaysSpawn.Value, SpawnChance = EldritchBepinExXenoDroneConfig.SpawnChance.Value, MinGroupSize = EldritchBepinExXenoDroneConfig.MinGroupSize.Value, MaxGroupSize = EldritchBepinExXenoDroneConfig.MaxGroupSize.Value, SpawnInterval = EldritchBepinExXenoDroneConfig.SpawnInterval.Value, SpawnAtDay = EldritchBepinExXenoDroneConfig.SpawnAtDay.Value, SpawnAtNight = EldritchBepinExXenoDroneConfig.SpawnAtNight.Value, MaxAltitude = EldritchBepinExXenoDroneConfig.MaxAltitude.Value, MinAltitude = EldritchBepinExXenoDroneConfig.MinAltitude.Value, HuntPlayer = EldritchBepinExXenoDroneConfig.HuntPlayer.Value, MaxLevel = EldritchBepinExXenoDroneConfig.MaxLevel.Value }; } public static void LoadAssemblies() { if (!Object.op_Implicit((Object)(object)assetBundle)) { assetBundle = Entry.LoadAssembly(); } if (!((Object)(object)assetBundle == (Object)null)) { Sprites = assetBundle.LoadAsset<SpriteAtlas>("icons"); } } public static void RegisterPlaceableAlien() { //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Expected O, but got Unknown //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Expected O, but got Unknown //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Expected O, but got Unknown if ((Object)(object)assetBundle == (Object)null) { return; } LoggerProvider.LogDebug("Starting InjectAlienPrefab", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchPrefabRegistry.cs", 111); GameObject val = assetBundle.LoadAsset<GameObject>("xenomorph-drone-v1"); if ((Object)(object)val == (Object)null) { return; } Component[] components = val.GetComponents<Component>(); GameObject val2 = PrefabManager.Instance.CreateClonedPrefab("Eldritch_XenoAdult_Piece", val); if (!Object.op_Implicit((Object)(object)val2)) { return; } val2.AddComponent<ZNetView>(); val2.AddComponent<XenoDroneSpawnHandler>(); Piece obj = val2.AddComponent<Piece>(); obj.m_name = "Eldritch_XenoAdult_Piece"; obj.m_icon = Sprites.GetSprite("anchor"); Component[] components2 = val2.GetComponents<Component>(); foreach (Component val3 in components2) { if ((Object)(object)val3 == (Object)null) { LoggerProvider.LogError("Got null component", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchPrefabRegistry.cs", 133); } else { LoggerProvider.LogDebug(((object)val3).GetType().ToString(), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchPrefabRegistry.cs", 136); } } components2 = components; foreach (Component val4 in components2) { if ((Object)(object)val4 == (Object)null) { LoggerProvider.LogError("Got null component", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchPrefabRegistry.cs", 143); } else { LoggerProvider.LogDebug(((object)val4).GetType().ToString(), "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchPrefabRegistry.cs", 146); } } PieceManager instance = PieceManager.Instance; PieceConfig val5 = new PieceConfig(); val5.PieceTable = "Hammer"; val5.Name = "XENO"; val5.Description = "Xenos....they're everywhere..."; val5.Icon = Sprites.GetSprite("anchor"); val5.Category = "Eldritch"; val5.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Amount = 1, Item = "Wood", Recover = true } }; instance.AddPiece(new CustomPiece(val2, true, val5)); } public static void OnConfigUpdateSpawnSettings() { UpdateSpawnConfig(); PrefabManager.Instance.GetPrefab("Xenomorph Drone"); } public static void RegisterXenoSpawn() { //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_026b: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_0286: Unknown result type (might be due to invalid IL or missing references) //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_0296: Expected O, but got Unknown //IL_0296: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_02c1: Expected O, but got Unknown //IL_02c1: Unknown result type (might be due to invalid IL or missing references) //IL_02c6: Unknown result type (might be due to invalid IL or missing references) //IL_02d1: Unknown result type (might be due to invalid IL or missing references) //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_02e3: Unknown result type (might be due to invalid IL or missing references) //IL_02ec: Expected O, but got Unknown //IL_02ec: Unknown result type (might be due to invalid IL or missing references) //IL_02f1: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_0307: Unknown result type (might be due to invalid IL or missing references) //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Expected O, but got Unknown //IL_0352: Unknown result type (might be due to invalid IL or missing references) //IL_0359: Expected O, but got Unknown //IL_03ad: Unknown result type (might be due to invalid IL or missing references) //IL_03b4: Expected O, but got Unknown UpdateSpawnConfig(); GameObject val = assetBundle.LoadAsset<GameObject>("xenomorph-drone-v1"); if (!Object.op_Implicit((Object)(object)val)) { LoggerProvider.LogError("Xeno prefab not found — spawn registration skipped.", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\EldritchPrefabRegistry.cs", 183); return; } CustomCreature creature = CreatureManager.Instance.GetCreature("Seeker"); GameObject val2 = ((creature != null) ? creature.Prefab : null); if (creature == null) { val2 = CreatureManager.Instance.GetCreaturePrefab("Seeker"); } if ((Object)(object)val2 == (Object)null) { return; } GameObject val3 = PrefabManager.Instance.CreateClonedPrefab("Eldritch_XenoAdult_Creature", val); if (!((Object)(object)val3 == (Object)null)) { Humanoid component = val2.GetComponent<Humanoid>(); ZNetView orAddComponent = ExposedGameObjectExtension.GetOrAddComponent<ZNetView>(val3); orAddComponent.m_type = (ObjectType)0; orAddComponent.m_persistent = false; Humanoid orAddComponent2 = ExposedGameObjectExtension.GetOrAddComponent<Humanoid>(val3); ((Character)orAddComponent2).m_deathEffects = ((Character)component).m_deathEffects; ((Character)orAddComponent2).m_onDeath = ((Character)component).m_onDeath; orAddComponent2.m_dropEffects = component.m_dropEffects; ((Character)orAddComponent2).m_waterEffects = ((Character)component).m_waterEffects; ((Character)orAddComponent2).m_critHitEffects = ((Character)component).m_critHitEffects; ExposedGameObjectExtension.GetOrAddComponent<ZSyncTransform>(val3); ZSyncAnimation orAddComponent3 = ExposedGameObjectExtension.GetOrAddComponent<ZSyncAnimation>(val3); XenoDrone_MonsterAI orAddComponent4 = ExposedGameObjectExtension.GetOrAddComponent<XenoDrone_MonsterAI>(val3); Animator componentInChildren = val3.GetComponentInChildren<Animator>(); CharacterAnimEvent orAddComponent5 = ExposedGameObjectExtension.GetOrAddComponent<CharacterAnimEvent>(((Component)componentInChildren).gameObject); XenoAnimationController componentInChildren2 = val3.GetComponentInChildren<XenoAnimationController>(); if (EldritchBepinExXenoDroneConfig.IsTameable.Value) { Tameable orAddComponent6 = ExposedGameObjectExtension.GetOrAddComponent<Tameable>(val3); orAddComponent6.m_commandable = true; orAddComponent6.m_monsterAI = (MonsterAI)(object)orAddComponent4; ((Character)orAddComponent2).m_tameableMonsterAI = (MonsterAI)(object)orAddComponent4; } ((Character)orAddComponent2).m_health = EldritchBepinExXenoDroneConfig.XenoHealth.Value; ((Character)orAddComponent2).m_runSpeed = EldritchBepinExXenoDroneConfig.RunSpeed.Value; ((Character)orAddComponent2).m_swimSpeed = EldritchBepinExXenoDroneConfig.XenoSwimSpeed.Value; ((Character)orAddComponent2).m_eye = val3.transform.Find("EyePos"); ((Character)orAddComponent2).m_animEvent = orAddComponent5; orAddComponent5.m_animator = componentInChildren; orAddComponent5.m_nview = orAddComponent; orAddComponent5.m_head = componentInChildren2.neckPivot; orAddComponent5.m_eyes = (Transform[])(object)new Transform[2] { componentInChildren2.neckPivot, componentInChildren2.neckPivot }; orAddComponent5.m_feets = ((IEnumerable<Collider>)componentInChildren2.footColliders).Select((Func<Collider, Foot>)((Collider x) => new Foot(((Component)x).transform, (AvatarIKGoal)((!((Object)((Component)x).transform.parent).name.Contains("_l_")) ? 1 : 0)))).ToArray(); ((Character)orAddComponent2).m_animator = componentInChildren; orAddComponent3.m_animator = componentInChildren; ((BaseAI)orAddComponent4).m_huntPlayer = true; ((MonsterAI)orAddComponent4).m_enableHuntPlayer = true; SpawnConfig[] spawnConfigs = (SpawnConfig[])((!EldritchBepinExXenoDroneConfig.Enabled.Value) ? ((Array)Array.Empty<SpawnConfig>()) : ((Array)new SpawnConfig[2] { xenoGlobalModifierSpawnConfig, xenoNoModifierSpawnConfig })); DropConfig val4 = new DropConfig { Item = "Tar", Chance = 10f, MinAmount = 1, MaxAmount = 3 }; DropConfig val5 = new DropConfig { Item = "BoneFragments", Chance = 100f, MinAmount = 2, MaxAmount = 4 }; DropConfig val6 = new DropConfig { Item = "Chitin", Chance = 70f, MinAmount = 2, MaxAmount = 3 }; DropConfig val7 = new DropConfig { Item = "Eitr", Chance = 10f, MinAmount = 1, MaxAmount = 1 }; string[] consumables = ((!EldritchBepinExXenoDroneConfig.IsTameable.Value) ? Array.Empty<string>() : new string[4] { "RawMeat", "NeckTail", "LoxMeat", "SerpentMeat" }); CreatureConfig val8 = new CreatureConfig(); val8.Name = "Xenomorph Drone"; val8.Consumables = consumables; val8.DropConfigs = (DropConfig[])(object)new DropConfig[4] { val4, val5, val6, val7 }; val8.SpawnConfigs = spawnConfigs; val8.Faction = (Faction)6; CreatureConfig val9 = val8; CustomCreature val10 = new CustomCreature(val3, true, val9); CreatureManager.Instance.AddCreature(val10); } } public static void UpdateDamage() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0049: 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_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) DamageTypes xenoDroneArmDamage = default(DamageTypes); xenoDroneArmDamage.m_slash = EldritchBepinExXenoDroneConfig.attackDamageArmsSlash.Value; xenoDroneArmDamage.m_pierce = EldritchBepinExXenoDroneConfig.attackDamageArmsPierce.Value; XenoDroneArmDamage = xenoDroneArmDamage; xenoDroneArmDamage = default(DamageTypes); xenoDroneArmDamage.m_poison = EldritchBepinExXenoDroneConfig.attackDamageBloodAcid.Value; XenoDroneBloodDamage = xenoDroneArmDamage; xenoDroneArmDamage = default(DamageTypes); xenoDroneArmDamage.m_pierce = EldritchBepinExXenoDroneConfig.attackDamageTailPierce.Value; xenoDroneArmDamage.m_slash = EldritchBepinExXenoDroneConfig.attackDamageTailSlash.Value; XenoDroneTailDamage = xenoDroneArmDamage; } public static void AddWeaponItemsToXenoInventory(Humanoid humanoid) { //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_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown //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: Expected O, but got Unknown //IL_0067: Expected O, but got Unknown //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Expected O, but got Unknown //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Expected O, but got Unknown //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Expected O, but got Unknown //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Expected O, but got Unknown //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Expected O, but got Unknown //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) Attack attack = new Attack { m_attackAnimation = null, m_speedFactor = 1f, m_attackStamina = 20f, m_attackRange = 2f }; GameObject val = new GameObject("XenoArmsPlaceholderDropPrefab"); ExposedGameObjectExtension.GetOrAddComponent<ZNetView>(val).m_persistent = false; GameObject val2 = new GameObject("XenoTailDropPrefab"); ExposedGameObjectExtension.GetOrAddComponent<ZNetView>(val2).m_persistent = false; ItemDrop orAddComponent = ExposedGameObjectExtension.GetOrAddComponent<ItemDrop>(val); ItemDrop orAddComponent2 = ExposedGameObjectExtension.GetOrAddComponent<ItemDrop>(val2); Attack attack2 = new Attack { m_attackAnimation = null, m_attackStamina = 20f, m_attackRange = 2f }; ItemData val3 = new ItemData(); val3.m_dropPrefab = ((Component)orAddComponent).gameObject; ItemData obj = val3; SharedData val4 = new SharedData(); val4.m_name = "xeno_arms_weapon"; val4.m_attack = attack; val4.m_itemType = (ItemType)14; val4.m_maxStackSize = 1; val4.m_icons = (Sprite[])(object)new Sprite[1] { Sprites.GetSprite("anchor") }; val4.m_skillType = (SkillType)1; val4.m_damages = XenoDroneArmDamage; val4.m_equipDuration = 0f; val4.m_attackForce = 10f; val4.m_useDurability = false; val4.m_aiTargetType = (AiTarget)0; val4.m_aiAttackMaxAngle = 25f; obj.m_shared = val4; ItemData val5 = val3; val3 = new ItemData(); val3.m_dropPrefab = ((Component)orAddComponent2).gameObject; ItemData obj2 = val3; val4 = new SharedData(); val4.m_name = "xeno_tail_weapon"; val4.m_icons = (Sprite[])(object)new Sprite[1] { Sprites.GetSprite("anchor") }; val4.m_attack = attack2; val4.m_maxStackSize = 1; val4.m_itemType = (ItemType)14; val4.m_equipDuration = 0f; val4.m_skillType = (SkillType)1; val4.m_damages = XenoDroneTailDamage; val4.m_attackForce = 10f; val4.m_useDurability = false; val4.m_aiTargetType = (AiTarget)0; val4.m_aiAttackMaxAngle = 25f; obj2.m_shared = val4; ItemData val6 = val3; humanoid.m_inventory.AddItem(val5); humanoid.m_inventory.AddItem(val6); } public static void RegisterAllPrefabs() { UpdateDamage(); } public static void RegisterAllCreatures() { LoadAssemblies(); RegisterXenoSpawn(); } } [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("zolantris.EldritchValheim", "EldritchValheim", "1.0.0")] public class EldritchValheimPlugin : BaseUnityPlugin { public const string Author = "zolantris"; public const string Version = "1.0.0"; public const string ModName = "EldritchValheim"; public const string ModGuid = "zolantris.EldritchValheim"; public static AssetBundle assetBundle = null; public static SpriteAtlas Sprites = null; public static ConfigSync ModConfigSync = new ConfigSync("EldritchValheim") { DisplayName = "EldritchValheim", CurrentVersion = "1.0.0", ModRequired = true, IsLocked = true }; public static string HarmonyGuid => "zolantris.EldritchValheim"; public void Awake() { LoggerProvider.Setup(((BaseUnityPlugin)this).Logger); PatchController.Apply(HarmonyGuid); BepInExBaseConfig<EldritchBepinExXenoDroneConfig>.BindConfig(((BaseUnityPlugin)this).Config, ModConfigSync); Pathfinding.Register((IPathfindingShim)(object)new ValheimPathfindingShim()); CreatureManager.OnVanillaCreaturesAvailable += delegate { EldritchPrefabRegistry.RegisterAllCreatures(); }; PrefabManager.OnVanillaPrefabsAvailable += delegate { EldritchPrefabRegistry.RegisterAllPrefabs(); }; } } public static class PatchController { private static Harmony? _harmonyInstance; public static void Apply(string harmonyGuid) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown _harmonyInstance = new Harmony(harmonyGuid); HarmonyHelper.TryPatchAll(_harmonyInstance, new Type[2] { typeof(Patch_Humanoid), typeof(Patch_Character) }); } public static void UnpatchSelf() { Harmony? harmonyInstance = _harmonyInstance; if (harmonyInstance != null) { harmonyInstance.UnpatchSelf(); } } } public class Patch_Character { private static bool IsXeno(Character ch) { if (Object.op_Implicit((Object)(object)((Component)ch).GetComponent<XenoAnimationController>())) { return true; } string name = ((Object)ch).name; if (!name.Contains("Eldritch_Xeno", StringComparison.OrdinalIgnoreCase)) { return name.Contains("xenomorph-drone-v1", StringComparison.OrdinalIgnoreCase); } return true; } [HarmonyPatch(typeof(Character), "Awake")] [HarmonyPostfix] internal static void Patch_Character_SetLevel_NoScaleForXeno_Awake(Character __instance) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)__instance) && IsXeno(__instance)) { ((Component)__instance).transform.localScale = Vector3.one; } } [HarmonyPatch(typeof(Character), "SetLevel")] [HarmonyPostfix] internal static void Patch_Character_SetLevel_NoScaleForXeno(Character __instance) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)__instance) && IsXeno(__instance)) { ((Component)__instance).transform.localScale = Vector3.one; } } } [HarmonyPatch] public class Patch_Humanoid { private static readonly int XenoHash1 = StringExtensionMethods.GetStableHashCode("Eldritch_XenoAdult_Creature"); private static readonly int XenoHash2 = StringExtensionMethods.GetStableHashCode("Eldritch_XenoAdult"); private static readonly HashSet<int> XenoPrefabHashes = new HashSet<int> { XenoHash1, XenoHash2 }; private static bool IsXeno(Humanoid h) { ZNetView component = ((Component)h).GetComponent<ZNetView>(); ZDO val = (Object.op_Implicit((Object)(object)component) ? component.GetZDO() : null); if (val != null) { return XenoPrefabHashes.Contains(val.m_prefab); } string text = ((Object)((Component)h).gameObject).name; if (text.EndsWith("(Clone)")) { string text2 = text; text = text2.Substring(0, text2.Length - 7); } if (!(text == "Eldritch_XenoAdult_Creature")) { return text == "Eldritch_XenoAdult"; } return true; } [HarmonyPatch(typeof(Humanoid), "StartAttack")] [HarmonyPrefix] private static bool Humanoid_StartAttack(Humanoid __instance, ref bool __result) { if (!IsXeno(__instance)) { return true; } XenoDroneAI component = ((Component)__instance).GetComponent<XenoDroneAI>(); MonsterAI component2 = ((Component)__instance).GetComponent<MonsterAI>(); if ((Object)(object)component == (Object)null || (Object)(object)component2 == (Object)null) { return true; } Character targetCreature = ((BaseAI)component2).GetTargetCreature(); if ((Object)(object)targetCreature == (Object)null) { return true; } component.PrimaryTarget = ((Component)targetCreature).transform; component.StartAttackBehavior(); __result = true; return false; } } public sealed class ValheimPathfindingShim : IPathfindingShim { private Pathfinding Instance => Pathfinding.instance; public bool GetPath(Vector3 from, Vector3 to, List<Vector3> path, int agentType, bool requireFullPath = false, bool cleanup = true, bool havePath = false) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) Pathfinding instance = Instance; if ((Object)(object)instance == (Object)null) { return false; } AgentType val = (AgentType)agentType; return instance.GetPath(from, to, path, val, requireFullPath, cleanup, havePath); } public bool TrySnapToNav(Vector3 center, int agentType, out Vector3 snapped) { //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_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0034: 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) snapped = Vector3.zero; Pathfinding instance = Instance; if ((Object)(object)instance == (Object)null) { return false; } Vector3 val = center; AgentType val2 = (AgentType)agentType; AgentSettings settings = instance.GetSettings(val2); bool result = instance.SnapToNavMesh(ref val, true, settings); snapped = val; return result; } public bool FindValidPoint(out Vector3 point, Vector3 center, float range, int agentType) { //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_0020: Unknown result type (might be due to invalid IL or missing references) point = Vector3.zero; if ((Object)(object)Pathfinding.instance == (Object)null) { return false; } return Pathfinding.instance.FindValidPoint(ref point, center, range, (AgentType)agentType); } public bool HavePath(Vector3 from, Vector3 to, int agentType) { //IL_0005: 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) return Pathfinding.instance.HavePath(from, to, (AgentType)agentType); } } public class XenoDroneSpawnHandler : MonoBehaviour { public XenoDroneAI droneAi; public bool HasRandomizedPackId; public static bool shouldAssignPrimaryTargetToPlayer = true; private void Awake() { droneAi = ((Component)this).GetComponent<XenoDroneAI>(); UpdatePackId(); ((MonoBehaviour)this).InvokeRepeating("UpdateXeno", 0f, 5f); } public void UpdatePackId() { if (!HasRandomizedPackId && Object.op_Implicit((Object)(object)droneAi)) { int num = Random.Range(1, 5); droneAi.PackId = Mathf.RoundToInt((float)num); HasRandomizedPackId = true; } } public void UpdatePlayerTarget() { if (shouldAssignPrimaryTargetToPlayer && !((Object)(object)Player.m_localPlayer == (Object)null)) { droneAi.SetPrimaryTarget(((Component)Player.m_localPlayer).transform); } } public void UpdateXeno() { if (Object.op_Implicit((Object)(object)droneAi)) { UpdatePlayerTarget(); UpdatePackId(); } } } public class XenoDrone_MonsterAI : MonsterAI { public XenoDroneAI DroneAI; public XenoAIMovementController MovementController; public static bool ShouldSkipAiMovement = false; public static bool ShouldSkipUpdateAI = false; public static bool ShouldUseNavigationOnAttack = false; public static bool ShouldUseNavigationOnHunt = false; public static bool ShouldUseNavigationOnHuntChargeAttack = false; public static float pushForce = 3f; public Character xenoCharacter; public override void Awake() { DroneAI = ((Component)this).GetComponent<XenoDroneAI>(); MovementController = ((Component)this).GetComponent<XenoAIMovementController>(); ((MonsterAI)this).Awake(); } public void SetupXeno() { //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) xenoCharacter = ((Component)this).GetComponent<Character>(); XenoDroneAI droneAI = DroneAI; droneAI.OnHitTarget = (Action<(XenoHitboxType, XenoAttackHitbox, Collider, GameObject)>)Delegate.Combine(droneAI.OnHitTarget, new Action<(XenoHitboxType, XenoAttackHitbox, Collider, GameObject)>(HandleHitTarget)); XenoDroneAI droneAI2 = DroneAI; droneAI2.OnHitBlood = (Action<GameObject>)Delegate.Combine(droneAI2.OnHitBlood, new Action<GameObject>(HandleBloodHitTarget)); if (!Object.op_Implicit((Object)(object)xenoCharacter)) { LoggerProvider.LogError("No character component found on XenoDrone_MonsterAI", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\XenoDrone_MonsterAI.cs", 42); return; } Character obj = xenoCharacter; obj.m_onDamaged = (Action<float, Character>)Delegate.Combine(obj.m_onDamaged, new Action<float, Character>(XenoDroneOnDamaged)); DroneAI.MaxHealth = xenoCharacter.GetMaxHealth(); DroneAI.Health = xenoCharacter.GetHealth(); xenoCharacter.m_health = EldritchBepinExXenoDroneConfig.XenoHealth.Value; xenoCharacter.m_runSpeed = EldritchBepinExXenoDroneConfig.RunSpeed.Value; xenoCharacter.m_swimSpeed = EldritchBepinExXenoDroneConfig.XenoSwimSpeed.Value; xenoCharacter.m_damageModifiers = new DamageModifiers { m_poison = (DamageModifier)4, m_frost = (DamageModifier)3, m_blunt = (DamageModifier)5, m_pickaxe = (DamageModifier)5, m_spirit = (DamageModifier)1, m_chop = (DamageModifier)1, m_slash = (DamageModifier)1, m_pierce = (DamageModifier)0, m_lightning = (DamageModifier)0, m_fire = (DamageModifier)8 }; } public void XenoDroneOnDamaged(float damage, Character character) { float health = xenoCharacter.GetHealth(); DroneAI.ApplyDamage(health); } public override void OnEnable() { ((BaseAI)this).OnEnable(); SetupXeno(); } public override void OnDisable() { ((BaseAI)this).OnDisable(); Character obj = xenoCharacter; obj.m_onDamaged = (Action<float, Character>)Delegate.Remove(obj.m_onDamaged, new Action<float, Character>(XenoDroneOnDamaged)); if ((Object)(object)DroneAI != (Object)null && DroneAI.OnHitTarget != null) { XenoDroneAI droneAI = DroneAI; droneAI.OnHitTarget = (Action<(XenoHitboxType, XenoAttackHitbox, Collider, GameObject)>)Delegate.Remove(droneAI.OnHitTarget, new Action<(XenoHitboxType, XenoAttackHitbox, Collider, GameObject)>(HandleHitTarget)); } if ((Object)(object)DroneAI != (Object)null && DroneAI.OnHitBlood != null) { XenoDroneAI droneAI2 = DroneAI; droneAI2.OnHitBlood = (Action<GameObject>)Delegate.Remove(droneAI2.OnHitBlood, new Action<GameObject>(HandleBloodHitTarget)); } } public void HandleBloodHitTarget(GameObject targetRoot) { Character componentInParent = targetRoot.GetComponentInParent<Character>(); if ((Object)(object)componentInParent != (Object)null) { ApplyCharacterDamage(componentInParent, (Collider)(object)componentInParent.GetCollider(), (XenoHitboxType)2); return; } IDestructible componentInParent2 = targetRoot.GetComponentInParent<IDestructible>(); if (componentInParent2 != null) { ApplyDestructibleDamage(targetRoot, componentInParent2, (XenoHitboxType)2); } } public void HandleHitTarget((XenoHitboxType type, XenoAttackHitbox hitbox, Collider other, GameObject targetRoot) args) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) (XenoHitboxType type, XenoAttackHitbox hitbox, Collider other, GameObject targetRoot) tuple = args; XenoHitboxType item = tuple.type; Collider item2 = tuple.other; GameObject item3 = tuple.targetRoot; Character componentInParent = item3.GetComponentInParent<Character>(); if ((Object)(object)componentInParent != (Object)null) { ApplyCharacterDamage(componentInParent, item2, item); return; } IDestructible componentInParent2 = item3.GetComponentInParent<IDestructible>(); if (componentInParent2 != null) { ApplyDestructibleDamage(item3, componentInParent2, item, item2); } } private void ApplyCharacterDamage(Character character, Collider other, XenoHitboxType type) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Invalid comparison between Unknown and I4 //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Expected O, but got Unknown Vector3 val = other.ClosestPoint(((Component)this).transform.position); Vector3 val2 = ((Component)character).transform.position - val; Vector3 normalized = ((Vector3)(ref val2)).normalized; HitData val3 = new HitData { m_point = val, m_dir = normalized, m_hitType = (HitType)1, m_staggerMultiplier = 50f, m_pushForce = pushForce, m_hitCollider = other, m_attacker = xenoCharacter.GetZDOID(), m_blockable = true, m_dodgeable = true, m_ranged = false, m_toolTier = (short)(((int)type != 2) ? 1 : 99), m_radius = 0f, m_damage = GetDamageFromType(type) }; character.Damage(val3); } private static DamageTypes GetDamageFromType(XenoHitboxType type) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Invalid comparison between Unknown and I4 //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if ((int)type == 0) { return EldritchPrefabRegistry.XenoDroneTailDamage; } if ((int)type == 1) { return EldritchPrefabRegistry.XenoDroneArmDamage; } if ((int)type == 2) { return EldritchPrefabRegistry.XenoDroneBloodDamage; } throw new Exception("Unknown damage type"); } private void ApplyDestructibleDamage(GameObject obj, IDestructible destructible, XenoHitboxType type, Collider? collider = null) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Expected O, but got Unknown if ((Object)(object)collider == (Object)null) { collider = obj.GetComponent<Collider>(); } Vector3 val = (((Object)(object)collider == (Object)null) ? obj.transform.position : collider.ClosestPoint(((Component)this).transform.position)); Vector3 val2 = obj.transform.position - val; Vector3 normalized = ((Vector3)(ref val2)).normalized; HitData val3 = new HitData { m_point = val, m_dir = normalized, m_hitType = (HitType)1, m_pushForce = pushForce, m_hitCollider = collider, m_blockable = true, m_dodgeable = true, m_ranged = false, m_toolTier = (short)(((int)type != 2) ? 1 : 99), m_radius = 0f, m_attacker = xenoCharacter.GetZDOID(), m_damage = GetDamageFromType(type) }; destructible.Damage(val3); } public bool MonsterUpdateAIMethod(float dt) { //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Invalid comparison between Unknown and I4 //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Invalid comparison between Unknown and I4 //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Invalid comparison between Unknown and I4 //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Invalid comparison between Unknown and I4 //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Invalid comparison between Unknown and I4 //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Invalid comparison between Unknown and I4 //IL_0249: Unknown result type (might be due to invalid IL or missing references) //IL_0254: Unknown result type (might be due to invalid IL or missing references) //IL_032b: Unknown result type (might be due to invalid IL or missing references) //IL_033b: Unknown result type (might be due to invalid IL or missing references) //IL_0340: Unknown result type (might be due to invalid IL or missing references) //IL_02e1: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Unknown result type (might be due to invalid IL or missing references) //IL_03e1: Unknown result type (might be due to invalid IL or missing references) //IL_03b0: Unknown result type (might be due to invalid IL or missing references) //IL_0400: Unknown result type (might be due to invalid IL or missing references) //IL_03ce: Unknown result type (might be due to invalid IL or missing references) //IL_0454: Unknown result type (might be due to invalid IL or missing references) //IL_0466: Unknown result type (might be due to invalid IL or missing references) //IL_046b: Unknown result type (might be due to invalid IL or missing references) //IL_052e: Unknown result type (might be due to invalid IL or missing references) //IL_0708: Unknown result type (might be due to invalid IL or missing references) //IL_0a96: Unknown result type (might be due to invalid IL or missing references) //IL_0a9c: Invalid comparison between Unknown and I4 //IL_0ab5: Unknown result type (might be due to invalid IL or missing references) //IL_0abb: Invalid comparison between Unknown and I4 //IL_0aa4: Unknown result type (might be due to invalid IL or missing references) //IL_0aaa: Invalid comparison between Unknown and I4 //IL_072e: Unknown result type (might be due to invalid IL or missing references) //IL_0733: Unknown result type (might be due to invalid IL or missing references) //IL_0738: Unknown result type (might be due to invalid IL or missing references) //IL_073a: Unknown result type (might be due to invalid IL or missing references) //IL_0742: Unknown result type (might be due to invalid IL or missing references) //IL_07fd: Unknown result type (might be due to invalid IL or missing references) //IL_069a: Unknown result type (might be due to invalid IL or missing references) //IL_0688: Unknown result type (might be due to invalid IL or missing references) //IL_085e: Unknown result type (might be due to invalid IL or missing references) //IL_0863: Unknown result type (might be due to invalid IL or missing references) //IL_0869: Unknown result type (might be due to invalid IL or missing references) //IL_0874: Unknown result type (might be due to invalid IL or missing references) //IL_0776: Unknown result type (might be due to invalid IL or missing references) //IL_069f: Unknown result type (might be due to invalid IL or missing references) //IL_06a3: Unknown result type (might be due to invalid IL or missing references) //IL_0b77: Unknown result type (might be due to invalid IL or missing references) //IL_0aec: Unknown result type (might be due to invalid IL or missing references) //IL_0af7: Unknown result type (might be due to invalid IL or missing references) //IL_07bd: Unknown result type (might be due to invalid IL or missing references) //IL_0b57: Unknown result type (might be due to invalid IL or missing references) //IL_08f1: Unknown result type (might be due to invalid IL or missing references) //IL_08f6: Unknown result type (might be due to invalid IL or missing references) //IL_08f8: Unknown result type (might be due to invalid IL or missing references) //IL_0900: Unknown result type (might be due to invalid IL or missing references) //IL_0905: Unknown result type (might be due to invalid IL or missing references) //IL_0908: Unknown result type (might be due to invalid IL or missing references) //IL_090d: Unknown result type (might be due to invalid IL or missing references) //IL_0a6a: Unknown result type (might be due to invalid IL or missing references) //IL_0a37: Unknown result type (might be due to invalid IL or missing references) //IL_0b41: Unknown result type (might be due to invalid IL or missing references) //IL_0b22: Unknown result type (might be due to invalid IL or missing references) //IL_093e: Unknown result type (might be due to invalid IL or missing references) //IL_0926: Unknown result type (might be due to invalid IL or missing references) //IL_0928: Unknown result type (might be due to invalid IL or missing references) //IL_0930: Unknown result type (might be due to invalid IL or missing references) //IL_0935: Unknown result type (might be due to invalid IL or missing references) //IL_093a: Unknown result type (might be due to invalid IL or missing references) //IL_09db: Unknown result type (might be due to invalid IL or missing references) //IL_09a6: Unknown result type (might be due to invalid IL or missing references) //IL_09ee: Unknown result type (might be due to invalid IL or missing references) if (DroneAI.abilityManager.IsDodging) { return true; } if (!ShouldSkipUpdateAI && !((MonsterAI)this).UpdateAI(dt)) { return false; } if (((BaseAI)this).IsSleeping()) { ((MonsterAI)this).UpdateSleep(dt); return true; } Character character = ((BaseAI)this).m_character; Humanoid val = (Humanoid)(object)((character is Humanoid) ? character : null); if (Object.op_Implicit((Object)(object)val) && val.m_inventory != null && val.m_inventory.GetAllItems().Count == 0) { EldritchPrefabRegistry.AddWeaponItemsToXenoInventory(val); } if (((BaseAI)this).HuntPlayer()) { ((BaseAI)this).SetAlerted(true); } bool flag = default(bool); bool flag2 = default(bool); ((MonsterAI)this).UpdateTarget(val, dt, ref flag, ref flag2); if (Object.op_Implicit((Object)(object)((BaseAI)this).m_tamable) && Object.op_Implicit((Object)(object)((BaseAI)this).m_tamable.m_saddle) && ((BaseAI)this).m_tamable.m_saddle.UpdateRiding(dt)) { return true; } if ((int)DroneAI.CurrentState == 0) { return true; } if ((int)DroneAI.CurrentState == 6) { return true; } if ((Object)(object)base.m_targetCreature != (Object)null) { DroneAI.SetPrimaryTarget(((Component)base.m_targetCreature).transform); } else if (Object.op_Implicit((Object)(object)base.m_targetStatic)) { DroneAI.SetPrimaryTarget(((Component)base.m_targetStatic).transform); } if (ShouldUseNavigationOnHunt && (int)DroneAI.CurrentState == 2 && (int)DroneAI.huntBehaviorState.State != 1) { return true; } if (ShouldUseNavigationOnHuntChargeAttack && (int)DroneAI.CurrentState == 2 && (int)DroneAI.huntBehaviorState.State == 1) { return true; } if (ShouldUseNavigationOnAttack && (int)DroneAI.CurrentState == 3) { return true; } if (ShouldSkipAiMovement) { return true; } if (base.m_avoidLand && !((BaseAI)this).m_character.IsSwimming()) { ((BaseAI)this).MoveToWater(dt, 20f); return true; } if (((MonsterAI)this).DespawnInDay() && EnvMan.IsDay() && ((Object)(object)base.m_targetCreature == (Object)null || !flag2)) { ((BaseAI)this).MoveAwayAndDespawn(dt, true); return true; } if (((MonsterAI)this).IsEventCreature() && !RandEventSystem.HaveActiveEvent()) { ((BaseAI)this).SetHuntPlayer(false); if ((Object)(object)base.m_targetCreature == (Object)null && !((BaseAI)this).IsAlerted()) { ((BaseAI)this).MoveAwayAndDespawn(dt, false); return true; } } if (base.m_fleeIfNotAlerted && !((BaseAI)this).HuntPlayer() && Object.op_Implicit((Object)(object)base.m_targetCreature) && !((BaseAI)this).IsAlerted() && (double)Vector3.Distance(((Component)base.m_targetCreature).transform.position, ((Component)this).transform.position) - (double)base.m_targetCreature.GetRadius() > (double)base.m_alertRange) { ((BaseAI)this).Flee(dt, ((Component)base.m_targetCreature).transform.position); return true; } if ((double)base.m_fleeIfLowHealth > 0.0 && (double)((BaseAI)this).m_timeSinceHurt < (double)base.m_fleeTimeSinceHurt && (Object)(object)base.m_targetCreature != (Object)null && (double)((BaseAI)this).m_character.GetHealthPercentage() < (double)base.m_fleeIfLowHealth) { ((BaseAI)this).Flee(dt, ((Component)base.m_targetCreature).transform.position); return true; } if (base.m_fleeInLava && ((BaseAI)this).m_character.InLava() && ((Object)(object)base.m_targetCreature == (Object)null || base.m_targetCreature.AboveOrInLava())) { ((BaseAI)this).Flee(dt, ((Component)((BaseAI)this).m_character).transform.position - ((Component)((BaseAI)this).m_character).transform.forward); return true; } if ((((BaseAI)this).m_afraidOfFire || ((BaseAI)this).m_avoidFire) && ((BaseAI)this).AvoidFire(dt, base.m_targetCreature, ((BaseAI)this).m_afraidOfFire)) { if (((BaseAI)this).m_afraidOfFire) { base.m_targetStatic = null; base.m_targetCreature = null; } return true; } if (!((BaseAI)this).m_character.IsTamed()) { if ((Object)(object)base.m_targetCreature != (Object)null) { if (Object.op_Implicit((Object)(object)EffectArea.IsPointInsideNoMonsterArea(((Component)base.m_targetCreature).transform.position))) { ((BaseAI)this).Flee(dt, ((Component)base.m_targetCreature).transform.position); return true; } } else { EffectArea val2 = EffectArea.IsPointCloseToNoMonsterArea(((Component)this).transform.position); if ((Object)(object)val2 != (Object)null) { ((BaseAI)this).Flee(dt, ((Component)val2).transform.position); return true; } } } if (base.m_fleeIfHurtWhenTargetCantBeReached && (Object)(object)base.m_targetCreature != (Object)null && (double)base.m_timeSinceAttacking > 30.0 && (double)((BaseAI)this).m_timeSinceHurt < 20.0) { ((BaseAI)this).Flee(dt, ((Component)base.m_targetCreature).transform.position); base.m_lastKnownTargetPos = ((Component)this).transform.position; base.m_updateTargetTimer = 1f; return true; } if ((!((BaseAI)this).IsAlerted() || ((Object)(object)base.m_targetStatic == (Object)null && (Object)(object)base.m_targetCreature == (Object)null)) && ((MonsterAI)this).UpdateConsumeItem(val, dt)) { return true; } if ((double)base.m_circleTargetInterval > 0.0 && Object.op_Implicit((Object)(object)base.m_targetCreature)) { base.m_pauseTimer += dt; if ((double)base.m_pauseTimer > (double)base.m_circleTargetInterval) { if ((double)base.m_pauseTimer > (double)base.m_circleTargetInterval + (double)base.m_circleTargetDuration) { base.m_pauseTimer = Random.Range(0f, base.m_circleTargetInterval / 10f); } ((BaseAI)this).RandomMovementArroundPoint(dt, ((Component)base.m_targetCreature).transform.position, base.m_circleTargetDistance, ((BaseAI)this).IsAlerted()); return true; } } ItemData val3 = ((MonsterAI)this).SelectBestAttack(val, dt); bool flag3 = val3 != null && (double)Time.time - (double)val3.m_lastAttackTime > (double)val3.m_shared.m_aiAttackInterval && (double)((BaseAI)this).m_character.GetTimeSinceLastAttack() >= (double)base.m_minAttackInterval && !((BaseAI)this).IsTakingOff(); if (!((BaseAI)this).IsCharging() && ((Object)(object)base.m_targetStatic != (Object)null || (Object)(object)base.m_targetCreature != (Object)null) && val3 != null && flag3 && !((BaseAI)this).m_character.InAttack() && val3.m_shared.m_attack != null && !val3.m_shared.m_attack.IsDone() && !string.IsNullOrEmpty(val3.m_shared.m_attack.m_chargeAnimationBool)) { ((BaseAI)this).ChargeStart(val3.m_shared.m_attack.m_chargeAnimationBool); } if ((((BaseAI)this).m_character.IsFlying() ? base.m_circulateWhileChargingFlying : base.m_circulateWhileCharging) && ((Object)(object)base.m_targetStatic != (Object)null || (Object)(object)base.m_targetCreature != (Object)null) && val3 != null && !flag3 && !((BaseAI)this).m_character.InAttack()) { Vector3 val4 = (Object.op_Implicit((Object)(object)base.m_targetCreature) ? ((Component)base.m_targetCreature).transform.position : ((Component)base.m_targetStatic).transform.position); ((BaseAI)this).RandomMovementArroundPoint(dt, val4, ((BaseAI)this).m_randomMoveRange, ((BaseAI)this).IsAlerted()); return true; } if (((Object)(object)base.m_targetStatic == (Object)null && (Object)(object)base.m_targetCreature == (Object)null) || val3 == null) { if (Object.op_Implicit((Object)(object)base.m_follow)) { ((BaseAI)this).Follow(base.m_follow, dt); } else { ((BaseAI)this).IdleMovement(dt); } ((BaseAI)this).ChargeStop(); return true; } if ((int)val3.m_shared.m_aiTargetType == 0) { if (Object.op_Implicit((Object)(object)base.m_targetStatic)) { Vector3 val5 = base.m_targetStatic.FindClosestPoint(((Component)this).transform.position); if ((double)Vector3.Distance(val5, ((Component)this).transform.position) < (double)val3.m_shared.m_aiAttackRange && ((BaseAI)this).CanSeeTarget(base.m_targetStatic)) { ((BaseAI)this).LookAt(base.m_targetStatic.GetCenter()); if ((double)val3.m_shared.m_aiAttackMaxAngle == 0.0) { ZLog.LogError((object)("AI Attack Max Angle for " + val3.m_shared.m_name + " is 0!")); } if (((BaseAI)this).IsLookingAt(base.m_targetStatic.GetCenter(), val3.m_shared.m_aiAttackMaxAngle, val3.m_shared.m_aiInvertAngleCheck) && flag3) { ((MonsterAI)this).DoAttack((Character)null, false); } else { ((BaseAI)this).StopMoving(); } } else { ((BaseAI)this).MoveTo(dt, val5, 0f, ((BaseAI)this).IsAlerted()); ((BaseAI)this).ChargeStop(); } } else if (Object.op_Implicit((Object)(object)base.m_targetCreature)) { if (flag || flag2 || (((BaseAI)this).HuntPlayer() && base.m_targetCreature.IsPlayer())) { base.m_beenAtLastPos = false; base.m_lastKnownTargetPos = ((Component)base.m_targetCreature).transform.position; float num = Vector3.Distance(base.m_lastKnownTargetPos, ((Component)this).transform.position) - base.m_targetCreature.GetRadius(); float num2 = base.m_alertRange * base.m_targetCreature.GetStealthFactor(); if (flag2 && (double)num < (double)num2) { ((BaseAI)this).SetAlerted(true); } bool num3 = (double)num < (double)val3.m_shared.m_aiAttackRange; if (!num3 || !flag2 || (double)val3.m_shared.m_aiAttackRangeMin < 0.0 || !((BaseAI)this).IsAlerted()) { Vector3 velocity = base.m_targetCreature.GetVelocity(); Vector3 val6 = velocity * base.m_interceptTime; Vector3 val7 = base.m_lastKnownTargetPos; if ((double)num > (double)((Vector3)(ref val6)).magnitude / 4.0) { val7 += velocity * base.m_interceptTime; } ((BaseAI)this).MoveTo(dt, val7, 0f, ((BaseAI)this).IsAlerted()); if ((double)base.m_timeSinceAttacking > 15.0) { base.m_unableToAttackTargetTimer = 15f; } } else { ((BaseAI)this).StopMoving(); } if (num3 && flag2 && ((BaseAI)this).IsAlerted()) { if (((MonsterAI)this).PheromoneFleeCheck(base.m_targetCreature)) { ((BaseAI)this).Flee(dt, ((Component)base.m_targetCreature).transform.position); base.m_updateTargetTimer = Random.Range(base.m_fleePheromoneMin, base.m_fleePheromoneMax); base.m_targetCreature = null; } else { ((BaseAI)this).LookAt(base.m_targetCreature.GetTopPoint()); if (flag3 && ((BaseAI)this).IsLookingAt(base.m_lastKnownTargetPos, val3.m_shared.m_aiAttackMaxAngle, val3.m_shared.m_aiInvertAngleCheck)) { ((MonsterAI)this).DoAttack(base.m_targetCreature, false); } } } } else { ((BaseAI)this).ChargeStop(); if (base.m_beenAtLastPos) { ((BaseAI)this).RandomMovement(dt, base.m_lastKnownTargetPos, false); if ((double)base.m_timeSinceAttacking > 15.0) { base.m_unableToAttackTargetTimer = 15f; } } else if (((BaseAI)this).MoveTo(dt, base.m_lastKnownTargetPos, 0f, ((BaseAI)this).IsAlerted())) { base.m_beenAtLastPos = true; } } } } else if ((int)val3.m_shared.m_aiTargetType == 1 || (int)val3.m_shared.m_aiTargetType == 2) { Character val8 = (((int)val3.m_shared.m_aiTargetType == 1) ? ((BaseAI)this).HaveHurtFriendInRange(((BaseAI)this).m_viewRange) : ((BaseAI)this).HaveFriendInRange(((BaseAI)this).m_viewRange)); if (Object.op_Implicit((Object)(object)val8)) { if ((double)Vector3.Distance(((Component)val8).transform.position, ((Component)this).transform.position) < (double)val3.m_shared.m_aiAttackRange) { if (flag3) { ((BaseAI)this).StopMoving(); ((BaseAI)this).LookAt(((Component)val8).transform.position); ((MonsterAI)this).DoAttack(val8, true); } else { ((BaseAI)this).RandomMovement(dt, ((Component)val8).transform.position, false); } } else { ((BaseAI)this).MoveTo(dt, ((Component)val8).transform.position, 0f, ((BaseAI)this).IsAlerted()); } } else { ((BaseAI)this).RandomMovement(dt, ((Component)this).transform.position, true); } } return true; } public override bool UpdateAI(float dt) { return MonsterUpdateAIMethod(dt); } } public static class XenoFromSeekerMinimalMerge { private const BindingFlags F = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; private static readonly HashSet<Type> DenyTypes = new HashSet<Type> { typeof(Transform), typeof(Animator), typeof(Animation), typeof(SkinnedMeshRenderer), typeof(MeshRenderer), typeof(MeshFilter), typeof(Light), typeof(ReflectionProbe), typeof(LODGroup), typeof(ParticleSystem), typeof(ParticleSystemRenderer), typeof(TrailRenderer), typeof(LineRenderer), typeof(Cloth), typeof(Rigidbody), typeof(Collider), typeof(CharacterController) }; private static readonly HashSet<string> DenyFieldNames = new HashSet<string>(StringComparer.Ordinal) { "m_animator", "m_head", "m_eye", "m_visual", "m_visualRoot", "m_model", "m_root" }; private static readonly HashSet<string> WhitelistTypeNames = new HashSet<string>(StringComparer.Ordinal) { "Character", "Humanoid", "BaseAI", "MonsterAI", "SEMan", "Noise", "FootStep", "Tameable", "ZNetView", "ZSyncTransform", "ZSyncAnimation" }; public static bool MergeIntoXeno(GameObject xenoInstance, GameObject seekerPrefab) { if (!Object.op_Implicit((Object)(object)xenoInstance) || !Object.op_Implicit((Object)(object)seekerPrefab)) { return false; } Animator val = FindXenoAnimator(xenoInstance); if (!Object.op_Implicit((Object)(object)val)) { Debug.LogError((object)"[XenoMerge] Xeno Animator not found; aborting merge."); return false; } GameObject val2 = Object.Instantiate<GameObject>(seekerPrefab); try { Component[] components = val2.GetComponents<Component>(); foreach (Component val3 in components) { if (Object.op_Implicit((Object)(object)val3)) { Type type = ((object)val3).GetType(); if (!DenyTypes.Contains(type) && (WhitelistTypeNames.Count <= 0 || WhitelistTypeNames.Contains(type.Name)) && !Object.op_Implicit((Object)(object)xenoInstance.GetComponent(type))) { Component dst = xenoInstance.AddComponent(type); CopySerializableFields(val3, dst, DenyFieldNames); PostCopyFixups(dst, val); } } } Humanoid component = xenoInstance.GetComponent<Humanoid>(); if (Object.op_Implicit((Object)(object)component) && (Object)(object)((Character)component).m_animator != (Object)(object)val) { ((Character)component).m_animator = val; } EnsureZSyncAnimationLivesOnAnimator(xenoInstance, val); val.Rebind(); val.Update(0f); val.cullingMode = (AnimatorCullingMode)0; return true; } finally { Object.Destroy((Object)(object)val2); } } private static Animator FindXenoAnimator(GameObject xeno) { Transform val = xeno.transform.Find("Visual"); if (Object.op_Implicit((Object)(object)val)) { Animator componentInChildren = ((Component)val).GetComponentInChildren<Animator>(true); if (Object.op_Implicit((Object)(object)componentInChildren)) { return componentInChildren; } } return xeno.GetComponentInChildren<Animator>(true); } private static void CopySerializableFields(Component src, Component dst, HashSet<string> skipNames) { Type type = ((object)src).GetType(); Type type2 = ((object)dst).GetType(); FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral || fieldInfo.Name == "m_Script" || skipNames.Contains(fieldInfo.Name)) { continue; } FieldInfo field = type2.GetField(fieldInfo.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field == null || field.FieldType != fieldInfo.FieldType) { continue; } object value = fieldInfo.GetValue(src); if (!(value is Transform) && !(value is Animator) && !(value is Renderer) && !(value is MeshFilter)) { try { field.SetValue(dst, value); } catch { } } } } private static void PostCopyFixups(Component dst, Animator xenoAnimator) { if (Object.op_Implicit((Object)(object)dst) && Object.op_Implicit((Object)(object)xenoAnimator)) { FieldInfo field = ((object)dst).GetType().GetField("m_animator", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != null && typeof(Animator).IsAssignableFrom(field.FieldType)) { field.SetValue(dst, xenoAnimator); } } } private static void EnsureZSyncAnimationLivesOnAnimator(GameObject xenoRoot, Animator anim) { if (Object.op_Implicit((Object)(object)xenoRoot) && Object.op_Implicit((Object)(object)anim)) { ZSyncAnimation component = xenoRoot.GetComponent<ZSyncAnimation>(); if (Object.op_Implicit((Object)(object)component) && (Object)(object)((Component)component).gameObject != (Object)(object)((Component)anim).gameObject) { Object.Destroy((Object)(object)component); } ZSyncAnimation val = ((Component)anim).GetComponent<ZSyncAnimation>() ?? ((Component)anim).gameObject.AddComponent<ZSyncAnimation>(); FieldInfo field = ((object)val).GetType().GetField("m_animator", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != null && typeof(Animator).IsAssignableFrom(field.FieldType)) { field.SetValue(val, anim); } } } } public static class XenoFromSeekerBuilder { private static readonly Type[] TopLevelApis = new Type[4] { typeof(XenoDroneAI), typeof(XenoAIMovementController), typeof(AbilityManager), typeof(XenoAudioController) }; public static bool BuildXenoFromSeeker(GameObject seekerCloneRoot, GameObject xenoVisualPrefab, GameObject xenoTemplateRoot) { //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)seekerCloneRoot) || !Object.op_Implicit((Object)(object)xenoVisualPrefab) || !Object.op_Implicit((Object)(object)xenoTemplateRoot)) { LoggerProvider.LogError("BuildXenoFromSeeker: missing required prefabs/roots.", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\XenoSeekerBuilder.cs", 41); return false; } ZNetView nview = seekerCloneRoot.GetComponent<ZNetView>() ?? seekerCloneRoot.AddComponent<ZNetView>(); Character character = seekerCloneRoot.GetComponent<Character>() ?? seekerCloneRoot.AddComponent<Character>(); if (seekerCloneRoot.GetComponent<ZSyncTransform>() == null) { seekerCloneRoot.AddComponent<ZSyncTransform>(); } if (seekerCloneRoot.GetComponent<ZSyncAnimation>() == null) { seekerCloneRoot.AddComponent<ZSyncAnimation>(); } CapsuleCollider component = seekerCloneRoot.GetComponent<CapsuleCollider>(); CapsuleCollider component2 = xenoTemplateRoot.GetComponent<CapsuleCollider>(); if (Object.op_Implicit((Object)(object)component2)) { if (Object.op_Implicit((Object)(object)component)) { LayerHelpers.GetActiveLayers(((Collider)component).includeLayers, "seekerCapsule includeLayers"); LayerHelpers.GetActiveLayers(((Collider)component).includeLayers, "seekerCapsule excludeLayers"); PrefabGraft.CopyFields((Component)(object)component2, (Component)(object)component); } else { CapsuleCollider dst = seekerCloneRoot.AddComponent<CapsuleCollider>(); PrefabGraft.CopyFields((Component)(object)component2, (Component)(object)dst); } } else if (!Object.op_Implicit((Object)(object)component)) { LoggerProvider.LogDebug("No SeekerCapsule detected; adding default Xeno capsule.", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\XenoSeekerBuilder.cs", 72); CapsuleCollider obj = seekerCloneRoot.AddComponent<CapsuleCollider>(); obj.center = new Vector3(0f, 1.5f, 0f); obj.radius = 0.7f; obj.height = 3f; } Animator val = PrefabGraft.ReplaceVisual(seekerCloneRoot, xenoVisualPrefab); if (!Object.op_Implicit((Object)(object)val)) { LoggerProvider.LogError("BuildXenoFromSeeker: animator not found after Visual swap.", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\XenoSeekerBuilder.cs", 84); return false; } ExposedGameObjectExtension.GetOrAddComponent<CharacterAnimEvent>(((Component)val).gameObject).m_nview = nview; MonsterAI component3 = seekerCloneRoot.GetComponent<MonsterAI>(); XenoDrone_MonsterAI orAddComponent = ExposedGameObjectExtension.GetOrAddComponent<XenoDrone_MonsterAI>(seekerCloneRoot); if (Object.op_Implicit((Object)(object)component3)) { PrefabGraft.CopyFields((Component)(object)component3, (Component)(object)orAddComponent); ((BaseAI)orAddComponent).m_character = character; int num = PrefabGraft.RemapObjectReferences(seekerCloneRoot, (Object)(object)component3, (Object)(object)orAddComponent); Object.DestroyImmediate((Object)(object)component3); LoggerProvider.LogInfo($"MonsterAI→XenoDrone_MonsterAI migrated; remapped {num} refs.", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\XenoSeekerBuilder.cs", 100); } else { ((BaseAI)orAddComponent).m_character = character; } Type[] topLevelApis = TopLevelApis; foreach (Type type in topLevelApis) { Component component4 = xenoTemplateRoot.GetComponent(type); Component val2 = seekerCloneRoot.GetComponent(type) ?? seekerCloneRoot.AddComponent(type); if (Object.op_Implicit((Object)(object)component4)) { PrefabGraft.CopyFields(component4, val2); } TryBindCommonFields(val2, character, (MonsterAI)(object)orAddComponent, val); PrefabGraft.RemapObjectReferences(seekerCloneRoot, (Object)(object)component4, (Object)(object)val2); } val.Rebind(); val.Update(0f); return true; } private static void TryBindCommonFields(Component cmp, Character character, MonsterAI ai, Animator animator) { Component cmp2 = cmp; Type t; BindingFlags f; if (Object.op_Implicit((Object)(object)cmp2)) { t = ((object)cmp2).GetType(); f = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; SetIfExists("m_character", character); SetIfExists("character", character); SetIfExists("ownerCharacter", character); SetIfExists("m_ai", ai); SetIfExists("ai", ai); SetIfExists("brain", ai); SetIfExists("m_animator", animator); SetIfExists("animator", animator); SetIfExists("animationController", animator); } void SetIfExists(string name, object value) { FieldInfo field = t.GetField(name, f); if (field != null && field.FieldType.IsInstanceOfType(value)) { field.SetValue(cmp2, value); } } } } public static class XenoSeekerSwap { public static bool SwapToXeno(GameObject seekerClone, GameObject xenoVisualPrefab) { //IL_00e9: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)seekerClone) || !Object.op_Implicit((Object)(object)xenoVisualPrefab)) { return false; } Animator val = ComponentSwapUtil.ReplaceVisual(seekerClone, xenoVisualPrefab); ComponentSwapUtil.SafeAnimatorRebind(val); Character character = seekerClone.GetComponent<Character>() ?? seekerClone.AddComponent<Character>(); ZNetView nview = seekerClone.GetComponent<ZNetView>() ?? seekerClone.AddComponent<ZNetView>(); if (Object.op_Implicit((Object)(object)val)) { GameObject gameObject = ((Component)val).gameObject; (gameObject.GetComponent<CharacterAnimEvent>() ?? gameObject.AddComponent<CharacterAnimEvent>()).m_nview = nview; } MonsterAI component = seekerClone.GetComponent<MonsterAI>(); if (!Object.op_Implicit((Object)(object)component)) { LoggerProvider.LogError("SwapToXeno: Source MonsterAI not found on clone.", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\XenoSeekerSwap.cs", 46); return false; } Xeno_MonsterAI xeno_MonsterAI = seekerClone.GetComponent<Xeno_MonsterAI>(); if (!Object.op_Implicit((Object)(object)xeno_MonsterAI)) { xeno_MonsterAI = seekerClone.AddComponent<Xeno_MonsterAI>(); } ComponentSwapUtil.CopyFields((Component)(object)component, (Component)(object)xeno_MonsterAI); ((BaseAI)xeno_MonsterAI).m_character = character; int num = ComponentSwapUtil.RemapObjectReferences(seekerClone, (Object)(object)component, (Object)(object)xeno_MonsterAI); Object.DestroyImmediate((Object)(object)component); if (!Object.op_Implicit((Object)(object)seekerClone.GetComponent<CapsuleCollider>())) { CapsuleCollider obj = seekerClone.AddComponent<CapsuleCollider>(); obj.center = new Vector3(0f, 1f, 0f); obj.radius = 0.45f; obj.height = 2f; } LoggerProvider.LogInfo($"SwapToXeno complete: migrated MonsterAI -> Xeno_MonsterAI, remapped {num} refs.", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Eldritch.Valheim\\XenoSeekerSwap.cs", 77); return true; } } public class Xeno_MonsterAI : MonsterAI { } } namespace Eldritch.Core { public static class ComponentSwapUtil { private static readonly BindingFlags FieldFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; public static void CopyFields(Component source, Component target) { if (!Object.op_Implicit((Object)(object)source) || !Object.op_Implicit((Object)(object)target)) { return; } Type type = ((object)source).GetType(); Type type2 = ((object)target).GetType(); FieldInfo[] fields = type.GetFields(FieldFlags); foreach (FieldInfo fieldInfo in fields) { if (fieldInfo.Name == "m_Script") { continue; } FieldInfo field = type2.GetField(fieldInfo.Name, FieldFlags); if (!(field == null) && !(field.FieldType != fieldInfo.FieldType)) { try { object value = fieldInfo.GetValue(source); field.SetValue(target, value); } catch { } } } } public static int RemapObjectReferences(GameObject root, Object fromObj, Object toObj) { if (!Object.op_Implicit((Object)(object)root) || !Object.op_Implicit(fromObj) || !Object.op_Implicit(toObj)) { return 0; } int num = 0; Component[] componentsInChildren = root.GetComponentsInChildren<Component>(true); foreach (Component val in componentsInChildren) { if (!Object.op_Implicit((Object)(object)val)) { continue; } FieldInfo[] fields = ((object)val).GetType().GetFields(FieldFlags); foreach (FieldInfo fieldInfo in fields) { if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral) { continue; } Type fieldType = fieldInfo.FieldType; if (typeof(Object).IsAssignableFrom(fieldType)) { object? value = fieldInfo.GetValue(val); if ((Object)((value is Object) ? value : null) == fromObj && fieldType.IsAssignableFrom(((object)toObj).GetType())) { fieldInfo.SetValue(val, toObj); num++; } } else if (fieldType.IsArray && typeof(Object).IsAssignableFrom(fieldType.GetElementType())) { if (!(fieldInfo.GetValue(val) is Array array)) { continue; } bool flag = false; Type elementType = fieldType.GetElementType(); Array array2 = Array.CreateInstance(elementType, array.Length); for (int k = 0; k < array.Length; k++) { object? value2 = array.GetValue(k); if ((Object)((value2 is Object) ? value2 : null) == fromObj && elementType.IsAssignableFrom(((object)toObj).GetType())) { array2.SetValue(toObj, k); flag = true; num++; } else { array2.SetValue(array.GetValue(k), k); } } if (flag) { fieldInfo.SetValue(val, array2); } } else { if (!fieldType.IsGenericType || !(fieldType.GetGenericTypeDefinition() == typeof(List<>))) { continue; } Type type = fieldType.GetGenericArguments()[0]; if (!typeof(Object).IsAssignableFrom(type) || !(fieldInfo.GetValue(val) is IList list)) { continue; } bool flag2 = false; for (int l = 0; l < list.Count; l++) { object? obj = list[l]; if ((Object)((obj is Object) ? obj : null) == fromObj && type.IsAssignableFrom(((object)toObj).GetType())) { list[l] = toObj; flag2 = true; num++; } } if (flag2) { fieldInfo.SetValue(val, list); } } } } return num; } public static Animator ReplaceVisual(GameObject root, GameObject visualPrefab) { if (!Object.op_Implicit((Object)(object)root) || !Object.op_Implicit((Object)(object)visualPrefab)) { return null; } Transform val = root.transform.Find("Visual"); if (Object.op_Implicit((Object)(object)val)) { Object.DestroyImmediate((Object)(object)((Component)val).gameObject); } GameObject val2 = Object.Instantiate<GameObject>(visualPrefab, root.transform, false); ((Object)val2).name = ((Object)visualPrefab).name; return val2.GetComponentInChildren<Animator>(true) ?? val2.AddComponent<Animator>(); } public static void SafeAnimatorRebind(Animator animator) { if (Object.op_Implicit((Object)(object)animator)) { animator.Rebind(); animator.Update(0f); } } } public static class PrefabGraft { private static readonly BindingFlags F = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; public static void CopyFields(Component src, Component dst) { if (!Object.op_Implicit((Object)(object)src)
plugins\Newtonsoft.Json.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.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Newtonsoft.Json.Bson; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq.JsonPath; using Newtonsoft.Json.Schema; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AllowPartiallyTrustedCallers] [assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")] [assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")] [assembly: CLSCompliant(true)] [assembly: TargetFramework(".NETFramework,Version=v4.5", FrameworkDisplayName = ".NET Framework 4.5")] [assembly: AssemblyCompany("Newtonsoft")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © James Newton-King 2008")] [assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")] [assembly: AssemblyFileVersion("13.0.3.27908")] [assembly: AssemblyInformationalVersion("13.0.3+0a2e291c0d9c0c7675d445703e51750363a549ef")] [assembly: AssemblyProduct("Json.NET")] [assembly: AssemblyTitle("Json.NET .NET 4.5")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/JamesNK/Newtonsoft.Json")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("13.0.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } } namespace Newtonsoft.Json { public enum ConstructorHandling { Default, AllowNonPublicDefaultConstructor } public enum DateFormatHandling { IsoDateFormat, MicrosoftDateFormat } public enum DateParseHandling { None, DateTime, DateTimeOffset } public enum DateTimeZoneHandling { Local, Utc, Unspecified, RoundtripKind } public class DefaultJsonNameTable : JsonNameTable { private class Entry { internal readonly string Value; internal readonly int HashCode; internal Entry Next; internal Entry(string value, int hashCode, Entry next) { Value = value; HashCode = hashCode; Next = next; } } private static readonly int HashCodeRandomizer; private int _count; private Entry[] _entries; private int _mask = 31; static DefaultJsonNameTable() { HashCodeRandomizer = Environment.TickCount; } public DefaultJsonNameTable() { _entries = new Entry[_mask + 1]; } public override string? Get(char[] key, int start, int length) { if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; num += (num << 7) ^ key[start]; int num2 = start + length; for (int i = start + 1; i < num2; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; int num3 = Volatile.Read(ref _mask); int num4 = num & num3; for (Entry entry = _entries[num4]; entry != null; entry = entry.Next) { if (entry.HashCode == num && TextEquals(entry.Value, key, start, length)) { return entry.Value; } } return null; } public string Add(string key) { if (key == null) { throw new ArgumentNullException("key"); } int length = key.Length; if (length == 0) { return string.Empty; } int num = length + HashCodeRandomizer; for (int i = 0; i < key.Length; i++) { num += (num << 7) ^ key[i]; } num -= num >> 17; num -= num >> 11; num -= num >> 5; for (Entry entry = _entries[num & _mask]; entry != null; entry = entry.Next) { if (entry.HashCode == num && entry.Value.Equals(key, StringComparison.Ordinal)) { return entry.Value; } } return AddEntry(key, num); } private string AddEntry(string str, int hashCode) { int num = hashCode & _mask; Entry entry = new Entry(str, hashCode, _entries[num]); _entries[num] = entry; if (_count++ == _mask) { Grow(); } return entry.Value; } private void Grow() { Entry[] entries = _entries; int num = _mask * 2 + 1; Entry[] array = new Entry[num + 1]; for (int i = 0; i < entries.Length; i++) { Entry entry = entries[i]; while (entry != null) { int num2 = entry.HashCode & num; Entry next = entry.Next; entry.Next = array[num2]; array[num2] = entry; entry = next; } } _entries = array; Volatile.Write(ref _mask, num); } private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length) { if (str1.Length != str2Length) { return false; } for (int i = 0; i < str1.Length; i++) { if (str1[i] != str2[str2Start + i]) { return false; } } return true; } } [Flags] public enum DefaultValueHandling { Include = 0, Ignore = 1, Populate = 2, IgnoreAndPopulate = 3 } public enum FloatFormatHandling { String, Symbol, DefaultValue } public enum FloatParseHandling { Double, Decimal } public enum Formatting { None, Indented } public interface IArrayPool<T> { T[] Rent(int minimumLength); void Return(T[]? array); } public interface IJsonLineInfo { int LineNumber { get; } int LinePosition { get; } bool HasLineInfo(); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonArrayAttribute : JsonContainerAttribute { private bool _allowNullItems; public bool AllowNullItems { get { return _allowNullItems; } set { _allowNullItems = value; } } public JsonArrayAttribute() { } public JsonArrayAttribute(bool allowNullItems) { _allowNullItems = allowNullItems; } public JsonArrayAttribute(string id) : base(id) { } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)] public sealed class JsonConstructorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public abstract class JsonContainerAttribute : Attribute { internal bool? _isReference; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; private Type? _namingStrategyType; private object[]? _namingStrategyParameters; public string? Id { get; set; } public string? Title { get; set; } public string? Description { get; set; } public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get { return _namingStrategyType; } set { _namingStrategyType = value; NamingStrategyInstance = null; } } public object[]? NamingStrategyParameters { get { return _namingStrategyParameters; } set { _namingStrategyParameters = value; NamingStrategyInstance = null; } } internal NamingStrategy? NamingStrategyInstance { get; set; } public bool IsReference { get { return _isReference.GetValueOrDefault(); } set { _isReference = value; } } public bool ItemIsReference { get { return _itemIsReference.GetValueOrDefault(); } set { _itemIsReference = value; } } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } protected JsonContainerAttribute() { } protected JsonContainerAttribute(string id) { Id = id; } } public static class JsonConvert { public static readonly string True = "true"; public static readonly string False = "false"; public static readonly string Null = "null"; public static readonly string Undefined = "undefined"; public static readonly string PositiveInfinity = "Infinity"; public static readonly string NegativeInfinity = "-Infinity"; public static readonly string NaN = "NaN"; public static Func<JsonSerializerSettings>? DefaultSettings { get; set; } public static string ToString(DateTime value) { return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); } public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling); using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(DateTimeOffset value) { return ToString(value, DateFormatHandling.IsoDateFormat); } public static string ToString(DateTimeOffset value, DateFormatHandling format) { using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(bool value) { if (!value) { return False; } return True; } public static string ToString(char value) { return ToString(char.ToString(value)); } public static string ToString(Enum value) { return value.ToString("D"); } public static string ToString(int value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(short value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ushort value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(uint value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(long value) { return value.ToString(null, CultureInfo.InvariantCulture); } private static string ToStringInternal(BigInteger value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ulong value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(float value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value))) { return text; } if (floatFormatHandling == FloatFormatHandling.DefaultValue) { if (nullable) { return Null; } return "0.0"; } return quoteChar + text + quoteChar; } public static string ToString(double value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureDecimalPlace(double value, string text) { if (double.IsNaN(value) || double.IsInfinity(value) || StringUtils.IndexOf(text, '.') != -1 || StringUtils.IndexOf(text, 'E') != -1 || StringUtils.IndexOf(text, 'e') != -1) { return text; } return text + ".0"; } private static string EnsureDecimalPlace(string text) { if (StringUtils.IndexOf(text, '.') != -1) { return text; } return text + ".0"; } public static string ToString(byte value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(sbyte value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(decimal value) { return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture)); } public static string ToString(Guid value) { return ToString(value, '"'); } internal static string ToString(Guid value, char quoteChar) { string text = value.ToString("D", CultureInfo.InvariantCulture); string text2 = quoteChar.ToString(CultureInfo.InvariantCulture); return text2 + text + text2; } public static string ToString(TimeSpan value) { return ToString(value, '"'); } internal static string ToString(TimeSpan value, char quoteChar) { return ToString(value.ToString(), quoteChar); } public static string ToString(Uri? value) { if (value == null) { return Null; } return ToString(value, '"'); } internal static string ToString(Uri value, char quoteChar) { return ToString(value.OriginalString, quoteChar); } public static string ToString(string? value) { return ToString(value, '"'); } public static string ToString(string? value, char delimiter) { return ToString(value, delimiter, StringEscapeHandling.Default); } public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling) { if (delimiter != '"' && delimiter != '\'') { throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter"); } return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling); } public static string ToString(object? value) { if (value == null) { return Null; } return ConvertUtils.GetTypeCode(value.GetType()) switch { PrimitiveTypeCode.String => ToString((string)value), PrimitiveTypeCode.Char => ToString((char)value), PrimitiveTypeCode.Boolean => ToString((bool)value), PrimitiveTypeCode.SByte => ToString((sbyte)value), PrimitiveTypeCode.Int16 => ToString((short)value), PrimitiveTypeCode.UInt16 => ToString((ushort)value), PrimitiveTypeCode.Int32 => ToString((int)value), PrimitiveTypeCode.Byte => ToString((byte)value), PrimitiveTypeCode.UInt32 => ToString((uint)value), PrimitiveTypeCode.Int64 => ToString((long)value), PrimitiveTypeCode.UInt64 => ToString((ulong)value), PrimitiveTypeCode.Single => ToString((float)value), PrimitiveTypeCode.Double => ToString((double)value), PrimitiveTypeCode.DateTime => ToString((DateTime)value), PrimitiveTypeCode.Decimal => ToString((decimal)value), PrimitiveTypeCode.DBNull => Null, PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), PrimitiveTypeCode.Guid => ToString((Guid)value), PrimitiveTypeCode.Uri => ToString((Uri)value), PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), PrimitiveTypeCode.BigInteger => ToStringInternal((BigInteger)value), _ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), }; } [DebuggerStepThrough] public static string SerializeObject(object? value) { return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static string SerializeObject(object? value, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, JsonSerializerSettings? settings) { return SerializeObject(value, null, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); return SerializeObjectInternal(value, type, jsonSerializer); } [DebuggerStepThrough] public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings) { return SerializeObject(value, null, formatting, settings); } [DebuggerStepThrough] public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); jsonSerializer.Formatting = formatting; return SerializeObjectInternal(value, type, jsonSerializer); } private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer) { StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture); using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter)) { jsonTextWriter.Formatting = jsonSerializer.Formatting; jsonSerializer.Serialize(jsonTextWriter, value, type); } return stringWriter.ToString(); } [DebuggerStepThrough] public static object? DeserializeObject(string value) { return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static object? DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value) { return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject) { return DeserializeObject<T>(value); } [DebuggerStepThrough] public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject<T>(value, settings); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, params JsonConverter[] converters) { return (T)DeserializeObject(value, typeof(T), converters); } [DebuggerStepThrough] public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings) { return (T)DeserializeObject(value, typeof(T), settings); } [DebuggerStepThrough] public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return DeserializeObject(value, type, settings); } public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings) { ValidationUtils.ArgumentNotNull(value, "value"); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); if (!jsonSerializer.IsCheckAdditionalContentSet()) { jsonSerializer.CheckAdditionalContent = true; } using JsonTextReader reader = new JsonTextReader(new StringReader(value)); return jsonSerializer.Deserialize(reader, type); } [DebuggerStepThrough] public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); } public static void PopulateObject(string value, object target, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); using JsonReader jsonReader = new JsonTextReader(new StringReader(value)); jsonSerializer.Populate(jsonReader, target); if (settings == null || !settings.CheckAdditionalContent) { return; } while (jsonReader.Read()) { if (jsonReader.TokenType != JsonToken.Comment) { throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object."); } } } public static string SerializeXmlNode(XmlNode? node) { return SerializeXmlNode(node, Formatting.None); } public static string SerializeXmlNode(XmlNode? node, Formatting formatting) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); return SerializeObject(node, formatting, xmlNodeConverter); } public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } public static XmlDocument? DeserializeXmlNode(string value) { return DeserializeXmlNode(value, null); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), xmlNodeConverter); } public static string SerializeXNode(XObject? node) { return SerializeXNode(node, Formatting.None); } public static string SerializeXNode(XObject? node, Formatting formatting) { return SerializeXNode(node, formatting, omitRootObject: false); } public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter xmlNodeConverter = new XmlNodeConverter { OmitRootObject = omitRootObject }; return SerializeObject(node, formatting, xmlNodeConverter); } public static XDocument? DeserializeXNode(string value) { return DeserializeXNode(value, null); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false); } public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown XmlNodeConverter xmlNodeConverter = new XmlNodeConverter(); xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName; xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute; xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters; return (XDocument)DeserializeObject(value, typeof(XDocument), xmlNodeConverter); } } public abstract class JsonConverter { public virtual bool CanRead => true; public virtual bool CanWrite => true; public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer); public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer); public abstract bool CanConvert(Type objectType); } public abstract class JsonConverter<T> : JsonConverter { public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (!((value != null) ? (value is T) : ReflectionUtils.IsNullable(typeof(T)))) { throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } WriteJson(writer, (T)value, serializer); } public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer); public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { bool flag = existingValue == null; if (!flag && !(existingValue is T)) { throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T))); } return ReadJson(reader, objectType, flag ? default(T) : ((T)existingValue), !flag, serializer); } public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer); public sealed override bool CanConvert(Type objectType) { return typeof(T).IsAssignableFrom(objectType); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonConverterAttribute : Attribute { private readonly Type _converterType; public Type ConverterType => _converterType; public object[]? ConverterParameters { get; } public JsonConverterAttribute(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } _converterType = converterType; } public JsonConverterAttribute(Type converterType, params object[] converterParameters) : this(converterType) { ConverterParameters = converterParameters; } } public class JsonConverterCollection : Collection<JsonConverter> { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonDictionaryAttribute : JsonContainerAttribute { public JsonDictionaryAttribute() { } public JsonDictionaryAttribute(string id) : base(id) { } } [Serializable] public class JsonException : Exception { public JsonException() { } public JsonException(string message) : base(message) { } public JsonException(string message, Exception? innerException) : base(message, innerException) { } public JsonException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message) { message = JsonPosition.FormatMessage(lineInfo, path, message); return new JsonException(message); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class JsonExtensionDataAttribute : Attribute { public bool WriteData { get; set; } public bool ReadData { get; set; } public JsonExtensionDataAttribute() { WriteData = true; ReadData = true; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonIgnoreAttribute : Attribute { } public abstract class JsonNameTable { public abstract string? Get(char[] key, int start, int length); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonObjectAttribute : JsonContainerAttribute { private MemberSerialization _memberSerialization; internal MissingMemberHandling? _missingMemberHandling; internal Required? _itemRequired; internal NullValueHandling? _itemNullValueHandling; public MemberSerialization MemberSerialization { get { return _memberSerialization; } set { _memberSerialization = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public NullValueHandling ItemNullValueHandling { get { return _itemNullValueHandling.GetValueOrDefault(); } set { _itemNullValueHandling = value; } } public Required ItemRequired { get { return _itemRequired.GetValueOrDefault(); } set { _itemRequired = value; } } public JsonObjectAttribute() { } public JsonObjectAttribute(MemberSerialization memberSerialization) { MemberSerialization = memberSerialization; } public JsonObjectAttribute(string id) : base(id) { } } internal enum JsonContainerType { None, Object, Array, Constructor } internal struct JsonPosition { private static readonly char[] SpecialCharacters = new char[18] { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' }; internal JsonContainerType Type; internal int Position; internal string? PropertyName; internal bool HasIndex; public JsonPosition(JsonContainerType type) { Type = type; HasIndex = TypeHasIndex(type); Position = -1; PropertyName = null; } internal int CalculateLength() { switch (Type) { case JsonContainerType.Object: return PropertyName.Length + 5; case JsonContainerType.Array: case JsonContainerType.Constructor: return MathUtils.IntLength((ulong)Position) + 2; default: throw new ArgumentOutOfRangeException("Type"); } } internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer) { switch (Type) { case JsonContainerType.Object: { string propertyName = PropertyName; if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append("['"); if (writer == null) { writer = new StringWriter(sb); } JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer); sb.Append("']"); } else { if (sb.Length > 0) { sb.Append('.'); } sb.Append(propertyName); } break; } case JsonContainerType.Array: case JsonContainerType.Constructor: sb.Append('['); sb.Append(Position); sb.Append(']'); break; } } internal static bool TypeHasIndex(JsonContainerType type) { if (type != JsonContainerType.Array) { return type == JsonContainerType.Constructor; } return true; } internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition) { int num = 0; if (positions != null) { for (int i = 0; i < positions.Count; i++) { num += positions[i].CalculateLength(); } } if (currentPosition.HasValue) { num += currentPosition.GetValueOrDefault().CalculateLength(); } StringBuilder stringBuilder = new StringBuilder(num); StringWriter writer = null; char[] buffer = null; if (positions != null) { foreach (JsonPosition position in positions) { position.WriteTo(stringBuilder, ref writer, ref buffer); } } currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer); return stringBuilder.ToString(); } internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message) { if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { message = message.Trim(); if (!StringUtils.EndsWith(message, '.')) { message += "."; } message += " "; } message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path); if (lineInfo != null && lineInfo.HasLineInfo()) { message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); } message += "."; return message; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonPropertyAttribute : Attribute { internal NullValueHandling? _nullValueHandling; internal DefaultValueHandling? _defaultValueHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal ObjectCreationHandling? _objectCreationHandling; internal TypeNameHandling? _typeNameHandling; internal bool? _isReference; internal int? _order; internal Required? _required; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; public Type? ItemConverterType { get; set; } public object[]? ItemConverterParameters { get; set; } public Type? NamingStrategyType { get; set; } public object[]? NamingStrategyParameters { get; set; } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public TypeNameHandling TypeNameHandling { get { return _typeNameHandling.GetValueOrDefault(); } set { _typeNameHandling = value; } } public bool IsReference { get { return _isReference.GetValueOrDefault(); } set { _isReference = value; } } public int Order { get { return _order.GetValueOrDefault(); } set { _order = value; } } public Required Required { get { return _required.GetValueOrDefault(); } set { _required = value; } } public string? PropertyName { get; set; } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling.GetValueOrDefault(); } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling.GetValueOrDefault(); } set { _itemTypeNameHandling = value; } } public bool ItemIsReference { get { return _itemIsReference.GetValueOrDefault(); } set { _itemIsReference = value; } } public JsonPropertyAttribute() { } public JsonPropertyAttribute(string propertyName) { PropertyName = propertyName; } } public abstract class JsonReader : IDisposable { protected internal enum State { Start, Complete, Property, ObjectStart, Object, ArrayStart, Array, Closed, PostValue, ConstructorStart, Constructor, Error, Finished } private JsonToken _tokenType; private object? _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; private CultureInfo? _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string? _dateFormatString; private List<JsonPosition>? _stack; protected State CurrentState => _currentState; public bool CloseInput { get; set; } public bool SupportMultipleContent { get; set; } public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException("value"); } _dateTimeZoneHandling = value; } } public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset) { throw new ArgumentOutOfRangeException("value"); } _dateParseHandling = value; } } public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) { throw new ArgumentOutOfRangeException("value"); } _floatParseHandling = value; } } public string? DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; } } public virtual JsonToken TokenType => _tokenType; public virtual object? Value => _value; public virtual Type? ValueType => _value?.GetType(); public virtual int Depth { get { int num = _stack?.Count ?? 0; if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) { return num; } return num + 1; } } public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null); return JsonPosition.BuildPath(_stack, currentPosition); } } public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } public virtual Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<bool>() ?? Read().ToAsync(); } public async Task SkipAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (TokenType == JsonToken.PropertyName) { await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) && depth < Depth) { } } } internal async Task ReaderReadAndAssertAsync(CancellationToken cancellationToken) { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { throw CreateUnexpectedEndException(); } } public virtual Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<bool?>() ?? Task.FromResult(ReadAsBoolean()); } public virtual Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<byte[]>() ?? Task.FromResult(ReadAsBytes()); } internal async Task<byte[]?> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken) { List<byte> buffer = new List<byte>(); do { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { SetToken(JsonToken.None); } } while (!ReadArrayElementIntoByteArrayReportDone(buffer)); byte[] array = buffer.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } public virtual Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<DateTime?>() ?? Task.FromResult(ReadAsDateTime()); } public virtual Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<DateTimeOffset?>() ?? Task.FromResult(ReadAsDateTimeOffset()); } public virtual Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<decimal?>() ?? Task.FromResult(ReadAsDecimal()); } public virtual Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken)) { return Task.FromResult(ReadAsDouble()); } public virtual Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<int?>() ?? Task.FromResult(ReadAsInt32()); } public virtual Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.CancelIfRequestedAsync<string>() ?? Task.FromResult(ReadAsString()); } internal async Task<bool> ReadAndMoveToContentAsync(CancellationToken cancellationToken) { bool flag = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (flag) { flag = await MoveToContentAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } return flag; } internal Task<bool> MoveToContentAsync(CancellationToken cancellationToken) { JsonToken tokenType = TokenType; if (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { return MoveToContentFromNonContentAsync(cancellationToken); } return AsyncUtils.True; } private async Task<bool> MoveToContentFromNonContentAsync(CancellationToken cancellationToken) { JsonToken tokenType; do { if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) { return false; } tokenType = TokenType; } while (tokenType == JsonToken.None || tokenType == JsonToken.Comment); return true; } internal JsonPosition GetPosition(int depth) { if (_stack != null && depth < _stack.Count) { return _stack[depth]; } return _currentPosition; } protected JsonReader() { _currentState = State.Start; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; _maxDepth = 64; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); return; } if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); if (!_maxDepth.HasValue || !(Depth + 1 > _maxDepth) || _hasExceededMaxDepth) { return; } _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } private JsonContainerType Pop() { JsonPosition currentPosition; if (_stack != null && _stack.Count > 0) { currentPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { currentPosition = _currentPosition; _currentPosition = default(JsonPosition); } if (_maxDepth.HasValue && Depth <= _maxDepth) { _hasExceededMaxDepth = false; } return currentPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } public abstract bool Read(); public virtual int? ReadAsInt32() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is int) { return (int)value; } int num; if (value is BigInteger bigInteger) { num = (int)bigInteger; } else { try { num = Convert.ToInt32(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } } SetToken(JsonToken.Integer, num, updateIndex: false); return num; } case JsonToken.String: { string s = (string)Value; return ReadInt32String(s); } default: throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal int? ReadInt32String(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out var result)) { SetToken(JsonToken.Integer, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual string? ReadAsString() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.String: return (string)Value; default: if (JsonTokenUtils.IsPrimitiveToken(contentToken)) { object value = Value; if (value != null) { string text = ((!(value is IFormattable formattable)) ? ((value is Uri uri) ? uri.OriginalString : value.ToString()) : formattable.ToString(null, Culture)); SetToken(JsonToken.String, text, updateIndex: false); return text; } } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } public virtual byte[]? ReadAsBytes() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.StartObject: { ReadIntoWrappedTypeObject(); byte[] array2 = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, array2, updateIndex: false); return array2; } case JsonToken.String: { string text = (string)Value; Guid g; byte[] array3 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray())); SetToken(JsonToken.Bytes, array3, updateIndex: false); return array3; } case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Bytes: if (Value is Guid guid) { byte[] array = guid.ToByteArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); default: throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal byte[] ReadArrayIntoByteArray() { List<byte> list = new List<byte>(); do { if (!Read()) { SetToken(JsonToken.None); } } while (!ReadArrayElementIntoByteArrayReportDone(list)); byte[] array = list.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer) { switch (TokenType) { case JsonToken.None: throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); case JsonToken.Integer: buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); return false; case JsonToken.EndArray: return true; case JsonToken.Comment: return false; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } public virtual double? ReadAsDouble() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is double) { return (double)value; } double num = ((!(value is BigInteger bigInteger)) ? Convert.ToDouble(value, CultureInfo.InvariantCulture) : ((double)bigInteger)); SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDoubleString((string)Value); default: throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal double? ReadDoubleString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual bool? ReadAsBoolean() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { bool flag = ((!(Value is BigInteger bigInteger)) ? Convert.ToBoolean(Value, CultureInfo.InvariantCulture) : (bigInteger != 0L)); SetToken(JsonToken.Boolean, flag, updateIndex: false); return flag; } case JsonToken.String: return ReadBooleanString((string)Value); case JsonToken.Boolean: return (bool)Value; default: throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal bool? ReadBooleanString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (bool.TryParse(s, out var result)) { SetToken(JsonToken.Boolean, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual decimal? ReadAsDecimal() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { object value = Value; if (value is decimal) { return (decimal)value; } decimal num; if (value is BigInteger bigInteger) { num = (decimal)bigInteger; } else { try { num = Convert.ToDecimal(value, CultureInfo.InvariantCulture); } catch (Exception ex) { throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex); } } SetToken(JsonToken.Float, num, updateIndex: false); return num; } case JsonToken.String: return ReadDecimalString((string)Value); default: throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal decimal? ReadDecimalString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out result) == ParseResult.Success) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTime? ReadAsDateTime() { switch (GetContentToken()) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTimeOffset dateTimeOffset) { SetToken(JsonToken.Date, dateTimeOffset.DateTime, updateIndex: false); } return (DateTime)Value; case JsonToken.String: return ReadDateTimeString((string)Value); default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } internal DateTime? ReadDateTimeString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTimeOffset? ReadAsDateTimeOffset() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTime dateTime) { SetToken(JsonToken.Date, new DateTimeOffset(dateTime), updateIndex: false); } return (DateTimeOffset)Value; case JsonToken.String: { string s = (string)Value; return ReadDateTimeOffsetString(s); } default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal DateTimeOffset? ReadDateTimeOffsetString(string? s) { if (StringUtils.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } internal void ReaderReadAndAssert() { if (!Read()) { throw CreateUnexpectedEndException(); } } internal JsonReaderException CreateUnexpectedEndException() { return JsonReaderException.Create(this, "Unexpected end when reading JSON."); } internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); if (Value != null && Value.ToString() == "$type") { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == "$value") { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } public void Skip() { if (TokenType == JsonToken.PropertyName) { Read(); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && depth < Depth) { } } } protected void SetToken(JsonToken newToken) { SetToken(newToken, null, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value) { SetToken(newToken, value, updateIndex: true); } protected void SetToken(JsonToken newToken, object? value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Raw: case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: SetPostValueState(updateIndex); break; case JsonToken.Comment: break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != 0 || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } if (updateIndex) { UpdateScopeWithFinishedValue(); } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void ValidateEnd(JsonToken endToken) { JsonContainerType jsonContainerType = Pop(); if (GetTypeForCloseToken(endToken) != jsonContainerType) { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType)); } if (Peek() != 0 || SupportMultipleContent) { _currentState = State.PostValue; } else { SetFinished(); } } protected void SetStateBasedOnCurrent() { JsonContainerType jsonContainerType = Peek(); switch (jsonContainerType) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType)); } } private void SetFinished() { _currentState = ((!SupportMultipleContent) ? State.Finished : State.Start); } private JsonContainerType GetTypeForCloseToken(JsonToken token) { return token switch { JsonToken.EndObject => JsonContainerType.Object, JsonToken.EndArray => JsonContainerType.Array, JsonToken.EndConstructor => JsonContainerType.Constructor, _ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), }; } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } internal void ReadAndAssert() { if (!Read()) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter) { if (!ReadForType(contract, hasConverter)) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal bool ReadForType(JsonContract? contract, bool hasConverter) { if (hasConverter) { return Read(); } switch (contract?.InternalReadType ?? ReadType.Read) { case ReadType.Read: return ReadAndMoveToContent(); case ReadType.ReadAsInt32: ReadAsInt32(); break; case ReadType.ReadAsInt64: { bool result = ReadAndMoveToContent(); if (TokenType == JsonToken.Undefined) { throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long))); } return result; } case ReadType.ReadAsDecimal: ReadAsDecimal(); break; case ReadType.ReadAsDouble: ReadAsDouble(); break; case ReadType.ReadAsBytes: ReadAsBytes(); break; case ReadType.ReadAsBoolean: ReadAsBoolean(); break; case ReadType.ReadAsString: ReadAsString(); break; case ReadType.ReadAsDateTime: ReadAsDateTime(); break; case ReadType.ReadAsDateTimeOffset: ReadAsDateTimeOffset(); break; default: throw new ArgumentOutOfRangeException(); } return TokenType != JsonToken.None; } internal bool ReadAndMoveToContent() { if (Read()) { return MoveToContent(); } return false; } internal bool MoveToContent() { JsonToken tokenType = TokenType; while (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { if (!Read()) { return false; } tokenType = TokenType; } return true; } private JsonToken GetContentToken() { JsonToken tokenType; do { if (!Read()) { SetToken(JsonToken.None); return JsonToken.None; } tokenType = TokenType; } while (tokenType == JsonToken.Comment); return tokenType; } } [Serializable] public class JsonReaderException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonReaderException() { } public JsonReaderException(string message) : base(message) { } public JsonReaderException(string message, Exception innerException) : base(message, innerException) { } public JsonReaderException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonReaderException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonReaderException(message, path, lineNumber, linePosition, ex); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonRequiredAttribute : Attribute { } [Serializable] public class JsonSerializationException : JsonException { public int LineNumber { get; } public int LinePosition { get; } public string? Path { get; } public JsonSerializationException() { } public JsonSerializationException(string message) : base(message) { } public JsonSerializationException(string message, Exception innerException) : base(message, innerException) { } public JsonSerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonSerializationException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonSerializationException(message, path, lineNumber, linePosition, ex); } } public class JsonSerializer { internal TypeNameHandling _typeNameHandling; internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; internal JsonConverterCollection? _converters; internal IContractResolver _contractResolver; internal ITraceWriter? _traceWriter; internal IEqualityComparer? _equalityComparer; internal ISerializationBinder _serializationBinder; internal StreamingContext _context; private IReferenceResolver? _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string? _dateFormatString; private bool _dateFormatStringSet; public virtual IReferenceResolver? ReferenceResolver { get { return GetReferenceResolver(); } set { if (value == null) { throw new ArgumentNullException("value", "Reference resolver cannot be null."); } _referenceResolver = value; } } [Obsolete("Binder is obsolete. Use SerializationBinder instead.")] public virtual SerializationBinder Binder { get { if (_serializationBinder is SerializationBinder result) { return result; } if (_serializationBinder is SerializationBinderAdapter serializationBinderAdapter) { return serializationBinderAdapter.SerializationBinder; } throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set."); } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = (value as ISerializationBinder) ?? new SerializationBinderAdapter(value); } } public virtual ISerializationBinder SerializationBinder { get { return _serializationBinder; } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _serializationBinder = value; } } public virtual ITraceWriter? TraceWriter { get { return _traceWriter; } set { _traceWriter = value; } } public virtual IEqualityComparer? EqualityComparer { get { return _equalityComparer; } set { _equalityComparer = value; } } public virtual TypeNameHandling TypeNameHandling { get { return _typeNameHandling; } set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) { throw new ArgumentOutOfRangeException("value"); } _typeNameHandling = value; } } [Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")] public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get { return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling; } set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value; } } public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling { get { return _typeNameAssemblyFormatHandling; } set { if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormatHandling = value; } } public virtual PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling; } set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) { throw new ArgumentOutOfRangeException("value"); } _preserveReferencesHandling = value; } } public virtual ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) { throw new ArgumentOutOfRangeException("value"); } _referenceLoopHandling = value; } } public virtual MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) { throw new ArgumentOutOfRangeException("value"); } _missingMemberHandling = value; } } public virtual NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _nullValueHandling = value; } } public virtual DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) { throw new ArgumentOutOfRangeException("value"); } _defaultValueHandling = value; } } public virtual ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) { throw new ArgumentOutOfRangeException("value"); } _objectCreationHandling = value; } } public virtual ConstructorHandling ConstructorHandling { get { return _constructorHandling; } set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) { throw new ArgumentOutOfRangeException("value"); } _constructorHandling = value; } } public virtual MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling; } set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _metadataPropertyHandling = value; } } public virtual JsonConverterCollection Converters { get { if (_converters == null) { _converters = new JsonConverterCollection(); } return _converters; } } public virtual IContractResolver ContractResolver { get { return _contractResolver; } set { _contractResolver = value ?? DefaultContractResolver.Instance; } } public virtual StreamingContext Context { get { return _context; } set { _context = value; } } public virtual Formatting Formatting { get { return _formatting.GetValueOrDefault(); } set { _formatting = value; } } public virtual DateFormatHandling DateFormatHandling { get { return _dateFormatHandling.GetValueOrDefault(); } set { _dateFormatHandling = value; } } public virtual DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind; } set { _dateTimeZoneHandling = value; } } public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling ?? DateParseHandling.DateTime; } set { _dateParseHandling = value; } } public virtual FloatParseHandling FloatParseHandling { get { return _floatParseHandling.GetValueOrDefault(); } set { _floatParseHandling = value; } } public virtual FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling.GetValueOrDefault(); } set { _floatFormatHandling = value; } } public virtual StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling.GetValueOrDefault(); } set { _stringEscapeHandling = value; } } public virtual string DateFormatString { get { return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; } set { _dateFormatString = value; _dateFormatStringSet = true; } } public virtual CultureInfo Culture { get { return _culture ?? JsonSerializerSettings.DefaultCulture; } set { _culture = value; } } public virtual int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; _maxDepthSet = true; } } public virtual bool CheckAdditionalContent { get { return _checkAdditionalContent.GetValueOrDefault(); } set { _checkAdditionalContent = value; } } public virtual event EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>? Error; internal bool IsCheckAdditionalContentSet() { return _checkAdditionalContent.HasValue; } public JsonSerializer() { _referenceLoopHandling = ReferenceLoopHandling.Error; _missingMemberHandling = MissingMemberHandling.Ignore; _nullValueHandling = NullValueHandling.Include; _defaultValueHandling = DefaultValueHandling.Include; _objectCreationHandling = ObjectCreationHandling.Auto; _preserveReferencesHandling = PreserveReferencesHandling.None; _constructorHandling = ConstructorHandling.Default; _typeNameHandling = TypeNameHandling.None; _metadataPropertyHandling = MetadataPropertyHandling.Default; _context = JsonSerializerSettings.DefaultContext; _serializationBinder = DefaultSerializationBinder.Instance; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } public static JsonSerializer Create() { return new JsonSerializer(); } public static JsonSerializer Create(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = Create(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } public static JsonSerializer CreateDefault() { return Create(JsonConvert.DefaultSettings?.Invoke()); } public static JsonSerializer CreateDefault(JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = CreateDefault(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } if (settings._typeNameHandling.HasValue) { serializer.TypeNameHandling = settings.TypeNameHandling; } if (settings._metadataPropertyHandling.HasValue) { serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; } if (settings._typeNameAssemblyFormatHandling.HasValue) { serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling; } if (settings._preserveReferencesHandling.HasValue) { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; } if (settings._referenceLoopHandling.HasValue) { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; } if (settings._missingMemberHandling.HasValue) { serializer.MissingMemberHandling = settings.MissingMemberHandling; } if (settings._objectCreationHandling.HasValue) { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; } if (settings._nullValueHandling.HasValue) { serializer.NullValueHandling = settings.NullValueHandling; } if (settings._defaultValueHandling.HasValue) { serializer.DefaultValueHandling = settings.DefaultValueHandling; } if (settings._constructorHandling.HasValue) { serializer.ConstructorHandling = settings.ConstructorHandling; } if (settings._context.HasValue) { serializer.Context = settings.Context; } if (settings._checkAdditionalContent.HasValue) { serializer._checkAdditionalContent = settings._checkAdditionalContent; } if (settings.Error != null) { serializer.Error += settings.Error; } if (settings.ContractResolver != null) { serializer.ContractResolver = settings.ContractResolver; } if (settings.ReferenceResolverProvider != null) { serializer.ReferenceResolver = settings.ReferenceResolverProvider(); } if (settings.TraceWriter != null) { serializer.TraceWriter = settings.TraceWriter; } if (settings.EqualityComparer != null) { serializer.EqualityComparer = settings.EqualityComparer; } if (settings.SerializationBinder != null) { serializer.SerializationBinder = settings.SerializationBinder; } if (settings._formatting.HasValue) { serializer._formatting = settings._formatting; } if (settings._dateFormatHandling.HasValue) { serializer._dateFormatHandling = settings._dateFormatHandling; } if (settings._dateTimeZoneHandling.HasValue) { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; } if (settings._dateParseHandling.HasValue) { serializer._dateParseHandling = settings._dateParseHandling; } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling.HasValue) { serializer._floatFormatHandling = settings._floatFormatHandling; } if (settings._floatParseHandling.HasValue) { serializer._floatParseHandling = settings._floatParseHandling; } if (settings._stringEscapeHandling.HasValue) { serializer._stringEscapeHandling = settings._stringEscapeHandling; } if (settings._culture != null) { serializer._culture = settings._culture; } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } } [DebuggerStepThrough] public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } [DebuggerStepThrough] public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, "reader"); ValidationUtils.ArgumentNotNull(target, "target"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader) { return Deserialize(reader, null); } [DebuggerStepThrough] public object? Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } [DebuggerStepThrough] public T? Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } [DebuggerStepThrough] public object? Deserialize(JsonReader reader, Type? objectType) { return DeserializeInternal(reader, objectType); } internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType) { ValidationUtils.ArgumentNotNull(reader, "reader"); SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null); object? result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); return result; } internal void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString) { if (_culture != null && !_culture.Equals(reader.Culture)) { previousCulture = reader.Culture; reader.Culture = _culture; } else { previousCulture = null; } if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } else { previousDateTimeZoneHandling = null; } if (_dateParseHandling.HasValue && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.GetValueOrDefault(); } else { previousDateParseHandling = null; } if (_floatParseHandling.HasValue && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault(); } else { previousFloatParseHandling = null; } if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } else { previousMaxDepth = null; } if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) { previousDateFormatString = reader.DateFormatString; reader.DateFormatString = _dateFormatString; } else { previousDateFormatString = null; } if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable == null && _contractResolver is DefaultContractResolver defaultContractResolver) { jsonTextReader.PropertyNameTable = defaultContractResolver.GetNameTable(); } } private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString) { if (previousCulture != null) { reader.Culture = previousCulture; } if (previousDateTimeZoneHandling.HasValue) { reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousDateParseHandling.HasValue) { reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault(); } if (previousFloatParseHandling.HasValue) { reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault(); } if (_maxDepthSet) { reader.MaxDepth = previousMaxDepth; } if (_dateFormatStringSet) { reader.DateFormatString = previousDateFormatString; } if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable != null && _contractResolver is DefaultContractResolver defaultContractResolver && jsonTextReader.PropertyNameTable == defaultContractResolver.GetNameTable()) { jsonTextReader.PropertyNameTable = null; } } public void Serialize(TextWriter textWriter, object? value) { Serialize(new JsonTextWriter(textWriter), value); } public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType) { SerializeInternal(jsonWriter, value, objectType); } public void Serialize(TextWriter textWriter, object? value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } public void Serialize(JsonWriter jsonWriter, object? value) { SerializeInternal(jsonWriter, value, null); } private TraceJsonReader CreateTraceJsonReader(JsonReader reader) { TraceJsonReader traceJsonReader = new TraceJsonReader(reader); if (reader.TokenType != 0) { traceJsonReader.WriteCurrentToken(); } return traceJsonReader; } internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter"); Formatting? formatting = null; if (_formatting.HasValue && jsonWriter.Formatting != _formatting) { formatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.GetValueOrDefault(); } DateFormatHandling? dateFormatHandling = null; if (_dateFormatHandling.HasValue && jsonWriter.DateFormatHandling != _dateFormatHandling) { dateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault(); } DateTimeZoneHandling? dateTimeZoneHandling = null; if (_dateTimeZoneHandling.HasValue && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) { dateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } FloatFormatHandling? floatFormatHandling = null; if (_floatFormatHandling.HasValue && jsonWriter.FloatFormatHandling != _floatFormatHandling) { floatFormatHandling = jsonWriter.FloatFormatHandling; jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault(); } StringEscapeHandling? stringEscapeHandling = null; if (_stringEscapeHandling.HasValue && jsonWriter.StringEscapeHandling != _stringEscapeHandling) { stringEscapeHandling = jsonWriter.StringEscapeHandling; jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); } CultureInfo cultureInfo = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { cultureInfo = jsonWriter.Culture; jsonWriter.Culture = _culture; } string dateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { dateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } TraceJsonWriter traceJsonWriter = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null); new JsonSerializerInternalWriter(this).Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); } if (formatting.HasValue) { jsonWriter.Formatting = formatting.GetValueOrDefault(); } if (dateFormatHandling.HasValue) { jsonWriter.DateFormatHandling = dateFormatHandling.GetValueOrDefault(); } if (dateTimeZoneHandling.HasValue) { jsonWriter.DateTimeZoneHandling = dateTimeZoneHandling.GetValueOrDefault(); } if (floatFormatHandling.HasValue) { jsonWriter.FloatFormatHandling = floatFormatHandling.GetValueOrDefault(); } if (stringEscapeHandling.HasValue) { jsonWriter.StringEscapeHandling = stringEscapeHandling.GetValueOrDefault(); } if (_dateFormatStringSet) { jsonWriter.DateFormatString = dateFormatString; } if (cultureInfo != null) { jsonWriter.Culture = cultureInfo; } } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) { _referenceResolver = new DefaultReferenceResolver(); } return _referenceResolver; } internal JsonConverter? GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } internal static JsonConverter? GetMatchingConverter(IList<JsonConverter>? converters, Type objectType) { if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter jsonConverter = converters[i]; if (jsonConverter.CanConvert(objectType)) { return jsonConverter; } } } return null; } internal void OnError(Newtonsoft.Json.Serialization.ErrorEventArgs e) { this.Error?.Invoke(this, e); } } public class JsonSerializerSettings { internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error; internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore; internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include; internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include; internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto; internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None; internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default; internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None; internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default; internal static readonly StreamingContext DefaultContext; internal const Formatting DefaultFormatting = Formatting.None; internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat; internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime; internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double; internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String; internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default; internal const TypeNameAssemblyFormatHandling DefaultTypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple; internal static readonly CultureInfo DefaultCulture; internal const bool DefaultCheckAdditionalContent = false; internal const string DefaultDateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; internal const int DefaultMaxDepth = 64; internal Formatting? _formatting; internal DateFormatHandling? _dateFormatHandling; internal DateTimeZoneHandling? _dateTimeZoneHandling; internal DateParseHandling? _dateParseHandling; internal FloatFormatHandling? _floatFormatHandling; internal FloatParseHandling? _floatParseHandling; internal StringEscapeHandling? _stringEscapeHandling; internal CultureInfo? _culture; internal bool? _checkAdditionalContent; internal int? _maxDepth; internal bool _maxDepthSet; internal string? _dateFormatString; internal bool _dateFormatStringSet; internal TypeNameAssemblyFormatHandling? _typeNameAssemblyFormatHandling; internal DefaultValueHandling? _defaultValueHandling; internal PreserveReferencesHandling? _preserveReferencesHandling; internal NullValueHandling? _nullValueHandling; internal ObjectCreationHandling? _objectCreationHandling; internal MissingMemberHandling? _missingMemberHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal StreamingContext? _context; internal ConstructorHandling? _constructorHandling; internal TypeNameHandling? _typeNameHandling; internal MetadataPropertyHandling? _metadataPropertyHandling; public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling.GetValueOrDefault(); } set { _referenceLoopHandling = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling.GetValueOrDefault(); } set { _missingMemberHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling.GetValueOrDefault(); } set { _objectCreationHandling = value; } } public NullValueHandling NullValueHandling { get { return _nullValueHandling.GetValueOrDefault(); } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling.GetValueOrDefault(); } set { _defaultValueHandling = value; } } public IList<JsonConverter> Converters { get; set; } public PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling.GetValueOrDef
plugins\ServerSync.dll
Decompiled 2 weeks agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; 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.Versioning; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("ServerSync")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ServerSync")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("E16C3332-50B4-4DA6-9E8A-A590C4E5CD49")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ServerSync { [PublicAPI] public abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] public class SyncedConfigEntry<T> : OwnConfigEntryBase { public readonly ConfigEntry<T> SourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public SyncedConfigEntry(ConfigEntry<T> sourceConfig) { SourceConfig = sourceConfig; base..ctor(); } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } public abstract class CustomSyncedValueBase { public object? LocalBaseValue; public readonly string Identifier; public readonly Type Type; private object? boxedValue; protected bool localIsOwner; public readonly int Priority; public object? BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action? ValueChanged; protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [PublicAPI] public sealed class CustomSyncedValue<T> : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [PublicAPI] public class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { public static ZRpc? currentRpc; [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List<ZNetPeer> peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List<string> CurrentList = new List<string>(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List<string>(adminList.GetList()); List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>(); public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished = false; public volatile int versionMatchQueued = -1; public readonly List<ZPackage> Package = new List<ZPackage>(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFabSocket)this)..ctor(); } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend > 0) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); object? value = fieldInfo.GetValue(val); ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null); if (val2 != null) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId); } fieldInfo.SetValue(val, bufferingSocket); } if (__state == null) { __state = new Dictionary<Assembly, BufferingSocket>(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc) { ZRpc rpc2 = rpc; ZNet __instance2 = __instance; Dictionary<Assembly, BufferingSocket> __state2 = __state; ZNetPeer peer; if (__instance2.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance2).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc2.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state2[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List<PackageEntry> entries = new List<PackageEntry>(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc2.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; public object? value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } private class InvalidDeserializationTypeException : Exception { public string expected = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet<ConfigSync> configSyncs; private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>(); private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>(); private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag.GetValueOrDefault(); } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0053: return (byte)result != 0; IL_0052: result = 0; goto IL_0053; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action<bool>? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet<ConfigSync>(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry) { ConfigEntry<T> configEntry2 = configEntry; OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2); SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry<T>(configEntry2); AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray()); configEntry2.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry<T>(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry<T>)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { CustomSyncedValueBase customValue2 = customValue; if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue2); allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue2.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue2); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2u) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value)) { value = new SortedDictionary<int, byte[]>(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4u) != 0) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; val2.Save(); } foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int i = 0; i < num; i++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected)); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown"))); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName)); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match.")); } continue; } Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs")); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { OwnConfigEntryBase config2 = config; ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (val == null) { val = item.BaseConfig.ConfigFile; saveOnConfigSet = val.SaveOnConfigSet; val.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (val != null) { val.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZNetPeer peer2 = peer; ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer2.m_socket.IsConnected()) { ZPackage fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer2.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg }); } } IEnumerable<bool> waitForQueue() { float timeout = Time.time + 30f; while (peer2.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout"); peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer2); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty<object>().GetEnumerator(); } List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package) { ZPackage package2 = package; if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package2.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package2 = compressedPackage; } List<IEnumerator<bool>> writers = (from peer in peers where peer.IsReady() select peer into p select distributeConfigToPeers(p, package2)).ToList(); writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private static OwnConfigEntryBase? configData(ConfigEntryBase config) { return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault(); } public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config) { return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault(); } private static T configAttribute<T>(ConfigEntryBase config) { return config.Description.Tags.OfType<T>().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>(); List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>()) { AddEntryToPackage(val, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(val, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(val, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return val; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, object? value) { Type type = value?.GetType(); if (value is Enum) { value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture); } else { if (value is ICollection collection) { package.Write(collection.Count); { foreach (object item in collection) { AddValueToZPackage(package, item); } return; } } if ((object)type != null && type.IsValueType && !type.IsPrimitive) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); package.Write(fields.Length); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { package.Write(GetZPackageTypeString(fieldInfo.FieldType)); AddValueToZPackage(package, fieldInfo.GetValue(value)); } return; } } ZRpc.Serialize(new object[1] { value }, ref package); } private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type) { if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); int num = package.ReadInt(); if (num != fields.Length) { throw new InvalidDeserializationTypeException { received = $"(field count: {num})", expected = $"(field count: {fields.Length})" }; } object uninitializedObject = FormatterServices.GetUninitializedObject(type); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { string text = package.ReadString(); if (text != GetZPackageTypeString(fieldInfo.FieldType)) { throw new InvalidDeserializationTypeException { received = text, expected = GetZPackageTypeString(fieldInfo.FieldType), field = fieldInfo.Name }; } fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType)); } return uninitializedObject; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { int num2 = package.ReadInt(); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type); Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments); FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic); for (int j = 0; j < num2; j++) { object obj = ReadValueWithTypeFromZPackage(package, type2); dictionary.Add(field.GetValue(obj), field2.GetValue(obj)); } return dictionary; } if (type != typeof(List<string>) && type.IsGenericType) { Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]); if ((object)type3 != null && type3.IsAssignableFrom(type)) { int num3 = package.ReadInt(); object obj2 = Activator.CreateInstance(type); MethodInfo method = type3.GetMethod("Add"); for (int k = 0; k < num3; k++) { method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) }); } return obj2; } } ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo)); AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type); List<object> source = new List<object>(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [PublicAPI] [HarmonyPatch] public class VersionCheck { private static readonly HashSet<VersionCheck> versionChecks; private static readonly Dictionary<string, string> notProcessedNames; public string Name; private string? displayName; private string? currentVersion; private string? minimumRequiredVersion; public bool ModRequired = true; private string? ReceivedCurrentVersion; private string? ReceivedMinimumRequiredVersion; private readonly List<ZRpc> ValidatedClients = new List<ZRpc>(); private ConfigSync? ConfigSync; public string DisplayName { get { return displayName ?? Name; } set { displayName = value; } } public string CurrentVersion { get { return currentVersion ?? "0.0.0"; } set { currentVersion = value; } } public string MinimumRequiredVersion { get { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null)); if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony val = new Harmony("org.bepinex.helpers.ServerSync"); foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) }) where t.IsClass select t) { val.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet<VersionCheck>(); notProcessedNames = new Dictionary<string, string>(); typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1] { new Action(PatchServerSync) }); } public VersionCheck(string name) { Name = name; ModRequired = true; versionChecks.Add(this); } public VersionCheck(ConfigSync configSync) { ConfigSync = configSync; Name = ConfigSync.Name; versionChecks.Add(this); } public void Initialize() { ReceivedCurrentVersion = null; ReceivedMinimumRequiredVersion = null; if (ConfigSync != null) { Name = ConfigSync.Name; DisplayName = ConfigSync.DisplayName; CurrentVersion = ConfigSync.CurrentVersion; MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion; ModRequired = ConfigSync.ModRequired; } } private bool IsVersionOk() { if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null) { return !ModRequired; } bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion); bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + "."); } private string ErrorServer(ZRpc rpc) { return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion; } private string Error(ZRpc? rpc = null) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { ZRpc rpc2 = rpc; return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc2)).ToArray(); } private static void Logout() { Game.instance.Logout(true, true); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", new object[1] { 3 }); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action<ZRpc, ZPackage>? original) { string text = pkg.ReadString(); string text2 = pkg.ReadString(); string text3 = pkg.ReadString(); bool flag = false; foreach (VersionCheck versionCheck in versionChecks) { if (!(text != versionCheck.Name)) { Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + ".")); versionCheck.ReceivedMinimumRequiredVersion = text2; versionCheck.ReceivedCurrentVersion = text3; if (ZNet.instance.IsServer() && versionCheck.IsVersionOk()) { versionCheck.ValidatedClients.Add(rpc); } flag = true; } } if (flag) { return; } pkg.SetPos(0); if (original != null) { original(rpc, pkg); if (pkg.GetPos() == 0) { notProcessedNames.Add(text, text3); } } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Expected O, but got Unknown notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck"))) { object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")]; Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + ".")); ZPackage val = new ZPackage(); val.Write(versionCheck.Name); val.Write(versionCheck.MinimumRequiredVersion); val.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val }); } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] [HarmonyPrefix] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] [HarmonyPostfix] private static void ShowConnectionError(FejdStartup __instance) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3) { return; } bool flag = false; VersionCheck[] failedClient = GetFailedClient(); if (failedClient.Length != 0) { string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error())); TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + text; flag = true; } foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> kv) => kv.Key)) { if (!__instance.m_connectionFailedError.text.Contains(item.Key)) { TMP_Text connectionFailedError2 = __instance.m_connectionFailedError; connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed."; flag = true; } } if (flag) { RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent<RectTransform>(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; __instance.m_connectionFailedError.ForceMeshUpdate(false, false); float num = __instance.m_connectionFailedError.renderedHeight + 105f; RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent<RectTransform>(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } }
plugins\Zolantris.Shared.dll
Decompiled 2 weeks agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using ServerSync; using UnityEngine; using UnityEngine.Rendering; using Zolantris.Shared.Interfaces; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace GenericConfigUtil { public enum ConfigRole { User, Advanced, Admin } public sealed class ConfigMeta { public bool IsAdvanced { get; set; } public bool IsAdmin { get; set; } public string Category { get; set; } public string Tooltip { get; set; } public int? Order { get; set; } public bool? ReadOnly { get; set; } public bool? Hidden { get; set; } public Func<bool> IsVisibleWhen { get; set; } public Func<bool> IsReadOnlyWhen { get; set; } } public sealed class ConfigRegistry { [CompilerGenerated] private sealed class <VisibleEntries>d__14 : IEnumerable<ConfigEntryBase>, IEnumerable, IEnumerator<ConfigEntryBase>, IEnumerator, IDisposable { private int <>1__state; private ConfigEntryBase <>2__current; private int <>l__initialThreadId; public ConfigRegistry <>4__this; private IEnumerator<KeyValuePair<ConfigDefinition, ConfigEntryBase>> <>7__wrap1; ConfigEntryBase IEnumerator<ConfigEntryBase>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <VisibleEntries>d__14(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; ConfigRegistry configRegistry = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = configRegistry._config.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } while (<>7__wrap1.MoveNext()) { ConfigEntryBase value = <>7__wrap1.Current.Value; if (configRegistry.IsVisible(value.Definition)) { <>2__current = value; <>1__state = 1; return true; } } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator<ConfigEntryBase> IEnumerable<ConfigEntryBase>.GetEnumerator() { <VisibleEntries>d__14 result; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; result = this; } else { result = new <VisibleEntries>d__14(0) { <>4__this = <>4__this }; } return result; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<ConfigEntryBase>)this).GetEnumerator(); } } private readonly ConfigFile _config; private readonly Dictionary<ConfigDefinition, ConfigMeta> _metaByDef = new Dictionary<ConfigDefinition, ConfigMeta>(); private readonly Type _cmAttrType; private readonly string[] _cmCommonPropNames = new string[12] { "Category", "Order", "ReadOnly", "Browsable", "IsAdvanced", "Tooltip", "Description", "DispName", "HideDefaultButton", "HideSettingName", "DefaultValue", "ShowRangeAsPercent" }; public ConfigRole CurrentRole { get; set; } public ConfigRegistry(ConfigFile config) { if (config == null) { throw new ArgumentNullException("config"); } _config = config; _cmAttrType = FindConfigurationManagerAttributesType(); } public ConfigEntry<T> CreateEntry<T>(string section, string key, T defaultValue, string description = null, ConfigMeta meta = null, AcceptableValueBase acceptableValues = null) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown ConfigDefinition val = new ConfigDefinition(section, key); object cmAttr = BuildConfigurationManagerAttributes(meta); object[] array = BuildTags(meta, cmAttr); ConfigDescription val2 = ((acceptableValues == null) ? new ConfigDescription(description ?? string.Empty, (AcceptableValueBase)null, array) : new ConfigDescription(description ?? string.Empty, acceptableValues, array)); ConfigEntry<T> val3 = _config.Bind<T>(val, defaultValue, val2); if (meta != null) { _metaByDef[val] = meta; } AttachRoleGuard<T>(val3, meta); return val3; } public ConfigEntry<T> CreateAdvanced<T>(string section, string key, T defaultValue, string description = null, AcceptableValueBase acceptableValues = null, string category = null, int? order = null) { ConfigMeta meta = new ConfigMeta { IsAdvanced = true, Category = category, Order = order }; return CreateEntry(section, key, defaultValue, description, meta, acceptableValues); } public ConfigEntry<T> CreateAdmin<T>(string section, string key, T defaultValue, string description = null, AcceptableValueBase acceptableValues = null, string category = null, int? order = null, bool lockReadOnly = true) { ConfigMeta meta = new ConfigMeta { IsAdmin = true, Category = category, Order = order, ReadOnly = lockReadOnly }; return CreateEntry(section, key, defaultValue, description, meta, acceptableValues); } public bool IsVisible(ConfigDefinition def) { if (!_metaByDef.TryGetValue(def, out ConfigMeta value)) { return true; } if (value.Hidden.GetValueOrDefault()) { return false; } if (value.IsAdmin && CurrentRole < ConfigRole.Admin) { return false; } if (value.IsAdvanced && CurrentRole < ConfigRole.Advanced) { return false; } if (value.IsVisibleWhen != null && !value.IsVisibleWhen()) { return false; } return true; } public bool IsEditable(ConfigDefinition def) { if (!_metaByDef.TryGetValue(def, out ConfigMeta value)) { return true; } if (value.IsAdmin && CurrentRole < ConfigRole.Admin) { return false; } if (value.ReadOnly.GetValueOrDefault()) { return false; } if (value.IsReadOnlyWhen != null && value.IsReadOnlyWhen()) { return false; } return true; } [IteratorStateMachine(typeof(<VisibleEntries>d__14))] public IEnumerable<ConfigEntryBase> VisibleEntries() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <VisibleEntries>d__14(-2) { <>4__this = this }; } public void RefreshUiAttributes() { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown if (_cmAttrType == null) { return; } foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in _config) { ConfigEntryBase value = item.Value; ConfigDescription description = value.Description; _metaByDef.TryGetValue(value.Definition, out ConfigMeta value2); object cmAttr = BuildConfigurationManagerAttributes(value2); object[] array = BuildTags(value2, cmAttr); ConfigDescription value3 = new ConfigDescription(description.Description, description.AcceptableValues, array); PropertyInfo property = typeof(ConfigEntryBase).GetProperty("Description", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property != null) { property.SetValue(value, value3, null); } } } private void AttachRoleGuard<T>(ConfigEntry<T> entry, ConfigMeta meta) { ConfigEntry<T> entry2 = entry; if (meta == null) { return; } entry2.SettingChanged += delegate { if (!IsEditable(((ConfigEntryBase)entry2).Definition)) { _config.Reload(); } }; } private object[] BuildTags(ConfigMeta meta, object cmAttr) { if (meta == null && cmAttr == null) { return new object[0]; } if (meta != null && cmAttr != null) { return new object[2] { meta, cmAttr }; } if (meta != null) { return new object[1] { meta }; } return new object[1] { cmAttr }; } private object BuildConfigurationManagerAttributes(ConfigMeta meta) { if (_cmAttrType == null) { return null; } object attr = Activator.CreateInstance(_cmAttrType); if (attr == null) { return null; } Action<string, object> setter = delegate(string name, object value) { PropertyInfo property = _cmAttrType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public); if (property != null) { property.SetValue(attr, value, null); } }; if (meta != null) { if (!string.IsNullOrEmpty(meta.Category)) { SetSafe(setter, "Category", meta.Category); } if (meta.Order.HasValue) { SetSafe(setter, "Order", meta.Order.Value); } if (meta.ReadOnly.HasValue) { SetSafe(setter, "ReadOnly", meta.ReadOnly.Value); } ConfigRole currentRole = CurrentRole; bool flag = (!meta.IsAdmin || currentRole >= ConfigRole.Admin) && (!meta.IsAdvanced || currentRole >= ConfigRole.Advanced); if (meta.Hidden.GetValueOrDefault() || !flag || (meta.IsVisibleWhen != null && !meta.IsVisibleWhen())) { SetSafe(setter, "Browsable", false); } if (meta.IsAdvanced) { SetSafe(setter, "IsAdvanced", true); } if (!string.IsNullOrEmpty(meta.Tooltip)) { SetSafe(setter, "Tooltip", meta.Tooltip); } } return attr; } private void SetSafe(Action<string, object> setter, string name, object value) { if (_cmAttrType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public) != null) { setter(name, value); } } private static Type FindConfigurationManagerAttributesType() { string[] array = new string[3] { "ConfigurationManager.Attributes.ConfigurationManagerAttributes, ConfigurationManager", "ConfigurationManager.ConfigurationManagerAttributes, ConfigurationManager", "ConfigurationManager.ConfigurationManagerAttributes, BepInEx.ConfigurationManager" }; for (int i = 0; i < array.Length; i++) { Type type = Type.GetType(array[i], throwOnError: false); if (type != null) { return type; } } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { try { Type type2 = assembly.GetTypes().FirstOrDefault((Type x) => x.Name == "ConfigurationManagerAttributes"); if (type2 != null && type2.IsClass && !type2.IsAbstract) { return type2; } } catch { } } return null; } } } namespace Shared.Interfaces { public interface PluginInfo { string Name { get; } string Version { get; } string Guid { get; } } } namespace Zolantris.Shared { public interface IBepInExBaseConfig { void OnBindConfig(ConfigFile config); } public class BepInExBaseConfig<TSelf> : IBepInExBaseConfig where TSelf : BepInExBaseConfig<TSelf>, new() { private static readonly TSelf Instance = new TSelf(); public static bool ShouldSkipSyncOnBind = false; public static void BindConfig(ConfigFile config, ConfigSync configSync) { Instance.OnBindConfig(config); ClassValidator.ValidateRequiredNonNullFields<TSelf>(); if (!ShouldSkipSyncOnBind) { ServerSyncConfigSyncUtil.RegisterAllConfigEntries(configSync, typeof(TSelf)); } ShouldSkipSyncOnBind = false; } public virtual void OnBindConfig(ConfigFile config) { LoggerProvider.LogError("No implementation of OnBindConfig in parent class " + typeof(TSelf).FullName, "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared.Config\\BepInExBaseConfig.cs", 44); } } public static class BepInExConfigUtils { public sealed class BepInExConfigSettings { internal class UiMetaTag { public bool IsAdmin; public bool IsAdvanced; public string Category; public int? Order; public bool? ReadOnly; public bool? Hidden; public string Tooltip; public bool Synchronized; } public AcceptableValueBase AcceptableValues { get; set; } public bool Synchronize { get; set; } public bool IsAdmin { get; set; } public bool IsAdvanced { get; set; } public string Category { get; set; } public int? Order { get; set; } public bool? ReadOnly { get; set; } public bool? Hidden { get; set; } public string Tooltip { get; set; } } public interface IConfigSyncAdapter { void Register<T>(ConfigEntry<T> entry, bool adminLock, bool synchronize); } private static readonly HashSet<string> BoundKeys = new HashSet<string>(); private static void EnsureUniqueKey(string section, string key, string file, int line) { string text = section + "." + key; if (!BoundKeys.Add(text)) { throw new InvalidOperationException($"[BepInExConfigUtils] Duplicate config key: '{text}'\n - Source: {file}:{line}"); } } public static ConfigEntry<string> BindJson<T>(this ConfigFile config, string section, string key, T defaultValue, string description = "") { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown string text = JsonConvert.SerializeObject((object)defaultValue, (Formatting)0); return config.Bind<string>(section, key, text, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())); } public static T ReadJson<T>(this ConfigEntry<string> entry) { return JsonConvert.DeserializeObject<T>(entry.Value); } public static void WriteJson<T>(this ConfigEntry<string> entry, T value) { entry.Value = JsonConvert.SerializeObject((object)value, (Formatting)0); } public static ConfigEntry<T> BindUnique<T>(this ConfigFile config, string section, string key, T defaultValue, ConfigDescription desc, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { EnsureUniqueKey(section, key, file, line); return config.Bind<T>(section, key, defaultValue, desc); } public static ConfigEntry<bool> BindUnique(this ConfigFile config, string section, string key, bool defaultValue, string description, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown EnsureUniqueKey(section, key, file, line); return config.Bind<bool>(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())); } public static ConfigEntry<int> BindUnique(this ConfigFile config, string section, string key, int defaultValue, string description, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown EnsureUniqueKey(section, key, file, line); return config.Bind<int>(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())); } public static ConfigEntry<float> BindUnique(this ConfigFile config, string section, string key, float defaultValue, string description, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown EnsureUniqueKey(section, key, file, line); return config.Bind<float>(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())); } public static ConfigEntry<string> BindUnique(this ConfigFile config, string section, string key, string defaultValue, string description, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown EnsureUniqueKey(section, key, file, line); return config.Bind<string>(section, key, defaultValue, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>())); } public static ConfigEntry<T> BindUnique<T>(this ConfigFile config, string section, string key, T defaultValue, string description, BepInExConfigSettings settings, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { EnsureUniqueKey(section, key, file, line); ConfigDescription val = BuildDescription(description, settings); return config.Bind<T>(section, key, defaultValue, val); } public static ConfigEntry<T> BindUniqueWithSync<T>(this ConfigFile config, string section, string key, T defaultValue, string description, BepInExConfigSettings settings, IConfigSyncAdapter sync, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { ConfigEntry<T> val = config.BindUnique(section, key, defaultValue, description, settings, file, line); sync?.Register<T>(val, settings.IsAdmin, settings.Synchronize); return val; } private static ConfigDescription BuildDescription(string description, BepInExConfigSettings s) { //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown BepInExConfigSettings.UiMetaTag uiMetaTag = new BepInExConfigSettings.UiMetaTag { IsAdmin = s.IsAdmin, IsAdvanced = s.IsAdvanced, Category = s.Category, Order = s.Order, ReadOnly = s.ReadOnly, Hidden = s.Hidden, Tooltip = s.Tooltip, Synchronized = s.Synchronize }; object obj = BuildConfigurationManagerAttributes(FindConfigurationManagerAttributesType(), uiMetaTag); object[] array = ((obj == null) ? new object[1] { uiMetaTag } : new object[2] { uiMetaTag, obj }); return new ConfigDescription(description ?? string.Empty, s.AcceptableValues, array); } private static Type FindConfigurationManagerAttributesType() { string[] array = new string[3] { "ConfigurationManager.Attributes.ConfigurationManagerAttributes, ConfigurationManager", "ConfigurationManager.ConfigurationManagerAttributes, ConfigurationManager", "ConfigurationManager.ConfigurationManagerAttributes, BepInEx.ConfigurationManager" }; for (int i = 0; i < array.Length; i++) { Type type = Type.GetType(array[i], throwOnError: false); if (type != null) { return type; } } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { try { Type type2 = assembly.GetTypes().FirstOrDefault((Type x) => x.Name == "ConfigurationManagerAttributes"); if (type2 != null && !type2.IsAbstract) { return type2; } } catch { } } return null; } private static object BuildConfigurationManagerAttributes(Type cmAttrType, BepInExConfigSettings.UiMetaTag meta) { Type cmAttrType2 = cmAttrType; if (cmAttrType2 == null) { return null; } object attr = Activator.CreateInstance(cmAttrType2); if (attr == null) { return null; } if (!string.IsNullOrEmpty(meta.Category)) { Set("Category", meta.Category); } if (meta.Order.HasValue) { Set("Order", meta.Order.Value); } if (meta.ReadOnly.HasValue) { Set("ReadOnly", meta.ReadOnly.Value); } if (!string.IsNullOrEmpty(meta.Tooltip)) { Set("Tooltip", meta.Tooltip); } if (meta.Hidden.GetValueOrDefault()) { Set("Browsable", false); } if (meta.IsAdvanced) { Set("IsAdvanced", true); } if (meta.IsAdmin) { Set("IsAdminOnly", true); } return attr; void Set(string name, object val) { cmAttrType2.GetProperty(name, BindingFlags.Instance | BindingFlags.Public)?.SetValue(attr, val, null); } } } public static class ConfigHelpers { public sealed class UiMetaTag { public AcceptableValueBase AcceptableValues { get; set; } public bool IsAdmin { get; set; } public bool IsAdvanced { get; set; } public string Category { get; set; } public int? Order { get; set; } public bool? ReadOnly { get; set; } public bool? Hidden { get; set; } public string Tooltip { get; set; } public bool Synchronized { get; set; } } public static ConfigDescription CreateConfigDescription(string description, bool isSynchronized = true, bool isAdvanced = false, AcceptableValueBase acceptableValues = null, string category = null, int? order = null, bool? readOnly = null, bool? hidden = null, string tooltip = null) { //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Expected O, but got Unknown //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Expected O, but got Unknown UiMetaTag uiMetaTag = new UiMetaTag { IsAdmin = isSynchronized, IsAdvanced = isAdvanced, Category = category, Order = order, ReadOnly = readOnly, Hidden = hidden, Tooltip = tooltip, Synchronized = isSynchronized, AcceptableValues = acceptableValues }; object obj = BuildConfigurationManagerAttributes(FindConfigurationManagerAttributesType(), uiMetaTag); object[] array = ((obj == null) ? new object[1] { uiMetaTag } : new object[2] { uiMetaTag, obj }); if (acceptableValues == null) { return new ConfigDescription(description ?? string.Empty, (AcceptableValueBase)null, array); } return new ConfigDescription(description ?? string.Empty, acceptableValues, array); } private static Type FindConfigurationManagerAttributesType() { string[] array = new string[3] { "ConfigurationManager.Attributes.ConfigurationManagerAttributes, ConfigurationManager", "ConfigurationManager.ConfigurationManagerAttributes, ConfigurationManager", "ConfigurationManager.ConfigurationManagerAttributes, BepInEx.ConfigurationManager" }; for (int i = 0; i < array.Length; i++) { Type type = Type.GetType(array[i], throwOnError: false); if (type != null) { return type; } } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { try { Type type2 = assembly.GetTypes().FirstOrDefault((Type x) => x.Name == "ConfigurationManagerAttributes"); if (type2 != null && type2.IsClass && !type2.IsAbstract) { return type2; } } catch { } } return null; } private static object BuildConfigurationManagerAttributes(Type cmAttrType, UiMetaTag meta) { Type cmAttrType2 = cmAttrType; if (cmAttrType2 == null) { return null; } object attr = Activator.CreateInstance(cmAttrType2); if (attr == null) { return null; } if (!string.IsNullOrEmpty(meta.Category)) { SetIf("Category", meta.Category); } if (meta.Order.HasValue) { SetIf("Order", meta.Order.Value); } if (meta.ReadOnly.HasValue) { SetIf("ReadOnly", meta.ReadOnly.Value); } if (!string.IsNullOrEmpty(meta.Tooltip)) { SetIf("Tooltip", meta.Tooltip); } if (meta.IsAdvanced) { SetIf("IsAdvanced", true); } if (meta.IsAdmin) { SetIf("IsAdminOnly", true); } if (meta.Hidden.GetValueOrDefault()) { SetIf("Browsable", false); } return attr; void SetIf(string name, object value) { PropertyInfo property = cmAttrType2.GetProperty(name, BindingFlags.Instance | BindingFlags.Public); if (property != null) { property.SetValue(attr, value, null); } } } } public class AnimatorIKRelay : MonoBehaviour { [CanBeNull] public IAnimatorIKRelayReceiver relayReceiver; private void LateUpdate() { relayReceiver?.OnAnimatorOverride(); } private void OnAnimatorIK(int layerIndex) { relayReceiver?.OnAnimatorIKRelay(layerIndex); } public void SetReceiver(IAnimatorIKRelayReceiver receiver) { relayReceiver = receiver; } } public static class ClassValidator { private const string ModIssuesPage = "https://github.com/zolantris/ValheimMods/issues"; public static bool ValidateRequiredNonNullFields(Type type, object? instance = null, string? context = null, Regex? skipRegex = null, bool canLog = true) { if (context == null) { context = type.Name; } bool result = true; if (instance != null) { result = ValidateInstanceFields(instance, context, skipRegex, canLog); } if (!ValidateStaticFields(type, context, skipRegex, canLog)) { result = false; } return result; } public static bool ValidateRequiredNonNullFields<T>(object? instance = null, string? context = null, Regex? skipRegex = null, bool canLog = true) { return ValidateRequiredNonNullFields(typeof(T), instance, context, skipRegex, canLog); } public static bool ValidateRequiredNonNullFields(object instance, string? context = null, bool skipStatic = true, Regex? skipRegex = null, bool canLog = true) { if (instance == null) { throw new ArgumentNullException("instance"); } Type type = instance.GetType(); if (context == null) { context = type.Name; } bool result = ValidateInstanceFields(instance, context, skipRegex, canLog); if (!skipStatic && !ValidateStaticFields(type, context, skipRegex, canLog)) { result = false; } return result; } private static bool ValidateStaticFields(Type type, string context, Regex? skipRegex = null, bool canLog = true) { FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public); bool result = true; FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { if (ShouldSkip(fieldInfo)) { continue; } object value = fieldInfo.GetValue(null); if ((skipRegex == null || !skipRegex.IsMatch(fieldInfo.Name)) && value == null) { if (canLog) { LoggerProvider.LogWarning("[" + context + "] Static field '" + fieldInfo.Name + "' is null. This can cause a null reference exception in code.", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\ClassValidator.cs", 88); } result = false; } } return result; } private static bool ValidateInstanceFields(object instance, string context, Regex? skipRegex = null, bool canLog = true) { FieldInfo[] fields = instance.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); bool result = true; FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { if (ShouldSkip(fieldInfo) || fieldInfo.IsDefined(typeof(CompilerGeneratedAttribute), inherit: false)) { continue; } object value = fieldInfo.GetValue(instance); if ((skipRegex == null || !skipRegex.IsMatch(fieldInfo.Name)) && value == null) { if (canLog) { LoggerProvider.LogError("[" + context + "] Instance field '" + fieldInfo.Name + "' is null. Report this issue to https://github.com/zolantris/ValheimMods/issues", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\ClassValidator.cs", 116); } result = false; } } return result; } private static bool ShouldSkip(FieldInfo field) { return field.IsDefined(typeof(SkipValidationAttribute), inherit: false); } } public class CoroutineHandle { [CompilerGenerated] private sealed class <Wrap>d__12 : IEnumerator<object>, IEnumerator, IDisposable { private int <>1__state; private object <>2__current; public IEnumerator routine; public CoroutineHandle <>4__this; object IEnumerator<object>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <Wrap>d__12(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -3; } else { <>1__state = -1; <>1__state = -3; } try { if (!routine.MoveNext()) { goto IL_0073; } } catch (Exception arg) { LoggerProvider.LogError($"[CoroutineHandle] Exception in coroutine: {arg}", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\CoroutineHandler.cs", 80); goto IL_0073; } <>2__current = routine.Current; <>1__state = 1; return true; IL_0073: <>m__Finally1(); return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; <>4__this.Instance = null; } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CanBeNull] private readonly MonoBehaviour _owner; public bool IsRunning => Instance != null; public Coroutine Instance { get; private set; } public CoroutineHandle(MonoBehaviour owner) { _owner = owner; } public MonoBehaviour GetOwner() { return _owner; } public bool IsValid(MonoBehaviour? instance) { if ((Object)(object)instance == (Object)null) { return false; } if (!Object.op_Implicit((Object)(object)_owner)) { return false; } if ((Object)(object)instance != (Object)(object)_owner) { return false; } return true; } public void Start(IEnumerator routine, bool shouldStop = true) { if (shouldStop) { Stop(); } if (!IsRunning && (Object)(object)_owner != (Object)null) { Instance = _owner.StartCoroutine(Wrap(routine)); } } public void Stop() { if (Instance != null) { if ((Object)(object)_owner != (Object)null) { _owner.StopCoroutine(Instance); } Instance = null; } } [IteratorStateMachine(typeof(<Wrap>d__12))] private IEnumerator Wrap(IEnumerator routine) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <Wrap>d__12(0) { <>4__this = this, routine = routine }; } } public static class HarmonyHelper { private const bool IsDebug = false; public static void TryPatchAll(Harmony harmonyInstance, Type type) { try { harmonyInstance.PatchAll(type); } catch (Exception arg) { LoggerProvider.LogError($"[Harmony] Failed to patch: {type.Name}\n{arg}", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\HarmonyHelpers.cs", 32); } } public static void TryPatchAll(Harmony harmonyInstance, params Type[] patchTypes) { foreach (Type type in patchTypes) { TryPatchAll(harmonyInstance, type); } } } public struct JointPose { [CanBeNull] public Transform transform; public Vector3 Position; public Quaternion Rotation; public JointPose(Vector3 pos, Quaternion rot, Transform tr = null) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) transform = tr; Position = pos; Rotation = rot; } public override string ToString() { return $"new JointPose(new Vector3({Position.x}f, {Position.y}f, {Position.z}f), new Quaternion({Rotation.x}f, {Rotation.y}f, {Rotation.z}f, {Rotation.w}f))"; } } public static class JointPoseDumpUtility { public static Dictionary<string, JointPose> ComputeDeltaPose(Dictionary<string, JointPose> basePose, Dictionary<string, JointPose> otherPose, float positionEpsilon = 0.01f, float rotationEpsilon = 0.01f) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) Dictionary<string, JointPose> dictionary = new Dictionary<string, JointPose>(); foreach (KeyValuePair<string, JointPose> item in otherPose) { bool flag = true; if (basePose.TryGetValue(item.Key, out var value)) { Vector3 val = item.Value.Position - value.Position; bool num = ((Vector3)(ref val)).sqrMagnitude > positionEpsilon * positionEpsilon; bool flag2 = Quaternion.Angle(item.Value.Rotation, value.Rotation) > rotationEpsilon; flag = num || flag2; } if (flag) { dictionary[item.Key] = item.Value; } } return dictionary; } public static void DumpDeltaPoseToFile(Dictionary<string, JointPose> basePose, Dictionary<string, JointPose> otherPose, string deltaName, string outputDir = null) { DumpPoseToFile(ComputeDeltaPose(basePose, otherPose), deltaName, outputDir); } public static void DumpPoseToFile(Dictionary<string, JointPose> poseDict, string modelName, string outputDir = null) { //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) string text = modelName.Replace(" ", "_").Replace("-", "_"); string text2 = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss"); string text3 = "ModelJointPoseSnapshot_" + text + "_" + text2; string path = "unity-model-poses-export"; string path2 = text + ".cs"; if (string.IsNullOrEmpty(outputDir)) { outputDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); } outputDir = Path.Combine(outputDir, path); if (!Directory.Exists(outputDir)) { Directory.CreateDirectory(outputDir); } string path3 = Path.Combine(outputDir, path2); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("// Auto-generated model pose snapshot"); stringBuilder.AppendLine("using UnityEngine;"); stringBuilder.AppendLine(); stringBuilder.AppendLine("public static class CustomAnimationPoses"); stringBuilder.AppendLine("{"); stringBuilder.AppendLine(" public static readonly System.Collections.Generic.Dictionary<string, JointPose> " + text3 + " = new() {"); foreach (KeyValuePair<string, JointPose> item in poseDict) { Vector3 position = item.Value.Position; Quaternion rotation = item.Value.Rotation; stringBuilder.AppendLine($" [\"{item.Key}\"] = new JointPose(new Vector3({position.x}f, {position.y}f, {position.z}f), new Quaternion({rotation.x}f, {rotation.y}f, {rotation.z}f, {rotation.w}f)),"); } stringBuilder.AppendLine(" };"); stringBuilder.AppendLine("}"); File.WriteAllText(path3, stringBuilder.ToString()); } } public static class LayerHelpers { public const int CustomRaftLayer = 29; public static int TerrainLayer = LayerMask.NameToLayer("terrain"); public static int UILayer = LayerMask.NameToLayer("UI"); public static int PieceLayer = LayerMask.NameToLayer("piece"); public static int DefaultLayer = LayerMask.NameToLayer("Default"); public static int DefaultSmallLayer = LayerMask.NameToLayer("Default_small"); public static int ItemLayer = LayerMask.NameToLayer("item"); public static int HitboxLayer = LayerMask.NameToLayer("hitbox"); public static LayerMask CustomRaftLayerMask = LayerMask.op_Implicit(LayerMask.GetMask(new string[1] { LayerMask.LayerToName(29) })); public static LayerMask PieceLayerMask = LayerMask.op_Implicit(LayerMask.GetMask(new string[1] { "piece" })); public static LayerMask PieceAndCustomVehicleMask = LayerMask.op_Implicit(LayerMask.GetMask(new string[2] { "piece", LayerMask.LayerToName(29) })); public static LayerMask PhysicalLayerMask = LayerMask.op_Implicit(LayerMask.GetMask(new string[9] { "Default", "character", "piece", "terrain", "static_solid", "Default_small", "character_net", "vehicle", LayerMask.LayerToName(29) })); public static LayerMask GroundLayers = LayerMask.op_Implicit(LayerMask.GetMask(new string[5] { "Default", "piece", "terrain", "static_solid", "Default_small" })); public static LayerMask OnboardLayers = LayerMask.op_Implicit(LayerMask.GetMask(new string[2] { "item", "character" })); public static string SmokeLayerString = LayerMask.LayerToName(31); public static LayerMask BlockingColliderExcludeLayers = LayerMask.op_Implicit(LayerMask.GetMask(new string[7] { "character", "character_net", "character_trigger", "viewbox", "character_nonenv", LayerMask.LayerToName(29), SmokeLayerString })); public static LayerMask CannonHitLayers = LayerMask.op_Implicit(LayerMask.GetMask(new string[11] { "character", "character_net", "character_ghost", "character_noenv", "Default", "Default_small", "hitbox", "piece", "static_solid", "terrain", "vehicle" })); public static LayerMask CannonBlockingSiteHitLayers = LayerMask.op_Implicit(LayerMask.GetMask(new string[7] { "Default", "Default_small", "piece", "terrain", "character", "character_net", "character_noenv" })); public static List<string> ActiveLayersForBlockingMask = new List<string>(); public static int PieceNonSolidLayer = LayerMask.NameToLayer("piece_nonsolid"); public static int IgnoreRaycastLayer = LayerMask.NameToLayer("Ignore Raycast"); public static LayerMask RamColliderExcludeLayers = LayerMask.op_Implicit(LayerMask.GetMask(new string[12] { "character_trigger", "viewbox", "character_nonenv", "UI", "effect", "ghost", "piece_nonsolid", "Water", "WaterVolume", "skybox", "hitbox", "character_ghost" })); public static int CharacterLayer = LayerMask.NameToLayer("character"); public static int CharacterTriggerLayer = LayerMask.NameToLayer("character_trigger"); public static int CharacterLayerMask = LayerMask.GetMask(new string[3] { "character", "character_net", "character_nonenv" }); public static bool IsItemLayer(int layer) { return layer == ItemLayer; } public static bool IsContainedWithinLayerMask(int layer, LayerMask mask) { return (((LayerMask)(ref mask)).value & (1 << layer)) != 0; } public static Func<Collider, bool> IsContainedWithinLayerMaskPredicate(LayerMask mask) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) return (Collider c) => (Object)(object)c != (Object)null && ((1 << ((Component)c).gameObject.layer) & ((LayerMask)(ref mask)).value) != 0; } [UsedImplicitly] public static List<int> GetActiveLayers(LayerMask mask, string layerVariant = "activeLayers") { List<int> list = new List<int>(); List<string> list2 = new List<string>(); for (int i = 0; i < 32; i++) { if ((((LayerMask)(ref mask)).value & (1 << i)) != 0) { string item = LayerMask.LayerToName(i); list2.Add(item); list.Add(i); } } return list; } [UsedImplicitly] public static void PrintAllLayers() { LoggerProvider.LogDebug("Listing All Runtime game layers", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\LayerHelpers.cs", 120); for (int i = 0; i < 32; i++) { string text = LayerMask.LayerToName(i); if (!string.IsNullOrEmpty(text)) { LoggerProvider.LogDebugDebounced($"Layer {i}: {text}", 5f, "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\LayerHelpers.cs", 126); } } } public static LayerMask CombineLayerMask(LayerMask originalMask, int layerToAdd) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) return LayerMask.op_Implicit(LayerMask.op_Implicit(originalMask) | (1 << layerToAdd)); } } public static class LoggerProvider { public static LogLevel ActiveLogLevel = (LogLevel)63; private static ManualLogSource? Logger; private static LogLevel GlobalLogLevel = (LogLevel)63; private static bool _hasInitialized; private static readonly Dictionary<string, string> _callerCache = new Dictionary<string, string>(); private static readonly Dictionary<string, float> _lastLogTimestamps = new Dictionary<string, float>(); private static float GetTime() { return Time.realtimeSinceStartup; } public static void Setup(ManualLogSource? logger) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) if (_hasInitialized) { Debug.LogWarning((object)"LoggerProvider: Setup called more than once. Ignoring duplicate initialization."); return; } _hasInitialized = true; Logger = (ManualLogSource?)(((object)logger) ?? ((object)new ManualLogSource("ValheimVehiclesLoggerProviderFallback"))); GlobalLogLevel = ReadBepInExConsoleLogLevel(); LogInfo($"Logger initialized. Plugin Level: {ActiveLogLevel}, Global Level: {GlobalLogLevel}", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\LoggerProvider.cs", 53); } public static void LogError(string val, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { if (IsLevelEnabled((LogLevel)2)) { SafeLog((LogLevel)2, Format("Error", val, file, line)); } } public static void LogWarning(string val, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { if (IsLevelEnabled((LogLevel)4)) { SafeLog((LogLevel)4, Format("Warning", val, file, line)); } } [Conditional("DEBUG")] public static void LogDev(string val, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { if (IsLevelEnabled((LogLevel)32)) { SafeLog((LogLevel)32, Format("Dev", val, file, line)); } } public static void LogDebug(string val, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { if (IsLevelEnabled((LogLevel)32)) { SafeLog((LogLevel)32, Format("Debug", val, file, line)); } } public static void LogMessage(string val, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { if (IsLevelEnabled((LogLevel)8)) { SafeLog((LogLevel)8, Format("Message", val, file, line)); } } public static void LogInfo(string val, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { if (IsLevelEnabled((LogLevel)16)) { SafeLog((LogLevel)16, Format("Info", val, file, line)); } } private static bool IsLevelEnabled(LogLevel level) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Invalid comparison between Unknown and I4 //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Invalid comparison between Unknown and I4 //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) if ((int)ActiveLogLevel == 0 || (int)GlobalLogLevel == 0) { return false; } if ((int)ActiveLogLevel == 63 && (int)GlobalLogLevel == 63) { return true; } if (level <= ActiveLogLevel) { return level <= GlobalLogLevel; } return false; } private static void SafeLog(LogLevel level, string message) { //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Invalid comparison between Unknown and I4 //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Invalid comparison between Unknown and I4 //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Invalid comparison between Unknown and I4 //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Invalid comparison between Unknown and I4 //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected I4, but got Unknown //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Invalid comparison between Unknown and I4 //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Invalid comparison between Unknown and I4 //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Invalid comparison between Unknown and I4 //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Invalid comparison between Unknown and I4 //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Invalid comparison between Unknown and I4 try { if (Logger != null) { if ((int)level <= 8) { switch (level - 1) { default: if ((int)level != 8) { break; } Logger.LogMessage((object)message); return; case 0: Logger.LogFatal((object)message); return; case 1: Logger.LogError((object)message); return; case 3: Logger.LogWarning((object)message); return; case 2: break; } } else { if ((int)level == 16) { Logger.LogInfo((object)message); return; } if ((int)level == 32) { Logger.LogDebug((object)message); return; } } Logger.LogMessage((object)message); return; } if ((int)level <= 4) { if (level - 1 <= 1) { Debug.LogError((object)message); return; } if ((int)level == 4) { Debug.LogWarning((object)message); return; } } else { if ((int)level == 8 || (int)level == 16) { Debug.Log((object)message); return; } if ((int)level == 32) { return; } } Debug.Log((object)message); } catch (Exception ex) { Debug.LogWarning((object)("LoggerProvider: Failed to log message. Exception: " + ex.Message + "\nOriginalMessage: " + message)); } } private static string Format(string logType, string message, string file, int line) { string key = $"{file}:{line}"; if (!_callerCache.TryGetValue(key, out string value)) { MethodBase? obj = new StackTrace(2, fNeedFileInfo: true).GetFrame(0)?.GetMethod(); Type type = obj?.DeclaringType; string text; if (type == null) { text = "UnknownType"; } else if (type.IsGenericType) { string name = type.Name; int num = name.IndexOf('`'); string obj2 = ((num >= 0) ? name.Substring(0, num) : name); string[] value2 = (from t in type.GetGenericArguments() select t.Name).ToArray(); text = obj2 + "<" + string.Join(", ", value2) + ">"; } else { text = type.Name; } string text2 = obj?.Name ?? "UnknownMethod"; string fileName = Path.GetFileName(file); value = $"[{text}.{fileName}:{line} ({text2})]"; _callerCache[key] = value; } return logType + ":" + value + " " + message; } public static void LogDevDebounced(string val, float debounceSeconds = 5f, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { if (IsLevelEnabled((LogLevel)32) && !ShouldDebounce($"Dev:{file}:{line}:{val.GetHashCode()}", debounceSeconds)) { SafeLog((LogLevel)16, Format("Dev", val, file, line)); } } public static void LogDebugDebounced(string val, float debounceSeconds = 5f, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { if (IsLevelEnabled((LogLevel)32) && !ShouldDebounce($"Debug:{file}:{line}:{val.GetHashCode()}", debounceSeconds)) { SafeLog((LogLevel)16, Format("Debug", val, file, line)); } } public static void LogInfoDebounced(string val, float debounceSeconds = 5f, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { if (IsLevelEnabled((LogLevel)16) && !ShouldDebounce($"INFO:{file}:{line}:{val.GetHashCode()}", debounceSeconds)) { SafeLog((LogLevel)16, Format("Info", val, file, line)); } } public static void LogInfoDebounced(string key, string message, float debounceSeconds = 5f, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { if (!ShouldDebounce($"INFO:{file}:{line}:{key}", debounceSeconds)) { SafeLog((LogLevel)16, Format("Info", message, file, line)); } } private static bool ShouldDebounce(string key, float debounceSeconds) { float time = GetTime(); if (_lastLogTimestamps.TryGetValue(key, out var value) && time - value < debounceSeconds) { return true; } _lastLogTimestamps[key] = time; return false; } private static LogLevel ReadBepInExConsoleLogLevel() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) try { string text = Path.Combine(Paths.ConfigPath, "BepInEx.cfg"); if (!File.Exists(text)) { return (LogLevel)63; } ConfigEntry<string> val = default(ConfigEntry<string>); if (new ConfigFile(text, true).TryGetEntry<string>("Logging", "ConsoleDisplayedLevel", ref val) && Enum.TryParse<LogLevel>(val.Value, ignoreCase: true, out LogLevel result)) { return result; } } catch (Exception ex) { Debug.LogWarning((object)("LoggerProvider: Failed to read BepInEx.cfg console level. Defaulting to All. Exception: " + ex.Message)); } return (LogLevel)63; } } public interface IParticleSystemCollisionForwarder { void OnParticleCollisionEvent(GameObject other, [CanBeNull] List<ParticleCollisionEvent> collisionEvent); } [RequireComponent(typeof(ParticleSystem))] public class ParticleSystem_CollisionForwarder : MonoBehaviour { private ParticleSystem _ps; public IParticleSystemCollisionForwarder _forwarder; private readonly List<ParticleCollisionEvent> _events = new List<ParticleCollisionEvent>(); public bool ShouldCollectEvents; private void Awake() { _ps = ((Component)this).GetComponent<ParticleSystem>(); _forwarder = ((Component)this).GetComponentInParent<IParticleSystemCollisionForwarder>(); } public void SetForwarder(IParticleSystemCollisionForwarder forwarder) { _forwarder = forwarder; } private void OnParticleCollision(GameObject other) { if (ShouldCollectEvents) { ParticlePhysicsExtensions.GetCollisionEvents(_ps, other, _events); } List<ParticleCollisionEvent> list = (ShouldCollectEvents ? _events : null); _forwarder?.OnParticleCollisionEvent(other, list); LoggerProvider.LogDebug($"[ParticleSystem_CollisionForwarder] hit {((Object)other).name} events={list}", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\ParticleSystem_CollisionForwarder.cs", 41); } } public class RuntimeDebugLineDrawer : SingletonBehaviour<RuntimeDebugLineDrawer> { private class LineInstance { public bool active; public float expiry; public LineRenderer renderer; } private static GameObject _singletonObject; public static Material DebugRayMaterial; public static bool IsEnabled = false; public static bool HasMaterialColorOverride = true; public static Color TRed = new Color(1f, 0f, 0f, 0.75f); public static Color TGreen = new Color(0f, 1f, 0f, 0.75f); public static Color TBlue = new Color(0f, 0.5f, 1f, 0.75f); public static Color TOrange = new Color(1f, 0.5f, 0f, 0.75f); public static Color TYellow = new Color(1f, 1f, 0f, 0.75f); private readonly Queue<LineInstance> _linePool = new Queue<LineInstance>(); private readonly List<LineInstance> _lines = new List<LineInstance>(); private Material _defaultMat; private void Update() { if (!IsEnabled) { return; } float realtimeSinceStartup = Time.realtimeSinceStartup; for (int i = 0; i < _lines.Count; i++) { LineInstance lineInstance = _lines[i]; if (lineInstance.active && realtimeSinceStartup > lineInstance.expiry) { ((Renderer)lineInstance.renderer).enabled = false; lineInstance.active = false; _linePool.Enqueue(lineInstance); } } } public override void OnAwake() { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown if ((Object)(object)_defaultMat == (Object)null) { if ((Object)(object)DebugRayMaterial == (Object)null) { Shader val = Shader.Find("Sprites/Default"); _defaultMat = new Material(val) { color = Color.white, renderQueue = 3000 }; } else { _defaultMat = DebugRayMaterial; _defaultMat.renderQueue = 3000; } } } private static void Init() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown if (IsEnabled) { _singletonObject = new GameObject("RuntimeDebugLineDrawer_Singleton", new Type[1] { typeof(RuntimeDebugLineDrawer) }); SingletonBehaviour<RuntimeDebugLineDrawer>.Instance = _singletonObject.GetComponent<RuntimeDebugLineDrawer>(); Object.DontDestroyOnLoad((Object)(object)_singletonObject); } } public static void DrawLine(Vector3 start, Vector3 end, Color color, float duration = 0.1f, float width = 0.04f) { //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) if (!IsEnabled) { return; } if ((Object)(object)SingletonBehaviour<RuntimeDebugLineDrawer>.Instance == (Object)null) { Init(); } if ((Object)(object)SingletonBehaviour<RuntimeDebugLineDrawer>.Instance == (Object)null || !((Behaviour)SingletonBehaviour<RuntimeDebugLineDrawer>.Instance).isActiveAndEnabled) { return; } LineInstance lineInstance = null; while (SingletonBehaviour<RuntimeDebugLineDrawer>.Instance._linePool.Count > 0 && lineInstance == null) { LineInstance lineInstance2 = SingletonBehaviour<RuntimeDebugLineDrawer>.Instance._linePool.Dequeue(); if (Object.op_Implicit((Object)(object)lineInstance2.renderer)) { lineInstance = lineInstance2; } } if (lineInstance == null) { GameObject val = new GameObject("[DebugLine]"); val.transform.SetParent(((Component)SingletonBehaviour<RuntimeDebugLineDrawer>.Instance).transform, false); LineRenderer val2 = val.AddComponent<LineRenderer>(); ((Renderer)val2).material = SingletonBehaviour<RuntimeDebugLineDrawer>.Instance._defaultMat; val2.positionCount = 2; val2.startWidth = width; val2.endWidth = width; ((Renderer)val2).shadowCastingMode = (ShadowCastingMode)0; ((Renderer)val2).receiveShadows = false; val2.useWorldSpace = true; lineInstance = new LineInstance { renderer = val2 }; SingletonBehaviour<RuntimeDebugLineDrawer>.Instance._lines.Add(lineInstance); } lineInstance.active = true; lineInstance.expiry = Time.realtimeSinceStartup + Mathf.Max(0.016f, duration); ((Renderer)lineInstance.renderer).enabled = true; lineInstance.renderer.SetPosition(0, start); lineInstance.renderer.SetPosition(1, end); if (HasMaterialColorOverride) { ((Renderer)lineInstance.renderer).material.color = color; } lineInstance.renderer.startColor = color; lineInstance.renderer.endColor = color; lineInstance.renderer.startWidth = width; lineInstance.renderer.endWidth = width; } public static void ClearAll() { if ((Object)(object)SingletonBehaviour<RuntimeDebugLineDrawer>.Instance == (Object)null || SingletonBehaviour<RuntimeDebugLineDrawer>.Instance._lines.Count == 0) { return; } foreach (LineInstance line in SingletonBehaviour<RuntimeDebugLineDrawer>.Instance._lines) { if (Object.op_Implicit((Object)(object)line.renderer)) { ((Renderer)line.renderer).enabled = false; } line.active = false; SingletonBehaviour<RuntimeDebugLineDrawer>.Instance._linePool.Enqueue(line); } } } public static class ServerSyncConfigSyncUtil { private static readonly HashSet<ConfigEntryBase> RegisteredEntries = new HashSet<ConfigEntryBase>(); private static readonly HashSet<string> RegisteredKeys = new HashSet<string>(); public static void RegisterAllConfigEntries(ConfigSync sync, Type configType) { FieldInfo[] fields = configType.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); foreach (FieldInfo fieldInfo in fields) { object? value = fieldInfo.GetValue(null); ConfigEntryBase val = (ConfigEntryBase)((value is ConfigEntryBase) ? value : null); if (val == null) { continue; } string text = val.Definition.Section + "." + val.Definition.Key; if (!RegisteredEntries.Add(val)) { LoggerProvider.LogWarning("[ServerSync] DUPLICATE ConfigEntry instance skipped: " + text + " (Field: " + fieldInfo.Name + ", Type: " + configType.FullName + ")", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\ServerSyncConfigSyncUtil.cs", 27); continue; } if (!RegisteredKeys.Add(text)) { LoggerProvider.LogWarning("[ServerSync] DUPLICATE Config key skipped: " + text + " (Field: " + fieldInfo.Name + ", Type: " + configType.FullName + ")", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\ServerSyncConfigSyncUtil.cs", 34); continue; } Type type = ((object)val).GetType(); if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ConfigEntry<>)) { Type type2 = type.GetGenericArguments()[0]; MethodInfo methodInfo = typeof(ConfigSync).GetMethod("AddConfigEntry")?.MakeGenericMethod(type2); if (methodInfo != null) { methodInfo.Invoke(sync, new object[1] { val }); LoggerProvider.LogDebug("[ServerSync] Registered config: " + text, "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\ServerSyncConfigSyncUtil.cs", 48); } else { LoggerProvider.LogWarning($"[ServerSync] Could not resolve AddConfigEntry<{type2}> for config key: {text}", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\ServerSyncConfigSyncUtil.cs", 52); } } else { LoggerProvider.LogWarning("[ServerSync] Skipped non-generic config entry: " + text, "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\ServerSyncConfigSyncUtil.cs", 57); } } } } public class SingletonBehaviour<T> : MonoBehaviour where T : SingletonBehaviour<T> { public static T? Instance { get; protected set; } public static event Action? OnPostAwake; public virtual void Awake() { if ((Object)(object)Instance != (Object)null && (Object)(object)Instance != (Object)(object)this) { Object.Destroy((Object)(object)((Component)this).gameObject); return; } Instance = (T)this; Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject); OnAwake(); SingletonBehaviour<T>.OnPostAwake?.Invoke(); } protected virtual void OnDestroy() { if ((Object)(object)Instance == (Object)(object)this) { Instance = null; } } public virtual void OnAwake() { } } [AttributeUsage(AttributeTargets.Field)] public sealed class SkipValidationAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class MeasureTimeAttribute : Attribute { } public static class TimerUtility { public static void ExecuteWithTiming(Action action, [CallerMemberName] string methodName = "") { } public static void MeasureTimeWithAttribute(object instance, string methodName) { object instance2 = instance; MethodInfo method = instance2.GetType().GetMethod(methodName); if ((object)method != null && method.GetCustomAttribute<MeasureTimeAttribute>() != null) { ExecuteWithTiming(delegate { method.Invoke(instance2, null); }, methodName); } else { method?.Invoke(instance2, null); } } } public class BatchedLogger : MonoBehaviour { private static BatchedLogger? _instance; private static readonly Queue<string> _logQueue = new Queue<string>(); private float _timer; public static bool IsLoggingEnabled { get; set; } = true; [UsedImplicitly] public static float BatchIntervalFrequencyInSeconds { get; set; } = 3f; public static BatchedLogger Instance { get { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown if (_instance == null) { GameObject val = new GameObject("Logger"); _instance = val.AddComponent<BatchedLogger>(); Object.DontDestroyOnLoad((Object)val); } return _instance; } } public void Log(string message) { _logQueue.Enqueue(message); } private void FlushLogs() { while (_logQueue.Count > 0) { LoggerProvider.LogInfoDebounced(_logQueue.Dequeue(), 5f, "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\WithMethodDebugger.cs", 96); } } } } namespace Zolantris.Shared.Debug { public class DebugSafeTimer { private bool _isRunning; private float _elapsedTime; private List<DebugSafeTimer>? _listRef; public float ElapsedMilliseconds => _elapsedTime * 1000f; public static DebugSafeTimer StartNew() { DebugSafeTimer debugSafeTimer = new DebugSafeTimer(); debugSafeTimer.Start(); return debugSafeTimer; } public static DebugSafeTimer StartNew(List<DebugSafeTimer> list) { DebugSafeTimer debugSafeTimer = new DebugSafeTimer(); debugSafeTimer.Start(); list.Add(debugSafeTimer); debugSafeTimer._listRef = list; return debugSafeTimer; } public static void UpdateTimersFromList(List<DebugSafeTimer> list) { if (list.Count == 0) { return; } DebugSafeTimer[] array = list.ToArray(); foreach (DebugSafeTimer debugSafeTimer in array) { if (debugSafeTimer != null) { debugSafeTimer.Update(); } else if (debugSafeTimer == null) { list.Remove(debugSafeTimer); } } } [UsedImplicitly] public void Start() { if (_listRef != null && !_listRef.Contains(this)) { _listRef.Add(this); } _isRunning = true; } [UsedImplicitly] public void Stop() { _isRunning = false; } [UsedImplicitly] public void Reset() { if (_listRef != null && _listRef.Contains(this)) { _listRef.Remove(this); } _elapsedTime = 0f; Stop(); } [UsedImplicitly] public void Restart() { _elapsedTime = 0f; Start(); } [UsedImplicitly] public void Clear() { Reset(); if (_listRef == null) { LoggerProvider.LogDebug("Called delete but listRef did not exist", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\DebugSafeTimer.cs", 109); } else { _listRef?.Remove(this); } } private void OnUpdateAutoExpire() { if (ElapsedMilliseconds > 20000f) { Clear(); } } [UsedImplicitly] private void Update() { if (_isRunning) { _elapsedTime += Time.deltaTime; } OnUpdateAutoExpire(); } } } namespace Zolantris.Shared.ModIntegrations { public interface IModIntegrationApi { void RunIntegration(); } public static class ConditionalImporter { public static bool ImportConditionally(string modGuid, string targetClass) { Type type = Type.GetType("Namespace.ParentClassName"); if (type != null) { LoggerProvider.LogDebug("Conditional " + modGuid + " found. " + targetClass + " will now run", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\ConditionalImporter.cs", 20); (Activator.CreateInstance(type) as IModIntegrationApi)?.RunIntegration(); return true; } LoggerProvider.LogDebug("Conditional " + modGuid + " not found. Exiting", "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\ConditionalImporter.cs", 30); return false; } } } namespace Zolantris.Shared.BepInExAutoDoc { public class BepInExConfigAutoDoc { private static readonly Regex ConfigMatchRegExp = new Regex("\\[(.*?)\\]"); public bool runOnDebug = true; public bool runOnRelease; private static string? GetOutputFolderPath(PluginInfo plugin, string autoDocName) { string directoryName = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location); string directoryName2 = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); LoggerProvider.LogDebug("BepInExConfigAutoDoc: GetOutputFolderPath() " + directoryName, "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\BepInExAutoDoc.cs", 29); LoggerProvider.LogDebug("BepInExConfigAutoDoc: GetOutputFolderPath() executingAssemblyLocation " + directoryName2, "C:\\Users\\fre\\dev\\repos\\ValheimMods\\src\\Shared\\Zolantris.Shared\\BepInExAutoDoc.cs", 31); if (directoryName2 == null) { return null; } return Path.Combine(directoryName2, autoDocName + "_AutoDoc.md"); } private static string StripString(string x) { return ConfigMatchRegExp.Match(x).Groups[1].Value; } private static void AutoWriteBepInExConfigDoc(PluginInfo plugin, ConfigFile Config, string documentName) { StringBuilder stringBuilder = new StringBuilder(); string text = ""; foreach (ConfigDefinition key in Config.Keys) { if (key.Section != text) { text = key.Section; stringBuilder.Append(Environment.NewLine + "## " + key.Section + Environment.NewLine); } stringBuilder.Append(("\n### " + key.Key + " [" + StripString(Config[key].Description.Description) + "]").Replace("[]", "") + Environment.NewLine + "- Description: " + Config[key].Description.Description.Replace("[Synced with Server]", "").Replace("[Not Synced with Server]", "") + $"{Environment.NewLine}- Default Value: {Config[key].DefaultValue}{Environment.NewLine}"); } string outputFolderPath = GetOutputFolderPath(plugin, documentName); if (outputFolderPath != null) { File.WriteAllText(outputFolderPath, stringBuilder.ToString()); } } public void Generate(PluginInfo pluginInfo, ConfigFile configFile, string documentName) { AutoWriteBepInExConfigDoc(pluginInfo, configFile, documentName); } } } namespace Zolantris.Shared.Interfaces { public interface IAnimatorIKRelayReceiver { void OnAnimatorIKRelay(int layerIndex); void OnAnimatorOverride(); } }